<?php
include("../db/cn.php");
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Fetch order details from the database
$orderId = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = $preAmount = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId' && status='' && r_order_id = ''";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = $order['net_amount'];
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = $order['discount_amount'];
        $discounted = $order['discounted'];
        $discountPer = $order['discount_per'];
        $cashAmount = $order['cash_amount'];
        $changeAmount = $order['change_amount'];
        $taxAmount = $order['tax_amount'];
        $preAmount = $order['pre_amount'];
        
        /* ------------------------------------------
            CALCULATE TOTALS HERE, BEFORE HTML OUTPUT
        ------------------------------------------- */
        /* 1) TOTAL NET AMOUNT OF ALL PRODUCTS */
        $totalSub = 0;
        $sb = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$orderId'");
        while ($tt = mysqli_fetch_array($sb)) {
            // Convert to float to ensure numeric operations work
            $totalSub += floatval($tt['net_amount']);   // net = total - discount
        }

        /* 2) DISCOUNT (ALREADY STORED IN DB) */
        if (!isset($discounted)) { 
            $discounted = 0; 
        }
        
        // Convert discount to float
        $discounted = floatval($discounted);

        /* 3) FINAL AMOUNT AFTER DISCOUNT */
        $discountedAmount = floatval($totalSub) - floatval($discounted);

        /* 4) PREVIOUS BALANCE - FIXED VARIABLE NAME */
        $pre = 0;
        $sub = mysqli_query($connection,
        "SELECT SUM(remain_balance) AS pre FROM creditor_closing WHERE creditor_name = '$customerName'");
        if ($rowSub = mysqli_fetch_assoc($sub)) {
            $pre = floatval($rowSub['pre'] ?? 0);
        }

        /* 5) GRAND TOTAL = Final Amount + Previous Amount */
        // Convert all to float before calculation
        $preAmount = floatval($preAmount);
        $close = floatval($discountedAmount) + floatval($preAmount);

        /* 6) CASH AND CHANGE */
        $cashAmount = floatval($cashAmount ?? 0);
        $changeAmount = floatval($cashAmount) - floatval($close);
    }
}

$content = ob_get_clean(); // Capture HTML content

// Function to send data to the printer
function sendToPrinter($result) {
    $printerName = "EPSON_TM_T88V_Receipt"; // Change to your printer's name
    $handle = @fopen("USB", "w"); // LPT1 is commonly used for parallel port printers, change if necessary
    if (!$handle) {
        echo "Error opening printer on Windows. Check the printer port and connection.";
        return;
    }
    fwrite($handle, $result);
    fclose($handle);
    echo "";
}

// Call the print function
sendToPrinter($content);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Print Order</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Quicksand', sans-serif;
        }
        @media print {
            body {
                width: 72mm;
                margin: 0;
                padding: 0;
            }
            .container {
                width: 100%;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none;
            }
            .text-center {
                text-align: center;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                font-size: 12px;
            }
            th, td {
                border: 1px solid #000;
                padding: 3px;
                text-align: center;
            }
            .mb-0, .mb-1 {
                margin-bottom: 5px;
            }
        }
        
        @media screen {
            .container {
                width: 72mm;
                margin: 0 auto;
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<div class="container" id="invoice">
    <div class="text-center" style="margin-left:10px;">
        <h2 style="font-weight:600; text-transform:uppercase; font-size: 16px;">ATR software</h2>
        <p class="mb-0" style="font-size:12px;margin-top:5px;text-transform:uppercase;font-weight:600;">
            Al hafeez</p>
        <p class="mb-0" style="margin-top:-2px;font-weight:600; font-size: 12px;">ATR</p>
        
        <p style="margin-top:-3px; font-size: 12px;"><strong>Date:</strong> <?php echo htmlspecialchars($dateTime); ?> </p>
    </div>

    <div style="font-size: 12px;">
        <p style="text-transform:capitalize;">
            <strong>Name:</strong> <?php echo htmlspecialchars($customerName); ?><br>
            <strong>Phone:</strong> <?php echo htmlspecialchars($customerPhone); ?><br>
            <strong>Payment:</strong> <?php echo htmlspecialchars($paidBy); ?><br>
            <strong>Order ID:</strong> <?php echo htmlspecialchars($orderId); ?>
        </p>
    </div>

    <div>
        <table>
            <thead>
                <tr>
                    <th>Sr.#</th>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Total</th>
                    <th>Dis</th>
                    <th>PKR</th>
                </tr>
            </thead>
            <tbody>
                <?php $sr = 1; ?>
                <?php foreach ($orderDetails as $order): ?>
                <tr>
                    <td><?php echo $sr++; ?></td>
                    <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                    <td><?php echo htmlspecialchars($order['product_quantity']); ?></td>
                    <td><?php echo htmlspecialchars($order['product_price']); ?></td>
                    <td><?php echo htmlspecialchars($order['product_total']); ?></td>
                    <td><?php echo htmlspecialchars($order['disc_amount']); ?></td>
                    <td><?php echo htmlspecialchars($order['net_amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <br> 
    <div style="font-size: 12px;">
        <strong>Total:</strong> Rs <?php echo isset($totalSub) ? number_format($totalSub, 2) : '0.00'; ?> /-<br>
        <strong>Discount:</strong> Rs <?php echo isset($discounted) ? number_format($discounted, 2) : '0.00'; ?> /-<br>
        <strong>Total Amount:</strong> Rs <?php echo isset($discountedAmount) ? number_format($discountedAmount, 2) : '0.00'; ?> /-<br>
        <strong>Previous Amount:</strong> Rs <?php echo isset($preAmount) ? number_format($preAmount, 2) : '0.00'; ?> /-<br>
        <strong>Grand Total:</strong> Rs <?php echo isset($close) ? number_format($close, 2) : '0.00'; ?> /-<br>
        <strong>Amount Received:</strong> Rs <?php echo isset($cashAmount) ? number_format($cashAmount, 2) : '0.00'; ?> /-<br>
        <strong>Cash Remaining:</strong> Rs <?php echo isset($changeAmount) ? number_format($changeAmount, 2) : '0.00'; ?> /-<br>
    </div>

    <div>
        <h3 style="text-align:center; font-size: 14px;">Thanks For Visiting.</h3>
    </div>

    <div class="text-center no-print">
        <button class="no-print btn btn-primary" onclick="window.print()" style="padding: 8px 15px; margin: 5px;">Print</button>
        <button class="no-print btn btn-success" onclick="downloadPDF()" style="padding: 8px 15px; margin: 5px;">Download PDF</button>
        <button class="no-print btn btn-secondary" onclick="window.location.href='order_detail_v.php'" style="padding: 8px 15px; margin: 5px;">Exit</button>
    </div>
</div>

</body>
<script>
    function downloadPDF() {
        // Import jsPDF
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('p', 'mm', [72, 297]); // Receipt size

        // Add header
        doc.setFontSize(14);
        doc.text('WELLFOOD TRADERS', 36, 10, { align: 'center' });
        
        doc.setFontSize(10);
        doc.text('نزد عبدالغنی پائے والے، شہاب پورہ، اکوگی روڈ', 36, 15, { align: 'center' });
        doc.text('03302724222', 36, 20, { align: 'center' });
        doc.text('Date: <?php echo htmlspecialchars($dateTime); ?>', 36, 25, { align: 'center' });

        // Add customer details
        doc.text('Name: <?php echo htmlspecialchars($customerName); ?>', 10, 35);
        doc.text('Phone: <?php echo htmlspecialchars($customerPhone); ?>', 10, 40);
        doc.text('Payment: <?php echo htmlspecialchars($paidBy); ?>', 10, 45);
        doc.text('Order ID: <?php echo htmlspecialchars($orderId); ?>', 10, 50);

        // Add the table
        const tableColumn = ["Sr", "Product", "Qty", "Price", "Total", "Dis", "PKR"];
        const tableRows = [];
        
        <?php $sr = 1; ?>
        <?php foreach ($orderDetails as $order): ?>
            tableRows.push([
                "<?php echo $sr++; ?>",
                "<?php echo htmlspecialchars($order['product_name']); ?>",
                "<?php echo htmlspecialchars($order['product_quantity']); ?>",
                "<?php echo htmlspecialchars($order['product_price']); ?>",
                "<?php echo htmlspecialchars($order['product_total']); ?>",
                "<?php echo htmlspecialchars($order['disc_amount']); ?>",
                "<?php echo htmlspecialchars($order['net_amount']); ?>"
            ]);
        <?php endforeach; ?>

        doc.autoTable({
            startY: 55,
            head: [tableColumn],
            body: tableRows,
            theme: 'grid',
            styles: { fontSize: 8 },
            headStyles: { fillColor: [0, 0, 0] },
            margin: { left: 5, right: 5 }
        });

        // Add totals
        let finalY = doc.lastAutoTable.finalY + 10;
        doc.setFontSize(10);
        
        doc.text('Total: Rs <?php echo isset($totalSub) ? number_format($totalSub, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Discount: Rs <?php echo isset($discounted) ? number_format($discounted, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Total Amount: Rs <?php echo isset($discountedAmount) ? number_format($discountedAmount, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Previous Amount: Rs <?php echo isset($preAmount) ? number_format($preAmount, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Grand Total: Rs <?php echo isset($close) ? number_format($close, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Amount Received: Rs <?php echo isset($cashAmount) ? number_format($cashAmount, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 5;
        doc.text('Cash Remaining: Rs <?php echo isset($changeAmount) ? number_format($changeAmount, 2) : '0.00'; ?> /-', 10, finalY);
        finalY += 10;
        
        doc.text('Thanks For Visiting.', 36, finalY, { align: 'center' });

        // Save the PDF
        doc.save('order_<?php echo $orderId; ?>.pdf');
    }
</script>
</html>