<?php
session_start();
include 'database/shikanisha.kts.php';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Arial Narrow', Arial, sans-serif;
            font-size: 12px;
            width: 80mm;
        }

        @page {
            size: 80mm auto;
            margin: 0;
        }

        * {
            box-sizing: border-box;
            line-height: 1.2;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        .text-center {
            text-align: center;
        }

        .text-left {
            text-align: left;
        }

        .text-right {
            text-align: right;
        }

        .bold {
            font-weight: bold;
        }

        .uppercase {
            text-transform: uppercase;
        }

        .logo {
            width: 100%;
            text-align: center;
            margin: 2px 0;
        }

        .logo img {
            max-width: 60%;
            height: auto;
        }

        .header-info {
            width: 100%;
            margin-bottom: 3px;
        }

        .receipt-title {
            font-size: 14px;
            font-weight: bold;
            margin: 3px 0;
            text-align: center;
        }

        .divider {
            border-top: 1px dashed #000;
            margin: 3px 0;
        }

        .thick-divider {
            border-top: 2px solid #000;
            margin: 5px 0;
        }

        .items thead th {
            font-size: 11px;
            border-bottom: 1px dashed #000;
            padding: 2px 0;
        }

        .items tbody td {
            font-size: 11px;
            padding: 2px 0;
        }

        .items tfoot td {
            font-size: 12px;
            padding: 3px 0;
            border-top: 1px dashed #000;
        }

        .total-row {
            font-weight: bold;
            border-top: 1px solid #000 !important;
            border-bottom: 1px solid #000 !important;
        }

        .footer {
            font-size: 10px;
            text-align: center;
            margin-top: 5px;
        }

        .qr-code {
            text-align: center;
            margin: 5px 0;
        }

        .qr-code img {
            width: 60px;
            height: 60px;
        }

        .customer-info {
            margin: 3px 0;
            font-size: 11px;
        }

        .col-item {
            width: 50%;
            text-align: left;
        }

        .col-qty {
            width: 15%;
            text-align: right;
        }

        .col-price {
            width: 20%;
            text-align: right;
        }

        .col-total {
            width: 15%;
            text-align: right;
        }
        
        .receipt-copy {
            margin-bottom: 20px;
        }
        
        .copy-notice {
            text-align: center;
            font-weight: bold;
            margin-top: 10px;
            border-top: 1px dashed #000;
            padding-top: 5px;
        }
        
        @media print {
            .noprint {
                display: none;
            }
            .page-break {
                page-break-after: always;
            }
        }
    </style>
</head>

<body>
    <div id="div_print">
        <!-- MERCHANT COPY -->
        <div class="receipt-copy">
            <!-- Logo Section -->
           

            <!-- Business Info -->
            <div class="header-info text-center">
                <div class="bold uppercase" id="shopname"></div>
                <div id="location"></div>
                <div id="quote"></div>
                <div><span id="street"></span>, <span id="address"></span></div>
                <div>PIN: <span id="pin"></span> | Tel: <span id="contact1"></span> / <span id="contact2"></span></div>
            </div>

            <!-- Receipt Title -->
            <div class="receipt-title uppercase">CUSTOMER BILL</div>

            <!-- Transaction Info -->
            <div class="divider"></div>
            <table>
                <tr>
                    <td class="text-left">SN #<?php echo $_SESSION['trans_id']; ?></td>
                    <td class="text-right"><?php echo date('Y-m-d H:i:s'); ?></td>
                </tr>
                <tr>
                    <td class="text-left">Till: 655857</td>
                    <td class="text-right">Served by: <?php echo $_SESSION['user']; ?></td>
                </tr>
            </table>
            <div class="divider"></div>

            <!-- Customer Info -->
            <?php
            if (isset($_SESSION['client_no'])) {
                $phoneNo = $_SESSION['client_no'];
                $query = "SELECT ca.amount_owed, cu.full_name
                          FROM client_acc ca
                          JOIN customers cu ON ca.client_id = cu.customer_id
                          WHERE cu.phone_number = ?";
                
                if ($stmt = mysqli_prepare($conn, $query)) {
                    mysqli_stmt_bind_param($stmt, 's', $phoneNo);
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_bind_result($stmt, $amountOwed, $customerName);
                    
                    if (mysqli_stmt_fetch($stmt)) {
                        echo '<div class="customer-info">';
                        echo '<div>Customer: ' . htmlspecialchars($customerName) . '</div>';
                        echo '<div>Balance: Ksh ' . number_format($amountOwed, 2) . '</div>';
                        echo '</div>';
                        echo '<div class="divider"></div>';
                    }
                    mysqli_stmt_close($stmt);
                }
            }
            ?>

            <!-- Items Table -->
            <table class="items">
                <thead>
                    <tr>
                        <th class="text-left col-item">ITEM</th>
                        <th class="text-right col-qty">QTY</th>
                        <th class="text-right col-price">PRICE</th>
                        <th class="text-right col-total">TOTAL</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $total = 0;
                    $totalA = 0;
                    $totalB = 0;
                    $totalC = 0;
                    $taxa = 0;
                    $tottax = 0;

                    $cart = !empty($_SESSION['cart_data']) 
                        ? $_SESSION['cart_data'] 
                        : (!empty($_SESSION['return_cart']) 
                            ? $_SESSION['return_cart'] 
                            : (!empty($_SESSION['cart']) 
                                ? $_SESSION['cart'] 
                                : []));

                    if (!empty($cart) && is_array($cart)) {
                        foreach ($cart as $value) {
                            $quantity = isset($value['quantity']) ? $value['quantity'] : 0;
                            $price = isset($value['food_price']) ? $value['food_price'] : 0;
                            $tax = isset($value['tax_class']) ? $value['tax_class'] : '';
                            $unit = isset($value['unit']) ? $value['unit'] : '';
                            $food_name = isset($value['food_name']) ? $value['food_name'] : 'Unknown Item';
                            $cat = isset($value['cat']) ? $value['cat'] : '';

                            echo "<tr>";
                            echo "<td class='text-left'>" . htmlspecialchars($food_name) . "</td>";
                            echo "<td class='text-right'>" . number_format($quantity, 2) . " " . htmlspecialchars($unit) . "</td>";
                            echo "<td class='text-right'>" . number_format($price, 2) . "</td>";
                            echo "<td class='text-right'>" . number_format($price * $quantity, 2) . "</td>";
                            echo "</tr>";

                            $subtotal = $quantity * $price;
                            $total += $subtotal;
                            
                            switch ($tax) {
                                case 'A':
                                    $totalA += $subtotal;
                                    break;
                                case 'B':
                                    $totalB += $subtotal;
                                    break;
                                case 'C':
                                    $totalC += $subtotal;
                                    break;
                            }
                        }
                    } else {
                        echo "<tr><td colspan='4' class='text-center'>No items in cart.</td></tr>";
                    }
                    ?>
                </tbody>
                <tfoot>
                    <?php if ($totalA > 0): ?>
                    <tr>
                        <td colspan="3" class="text-right">Taxable Amount (A):</td>
                        <td class="text-right"><?php echo number_format($totalA, 2); ?></td>
                    </tr>
                    <tr>
                        <td colspan="3" class="text-right">VAT (16%):</td>
                        <td class="text-right"><?php echo number_format($totalA * 0.16, 2); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr class="total-row">
                        <td colspan="3" class="text-right bold">TOTAL:</td>
                        <td class="text-right bold">Ksh <?php echo number_format($total, 2); ?></td>
                    </tr>
                </tfoot>
            </table>

            <!-- Payment Info -->
            <div class="thick-divider"></div>
            <table>
                <tr>
                    <td class="text-left">Payment Method:</td>
                    <td class="text-right">CASH</td>
                </tr>
                <tr>
                    <td class="text-left">Amount Paid:</td>
                    <td class="text-right">Ksh <?php echo isset($_SESSION['amount_paid']) ? number_format($_SESSION['amount_paid'], 2) : '0.00'; ?></td>
                </tr>
                <tr>
                    <td class="text-left">Change:</td>
                    <td class="text-right">Ksh <?php 
                        $amountPaid = isset($_SESSION['amount_paid']) ? $_SESSION['amount_paid'] : 0;
                        $change = $amountPaid - $total;
                        echo number_format(max($change, 0), 2); 
                    ?></td>
                </tr>
            </table>

           

            <!-- Footer -->
            <div class="footer">
                <div>THANK YOU FOR YOUR BUSINESS!</div>
                <div>Software by 0715585188</div>
            </div>
            
            <div class="copy-notice">MERCHANT COPY</div>
        </div>
        
        <!-- CUSTOMER COPY -->
        <div class="page-break"></div>
        <div class="receipt-copy">
            <!-- Logo Section -->
            

            <!-- Business Info -->
            <div class="header-info text-center">
                <div class="bold uppercase" id="shopname2"></div>
                <div id="location2"></div>
                <div id="quote2"></div>
                <div><span id="street2"></span>, <span id="address2"></span></div>
                <div>PIN: <span id="pin2"></span> | Tel: <span id="contact12"></span> / <span id="contact22"></span></div>
            </div>

            <!-- Receipt Title -->
            <div class="receipt-title uppercase">CUSTOMER BILL</div>

            <!-- Transaction Info -->
            <div class="divider"></div>
            <table>
                <tr>
                    <td class="text-left">SN #<?php echo $_SESSION['trans_id']; ?></td>
                    <td class="text-right"><?php echo date('Y-m-d H:i:s'); ?></td>
                </tr>
                <tr>
                    <td class="text-left">Till: 655857</td>
                    <td class="text-right">Served by: <?php echo $_SESSION['user']; ?></td>
                </tr>
            </table>
            <div class="divider"></div>

            <!-- Customer Info -->
            <?php
            if (isset($_SESSION['client_no'])) {
                $phoneNo = $_SESSION['client_no'];
                $query = "SELECT ca.amount_owed, cu.full_name
                          FROM client_acc ca
                          JOIN customers cu ON ca.client_id = cu.customer_id
                          WHERE cu.phone_number = ?";
                
                if ($stmt = mysqli_prepare($conn, $query)) {
                    mysqli_stmt_bind_param($stmt, 's', $phoneNo);
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_bind_result($stmt, $amountOwed, $customerName);
                    
                    if (mysqli_stmt_fetch($stmt)) {
                        echo '<div class="customer-info">';
                        echo '<div>Customer: ' . htmlspecialchars($customerName) . '</div>';
                        echo '<div>Balance: Ksh ' . number_format($amountOwed, 2) . '</div>';
                        echo '</div>';
                        echo '<div class="divider"></div>';
                    }
                    mysqli_stmt_close($stmt);
                }
            }
            ?>

            <!-- Items Table -->
            <table class="items">
                <thead>
                    <tr>
                        <th class="text-left col-item">ITEM</th>
                        <th class="text-right col-qty">QTY</th>
                        <th class="text-right col-price">PRICE</th>
                        <th class="text-right col-total">TOTAL</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $total = 0;
                    $totalA = 0;
                    $totalB = 0;
                    $totalC = 0;
                    $taxa = 0;
                    $tottax = 0;

                    if (!empty($cart) && is_array($cart)) {
                        foreach ($cart as $value) {
                            $quantity = isset($value['quantity']) ? $value['quantity'] : 0;
                            $price = isset($value['food_price']) ? $value['food_price'] : 0;
                            $tax = isset($value['tax_class']) ? $value['tax_class'] : '';
                            $unit = isset($value['unit']) ? $value['unit'] : '';
                            $food_name = isset($value['food_name']) ? $value['food_name'] : 'Unknown Item';
                            $cat = isset($value['cat']) ? $value['cat'] : '';

                            echo "<tr>";
                            echo "<td class='text-left'>" . htmlspecialchars($food_name) . "</td>";
                            echo "<td class='text-right'>" . number_format($quantity, 2) . " " . htmlspecialchars($unit) . "</td>";
                            echo "<td class='text-right'>" . number_format($price, 2) . "</td>";
                            echo "<td class='text-right'>" . number_format($price * $quantity, 2) . "</td>";
                            echo "</tr>";

                            $subtotal = $quantity * $price;
                            $total += $subtotal;
                        }
                    }
                    ?>
                </tbody>
                <tfoot>
                    <?php if ($totalA > 0): ?>
                    <tr>
                        <td colspan="3" class="text-right">Taxable Amount (A):</td>
                        <td class="text-right"><?php echo number_format($totalA, 2); ?></td>
                    </tr>
                    <tr>
                        <td colspan="3" class="text-right">VAT (16%):</td>
                        <td class="text-right"><?php echo number_format($totalA * 0.16, 2); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr class="total-row">
                        <td colspan="3" class="text-right bold">TOTAL:</td>
                        <td class="text-right bold">Ksh <?php echo number_format($total, 2); ?></td>
                    </tr>
                </tfoot>
            </table>

            <!-- Payment Info -->
            <div class="thick-divider"></div>
            <table>
                <tr>
                    <td class="text-left">Payment Method:</td>
                    <td class="text-right">CASH</td>
                </tr>
                <tr>
                    <td class="text-left">Amount Paid:</td>
                    <td class="text-right">Ksh <?php echo isset($_SESSION['amount_paid']) ? number_format($_SESSION['amount_paid'], 2) : '0.00'; ?></td>
                </tr>
                <tr>
                    <td class="text-left">Change:</td>
                    <td class="text-right">Ksh <?php 
                        echo number_format(max($change, 0), 2); 
                    ?></td>
                </tr>
            </table>

            <!-- QR Code -->
            

            <!-- Footer -->
            <div class="footer">
                <div>THANK YOU FOR YOUR BUSINESS!</div>
                <div>Software by 0715585188</div>
            </div>
            
            <div class="copy-notice">CUSTOMER COPY</div>
        </div>
    </div>

 <script>
    let printCount = 0;

    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                if (!data.error) {
                    updateBusinessDetails(data);
                }
            }
        };
        xhr.send();
    }

    function updateBusinessDetails(data) {
        document.getElementById('shopname').innerText = data.shop_name || '';
        document.getElementById('location').innerText = data.location || '';
        document.getElementById('quote').innerText = data.quote || '';
        document.getElementById('street').innerText = data.street || '';
        document.getElementById('address').innerText = data.address || '';
        document.getElementById('pin').innerText = data.pin || '';
        document.getElementById('contact1').innerText = data.contact1 || '';
        document.getElementById('contact2').innerText = data.contact2 || '';

        document.getElementById('shopname2').innerText = data.shop_name || '';
        document.getElementById('location2').innerText = data.location2 || '';
        document.getElementById('quote2').innerText = data.quote2 || '';
        document.getElementById('street2').innerText = data.street2 || '';
        document.getElementById('address2').innerText = data.address2 || '';
        document.getElementById('pin2').innerText = data.pin2 || '';
        document.getElementById('contact12').innerText = data.contact1 || '';
        document.getElementById('contact22').innerText = data.contact2 || '';
    }

    function printTwoCopies() {
        printCount = 0;
        printNext();
    }

    function printNext() {
        if (printCount < 2) {
            printCount++;
            window.addEventListener('afterprint', handleAfterPrint, { once: true });
            printReceipt();
        } else {
            window.location.href = 'database/endbill.kts.php';
        }
    }

    function handleAfterPrint() {
        // Delay a bit to ensure print dialog fully closes
        window.location.href = 'database/endbill.kts.php';
    }

    function printReceipt() {
        var headstr = "<html><head><title>Receipt</title></head><body>";
        var footstr = "</body></html>";
        var content = document.getElementById('div_print').innerHTML;
        var originalContent = document.body.innerHTML;

        document.body.innerHTML = headstr + content + footstr;
        window.print();
        document.body.innerHTML = originalContent;
    }

    window.onload = function() {
        fetchBusinessDetails();
    };
</script>


</body>
</html>

<button type="submit" onclick="printTwoCopies()" value="print" name="close" class="noprint">PRINT</button>