<?php
include("../db/cn.php");
ob_start();
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 = 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'];
        $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'];
    }
}

$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);
    echo "";
}

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>Print Order</title>
    <style>
   <style>
body {
    font-family: 'Quicksand', sans-serif;
    margin: 20px;
    padding: 20px;
    font-size: 14px;
}
.container {
    width: 100%;
    margin: auto;
}
.text-center {
    text-align: center;
}
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}
th, td {
    border: 1px solid #000;
    padding: 8px;
    text-align: center;
}
h2, h3, h4 {
    margin: 5px 0;
}

@media print {
    body {
        width: 210mm;   /* A4 width */
        height: 297mm;  /* A4 height */
        margin: 10mm auto;
        padding: 0;
    }
    .no-print {
        display: none;
    }
    table th, table td {
        font-size: 12px;
        padding: 6px;
    }
}
</style>
    </style>
</head>
<body>
<div class="container" id="invoice" >
    <div class="text-center" style="margin-left:10px;">
        <h2 style="font-weight:600; text-transform:uppercase;">world daignostic</h2>
        <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>Product</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Dis</th>
                    <th>PKR</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderDetails as $order): ?>
                <tr>
                    <td><?php echo $order['product_name']; ?></td>
                    <td><?php echo $order['product_quantity']; ?></td>
                    <td><?php echo $order['product_price']; ?></td>
                    <td><?php echo $order['discount']; ?></td>
                    <td><?php echo $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>


    <?php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && is_numeric($changeAmount)) {
        $checkQuery = "SELECT 1 FROM creditor_closing WHERE creditor_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            // Record exists: update
            $updateQuery = "UPDATE creditor_closing SET remain_balance = $changeAmount WHERE creditor_name = '$customerName'";
            $updateResult = mysqli_query($connection, $updateQuery);

            if ($updateResult) {
                header("Location: mainpos.php");
                exit;
            } else {
                echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
            }
        } else {
            // Record doesn't exist: insert
            $insertQuery = "INSERT INTO creditor_closing (
                creditor_name, opening_cash, credit_sales, credit_recieved,
                remain_balance, date_time, login_user, user_role,
                outlet_name, outlet_address
            ) VALUES (
                '$customerName', 0, 0, 0, $changeAmount, NOW(), '$userName', '$useRole', '$outlet_name', '$outlet_address'
            )";

            $insertResult = mysqli_query($connection, $insertQuery);

            if ($insertResult) {
                header("Location: mainpos.php");
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>

    <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>
            <a href="delivery_c.php?order_id=<?php echo urlencode($orderId); ?>" class="no-print">
    <button type="button">Delivery Challan</button>
</a>
    </div>
</div>
</body>
</html>
