<?php
include '../includes/config.php';
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<?php
$stmt_invoice = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM stock_sale;");
$stmt_invoice->execute();
$row_invoice = $stmt_invoice->fetch(PDO::FETCH_ASSOC);
$invoice_number = $row_invoice['max_invoice'];

$stmt_customer = $conn->prepare("SELECT contacts.name, stock_sale.user_id, stock_sale.date_sale, stock_sale.sales_man, stock_sale.order_tax FROM contacts
INNER JOIN stock_sale ON contacts.id = stock_sale.customer_id
WHERE stock_sale.invoice = :invoice_number;");
$stmt_customer->bindParam(':invoice_number', $invoice_number);
$stmt_customer->execute();
$row_customer = $stmt_customer->fetch(PDO::FETCH_ASSOC);

if ($row_customer) {
    $user_id = $row_customer['user_id'];

    $stmt_user = $conn->prepare("SELECT user_name FROM users WHERE id = :user_id");
    $stmt_user->bindParam(':user_id', $user_id);
    $stmt_user->execute();
    $row_user = $stmt_user->fetch(PDO::FETCH_ASSOC);

    $sales_man_name = $row_user ? $row_user['user_name'] : 'N/A';
}

$order_tax_percentage = floatval($row_customer['order_tax']);

$stmt_products = $conn->prepare("
    SELECT 
        ss.*, 
        p.name AS product_name,
        p.serial_no,
        p.model_no,
        b.name AS brand_name,
        c.product_color,
        s.product_size,
        u.actual_name AS unit_name       -- Added unit
    FROM stock_sale ss
    JOIN products p ON ss.product_id = p.id
    LEFT JOIN brands b ON p.brand_id = b.id
    LEFT JOIN colors c ON p.color_id = c.id
    LEFT JOIN sizes s ON p.size_id = s.id
    LEFT JOIN units u ON p.unit_id = u.id       -- Join units table
    WHERE ss.invoice = :invoice_number
");



$stmt_products->bindParam(':invoice_number', $invoice_number);
$stmt_products->execute();

$total_order_tax = 0;
$total_amount_with_tax = 0;

$stmt = $conn->query("SELECT * FROM companies ORDER BY id DESC LIMIT 1");
$company = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>

<head>
    <title>Sales Receipt</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Crimson+Text&display=swap" rel="stylesheet">
    <style>
        /* ================== General Styles ================== */
        body {
            font-family: Consolas, Arial, sans-serif;
            background-color: #fff;
            padding: 0;
            margin: 0;
        }

        .container {
            width: 76mm;
            /* safe margin for 80mm printer */
            max-width: 76mm;
            margin: 0 auto;
            padding: 0;
            box-sizing: border-box;
        }

        h1,
        h2,
        h3,
        h4,
        p {
            text-align: center;
            color: #000;
            margin: 0;
            padding: 1px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            word-break: break-word;
            font-size: 10px;
        }

        table td,
        table th {
            padding: 0 1px;
            /* minimal padding */
            border: 1px solid #000;
            font-size: 10px;
            text-align: left;
            word-wrap: break-word;
            overflow-wrap: break-word;
            white-space: normal;
        }

        table th {
            background-color: #f0f0f0;
            font-weight: bold;
        }

        /* Column widths */
        td:nth-child(1),
        th:nth-child(1) {
            width: 12px;
        }

        /* Sr # */
        td:nth-child(2),
        th:nth-child(2) {
            max-width: 45px;
        }

        /* Item */
        td:nth-child(3),
        th:nth-child(3) {
            max-width: 20px;
        }

        /* Size */
        td:nth-child(4),
        th:nth-child(4) {
            max-width: 20px;
        }

        /* QTY */
        td:nth-child(5),
        th:nth-child(5) {
            max-width: 25px;
        }

        /* Price */
        td:nth-child(6),
        th:nth-child(6) {
            max-width: 25px;
        }

        /* S.Tax */
        td:nth-child(7),
        th:nth-child(7) {
            max-width: 25px;
        }

        /* Total */

        .total {
            text-align: right;
            font-weight: bold;
            margin-top: 1px;
            margin-bottom: 1px;
            font-size: 10px;
            margin-right: 0.1em;
        }

        .image_logo {
            display: block;
            margin: 0 auto;
            width: 50px;
        }

        /* ================== Print Styles ================== */
        @media print {
            @page {
                size: 80mm auto;
                margin: 0;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                background: #fff;
            }

            .container {
                width: 76mm;
                max-width: 76mm;
                margin: 0 auto;
                padding: 0;
                box-sizing: border-box;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                table-layout: fixed;
                word-break: break-word;
                font-size: 10px;
            }

            table td,
            table th {
                padding: 0 1px;
                border: 1px solid #000;
                font-size: 10px;
                white-space: normal;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }

            td:nth-child(1),
            th:nth-child(1) {
                width: 12px;
            }

            td:nth-child(2),
            th:nth-child(2) {
                max-width: 45px;
            }

            td:nth-child(3),
            th:nth-child(3) {
                max-width: 20px;
            }

            td:nth-child(4),
            th:nth-child(4) {
                max-width: 20px;
            }

            td:nth-child(5),
            th:nth-child(5) {
                max-width: 25px;
            }

            td:nth-child(6),
            th:nth-child(6) {
                max-width: 25px;
            }

            td:nth-child(7),
            th:nth-child(7) {
                max-width: 25px;
            }

            h1,
            h2,
            h3,
            h4,
            p {
                font-size: 10px;
                padding: 1px;
            }

            .total {
                font-size: 10px;
                margin-right: 0.1em;
            }

            .image_logo {
                width: 50px;
            }

            #back-link {
                display: none !important;
                visibility: hidden;
            }
        }
    </style>
</head>
<a href="../pos.php" id="back-link">Back POS</a>

<body>
    <div class="container" id="data">

        <h3 style=" 
    font-size: 21px; 
    font-weight: bold;
    display: flex; 
    flex-direction: column;
    align-items: center; 
    justify-content: center; 
    text-align: center; 
    margin: 0; 
    position: relative; 
">
            <?php if (!empty($company['logo'])): ?>
                <img class="image_logo"
                    src="../<?= htmlspecialchars($company['logo']) ?>"
                    alt="Logo"
                    style="
                width: 67px; 
                height: auto; 
                margin-bottom: 5px;
            ">
            <?php endif; ?>

            <?php if (!empty($company['name'])): ?>
                <span><?= htmlspecialchars($company['name']) ?></span>
            <?php endif; ?>
        </h3>

        <h4 style="display: flex; flex-direction: column; align-items: center; text-align: center; font-size: 13px; font-weight:bold; margin-top: 4px; margin-bottom:2px;">
            <?php if (!empty($company['address'])): ?>
                <span>Address: <?= htmlspecialchars($company['address']) ?></span>
            <?php endif; ?>

            <?php if (!empty($company['phone']) || !empty($company['email'])): ?>
                <span>
                    <?php if (!empty($company['phone'])): ?>
                        Phone: <?= htmlspecialchars($company['phone']) ?>
                    <?php endif; ?>
<br>
                    <?php if (!empty($company['phone']) && !empty($company['email'])): ?>
                        &nbsp;  &nbsp;
                    <?php endif; ?>

                    <?php if (!empty($company['email'])): ?>
                        Email: <?= htmlspecialchars($company['email']) ?>
                    <?php endif; ?>
                </span>
            <?php endif; ?>

        </h4>

        <!-- <p style="align-items: center; text-align: center;">ESTIMATE
        </p> -->
        <h1 style="display: flex; flex-direction: column; align-items: center; text-align: center; font-size: 13px;"><?php echo  date("l"); ?> &nbsp; <?php echo date("d/m/Y"); ?> &nbsp; <?php date_default_timezone_set('Asia/Karachi');
                                                                                                                                                                                            $current_time = date('h:i A');
                                                                                                                                                                                            echo $current_time; ?></h1>
        <p style="font-size: 13px;"><b>Invoice: <?php echo intval($invoice_number) ?></b> / <b id="salesMan" style="cursor: pointer;">SaleMan: <?= htmlspecialchars($sales_man_name) ?></b></p>

        <p style="font-size: 13px;"><b>Customer Name:<?php echo $row_customer['name']; ?> </b></p>
        <!--<p style="font-size: 14px;"><b>Customer Phone: <?php echo $row_customer['customer_phone']; ?></b></p>-->
        <script>
            function updateSalesMan() {
                var newSalesMan = prompt("Please enter the new SalesMan name:");

                if (newSalesMan) {
                    var invoiceNumber = <?php echo json_encode($invoice_number); ?>;

                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "update_salesman.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                alert(xhr.responseText);
                                location.reload();
                            } else {
                                alert("Error updating salesman: " + xhr.statusText);
                            }
                        }
                    };
                    xhr.send("invoice_number=" + invoiceNumber + "&sales_man=" + encodeURIComponent(newSalesMan));
                }
            }
        </script>

        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Item</th>
                    <!-- <th>Brand Name</th> -->
                    <th>QTY</th>
                    <th>Price</th>
                    <th>Total</th>
                </tr>
            </thead>

            <tbody>
                <?php
                $sr_number = 1;
                $total_qty = 0; // Total quantity counter
                $total_order_tax = 0;
                $total_amount_with_tax = 0;
                $subtotal_without_tax = 0;
                $total_tax_value = 0;

                while ($row_product = $stmt_products->fetch(PDO::FETCH_ASSOC)) {
                    $exclusive_value = floatval($row_product['price']) * floatval($row_product['sale_qty']);
                    $subtotal_without_tax += $exclusive_value;

                    $product_tax_percentage = floatval($row_product['sale_tax']);
                    $sales_tax_value = ($exclusive_value * $product_tax_percentage) / 100;
                    $total_with_tax = $exclusive_value + $sales_tax_value;
                    $total_tax_value += $sales_tax_value;

                    $total_order_tax += $sales_tax_value;
                    $total_amount_with_tax += $total_with_tax;

                    $qty = floatval($row_product['sale_qty']); // Convert quantity to float
                    $total_qty += $qty; // Accumulate total quantity
                ?>
                    <tr>
                        <td><?php echo $sr_number++; ?></td>
                        <td><?php echo htmlentities($row_product['product_name']); ?></td>
                        <!-- <td><?php echo htmlentities($row_product['brand_name'] ?? ''); ?></td> -->
                        <td><?php echo $row_product['sale_qty'] . ' ' . $row_product['unit_name']; ?></td>
                        <td><?php echo number_format($row_product['price'], 2); ?></td>
                        <td><?php echo number_format($exclusive_value, 2); ?></td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php
        include '../includes/config.php';

        $stmt_invoice = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM stock_sale;");
        $stmt_invoice->execute();
        $row_invoice = $stmt_invoice->fetch(PDO::FETCH_ASSOC);
        $invoice_number = $row_invoice['max_invoice'];

        $stmt_customer = $conn->prepare("
    SELECT contacts.name, contacts.business_id, contacts.type, contacts.id, 
           contacts.opening_balance, contacts.balance_status, stock_sale.order_tax
    FROM contacts
    INNER JOIN stock_sale ON contacts.id = stock_sale.customer_id
    WHERE stock_sale.invoice = :invoice_number;
");
        $stmt_customer->bindParam(':invoice_number', $invoice_number);
        $stmt_customer->execute();
        $row_customer = $stmt_customer->fetch(PDO::FETCH_ASSOC);

        $customer_id = $row_customer['id'];
        $opening_balance = floatval($row_customer['opening_balance']);
        $balance_status = strtolower($row_customer['balance_status']); // 'yes' or 'no'
        $order_tax_percentage = floatval($row_customer['order_tax']);

        $stmt_products = $conn->prepare("
    SELECT SUM(total_amount) AS total_amount_sum,
           net_cash AS net_cash_sum,
           discount AS discount_sum,
           SUM(sale_qty) AS Total_sale_qty,
         change_value AS change_value_sum
    FROM stock_sale
    WHERE invoice = :invoice_number
");
        $stmt_products->bindParam(':invoice_number', $invoice_number);
        $stmt_products->execute();
        $row_products = $stmt_products->fetch(PDO::FETCH_ASSOC);

        $order_tax_sum = ($row_products['total_amount_sum'] * $order_tax_percentage) / 100;

        $total_previous_balance = 0;
        $due_balance = 0;

        if ($balance_status === 'yes') {
            $stmt_previous_balance = $conn->prepare("
        SELECT SUM(total_amount + order_tax - discount) AS previous_balance
        FROM stock_sale
        WHERE customer_id = :customer_id
          AND invoice < :invoice_number
          AND (total_amount + order_tax - discount) > 0
    ");
            $stmt_previous_balance->bindParam(':customer_id', $customer_id);
            $stmt_previous_balance->bindParam(':invoice_number', $invoice_number);
            $stmt_previous_balance->execute();
            $row_previous_balance = $stmt_previous_balance->fetch(PDO::FETCH_ASSOC);
            $previous_balance = floatval($row_previous_balance['previous_balance'] ?? 0);

            $stmt_cash_deposit = $conn->prepare("
        SELECT SUM(amount) AS cash_deposit_sum 
        FROM cash_deposit 
        WHERE user_id = :customer_id;
    ");
            $stmt_cash_deposit->bindParam(':customer_id', $customer_id);
            $stmt_cash_deposit->execute();
            $cash_deposit_sum = floatval($stmt_cash_deposit->fetchColumn());

            $stmt_manual_bill = $conn->prepare("
        SELECT SUM(amount) AS manual_bill_sum 
        FROM customer_bill_manual 
        WHERE user_id = :customer_id;
    ");
            $stmt_manual_bill->bindParam(':customer_id', $customer_id);
            $stmt_manual_bill->execute();
            $manual_bill_sum = floatval($stmt_manual_bill->fetchColumn());

            $total_previous_balance = $previous_balance + $opening_balance + $manual_bill_sum - $cash_deposit_sum;

            $due_balance = ((float)$row_products['total_amount_sum'] + (float)$order_tax_sum)
                - ((float)$row_products['net_cash_sum'] + (float)$row_products['discount_sum']);
        } else {
            $due_balance = ((float)$row_products['total_amount_sum'] + (float)$order_tax_sum)
                - ((float)$row_products['net_cash_sum'] + (float)$row_products['discount_sum']);
        }


        $change_value_sum = floatval($row_products['change_value_sum'] ?? 0);

        $net_receivable = floatval($row_products['net_cash_sum']);

        $subtotal_without_tax = $row_products['total_amount_sum'];
        $total_tax_value = $order_tax_sum;
        ?>

        <div class="total">
            Subtotal: <?php echo number_format($subtotal_without_tax, 2); ?>
        </div>
        <!-- <div class="total">
            Total Tax: <?php echo number_format($total_tax_value, 2); ?>
        </div> -->
        <!-- <div class="total">
            Total Amount (With Tax): <?php echo htmlspecialchars(number_format($row_products['total_amount_sum'] + $order_tax_sum, 2)); ?>
        </div> -->

        <?php if ($row_products['discount_sum'] > 0) : ?>
            <div class="total">
                Discount: <?php echo htmlspecialchars(number_format($row_products['discount_sum'], 2)); ?>
            </div>
        <?php endif; ?>

        <?php if ($balance_status === 'yes') : ?>
            <div class="total" style="display:none;">
                Previous Balance: <?php echo htmlspecialchars(number_format($total_previous_balance, 2)); ?>
            </div>
        <?php endif; ?>

        <?php if ($row_products['net_cash_sum'] > 0) : ?>
            <div class="total">
                Net Receivable: <?php echo htmlspecialchars(number_format($net_receivable + $change_value_sum, 2)); ?>
            </div>
        <?php endif; ?>





        <?php if ($change_value_sum > 0) : ?>
            <div class="total">
                Change: <?php echo htmlspecialchars(number_format($change_value_sum, 2)); ?>
            </div>
        <?php endif; ?>

        <div class="total">
            Due Balance: <?php echo htmlspecialchars(number_format($due_balance, 2)); ?>
        </div>



        <?php
        $stmt_installments = $conn->prepare("
    SELECT installment_no, amount, due_date, status 
    FROM customer_installments 
    WHERE invoice = :invoice_number 
    ORDER BY installment_no ASC
");
        $stmt_installments->bindParam(':invoice_number', $invoice_number);
        $stmt_installments->execute();
        $installments = $stmt_installments->fetchAll(PDO::FETCH_ASSOC);

        if ($installments && count($installments) > 0): ?>
            <h4 style="text-align:center; margin:5px 0;">Installment Plan</h4>
            <table>
                <thead>
                    <tr>
                        <th>No.</th>
                        <th>Due Date</th>
                        <th>Amount</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($installments as $inst): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($inst['installment_no']); ?></td>
                            <td><?php echo date("d-m-Y", strtotime($inst['due_date'])); ?></td>
                            <td><?php echo number_format($inst['amount'], 2); ?></td>
                            <td><?php echo ucfirst($inst['status']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>

        <div class="total">

        </div>

        <h2>Thank You</h2>

        <!-- <p style="text-align:center; font-size:14px; font-weight:bold;">(Developed by IT Genesis)<br>webisite:itgenesis.net & ph: +92 308 4926007</p> -->
        <!-- <button onclick="printContent()">Print</button>-->
    </div>

</body>
<script>
window.addEventListener('DOMContentLoaded', function() {
    var printButton = document.querySelector("button");
    if (printButton) printButton.style.display = "none";

    window.print();

    setTimeout(function() {
        window.location.href = "../pos.php";
    }, 500); 

    if (printButton) printButton.style.display = "block";
});
</script>



</html>