<?php
ob_start();
include("../db/cn.php");

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$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 = $customer_type = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId'";
    $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'];
        $customer_type = isset($order['customer_type']) ? trim($order['customer_type']) : '';
        $customerName = isset($order['customer_name']) ? trim($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'];
    }
}

// ===== Exit button handling =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    // Always redirect to mainpos.php, no ledger update
    header("Location: mainpos.php");
    exit;
}

// ===== Printer content capture =====
$content = ob_get_clean();

function sendToPrinter($result) {
    $printerName = "EPSON_TM_T88V_Receipt";
    $handle = @fopen("USB", "w");
    if (!$handle) {
        echo "Error opening printer on Windows. Check the printer port and connection.";
        return;
    }
    fwrite($handle, $result);
    fclose($handle);
}

sendToPrinter($content);
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <title>QudratULLAH Tradring</title>
    <style>
    body {
        font-family: 'Quicksand', sans-serif;
    }
    @media print {
        body {
            width: 70mm;
            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;
        }
        th, td {
            border: 1px solid #000;
            padding: 5px;
            text-align: center;
        }
        .mb-0, .mb-1 {
            margin-bottom: 5px;
        }
    }
    </style>
</head>
<body>
<div class="container" id="invoice" >
    <div class="text-center" style="margin-left:10px;">
        <!--<img src="../img/logo231.png" width="176" height="176" alt="Logo" style="border-radius:25px;">-->
        <h2 style="font-weight:600; text-transform:uppercase;">QUDRATULLAH TRADING</h2>
        <p class="mb-0" style="font-size:14px;margin-top:5px;text-transform:uppercase;font-weight:600;">
         Maddrasa Road New Adda Quetta Shop No. 30</p>
        <p class="mb-0" style="margin-top:-2px;font-weight:600;">NaseebUllah: 0332-8050950
        <br>QudratUllah: 03138236089
        <br>Abdul Razaq: 03365683326</p>
        <p style="margin-top:-3px;"><strong>Date:</strong> <?php echo $dateTime; ?> </p>
    </div>

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

    <div>
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Qty</th>
                    <th>Price</th>
                    
                    <th>PKR</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderDetails as $order): ?>
                <tr>
                    <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['discount']); ?></td>-->
                    <td><?php echo htmlspecialchars($order['net_amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php
    $sub = mysqli_query($connection, "SELECT SUM(remain_balance) AS rm FROM creditor_closing WHERE creditor_name = '$customerName'");
    $rowSub = mysqli_fetch_array($sub);
    $pre = $rowSub["rm"];
    $close = $discountedAmount + $pre;
    ?>
<br> 
    <div>
    <strong>Total Amount:</strong> Rs <?php echo $discountedAmount; ?> /-<br>
    <strong>Previous Amount:</strong> Rs <?= (string)($pre ?? '0') ?> /-<br>
    <strong>Grand Total:</strong> Rs <?php echo $close; ?> /-<br>
    <strong>Amount Received:</strong> Rs <?php echo $cashAmount; ?> /-<br>
    <strong>Cash Remaining:</strong> Rs <?php echo $changeAmount; ?> /-<br>
    </div>

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

    <div class="text-center no-print">
        <button class="no-print" onclick="window.print()">Print</button>
        <form method="post" style="display:inline;">
            <button type="submit" name="exit" class="no-print">Exit</button>
        </form>
    </div>
</div>
</body>
</html>
