<?php
include("../db/cn.php");
include("common/tx.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 = 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 = $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'];
        $pre = $order['pre_amount'];
        $close = $order['grand_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><?php echo $tx; ?></title>

    <style>
    body {
    font-family: 'Quicksand', sans-serif;
}
    @media print {
        body {
            width: 80mm;
            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;">
        <h2 style="font-weight:600; text-transform:uppercase;"><?php echo $tx; ?></h2>
          <p class="mb-0" style="font-size:14px;margin-top:5px;text-transform:uppercase;font-weight:600;"> Moharah Bazar.</p>
        <p class="mb-0" style="margin-top:-2px;font-weight:600;">Md Mahmood Chohan: 03556411764 <br> 03125516784</p>
        <p style="margin-top:-3px;"><strong>Date:</strong> <?= htmlspecialchars($dateTime ?? '', ENT_QUOTES, 'UTF-8') ?> </p>
    </div>

    <div>
        <p style="text-transform:capitalize;"><strong>Name:</strong> <?= htmlspecialchars($customerName ?? '', ENT_QUOTES, 'UTF-8') ?><br>
        <strong>Phone:</strong> <?= htmlspecialchars($customerPhone ?? '', ENT_QUOTES, 'UTF-8') ?><br>
        <strong>Payment:</strong> <?= htmlspecialchars($paidBy ?? '', ENT_QUOTES, 'UTF-8') ?><br>
        <strong>Order ID:</strong> <?= htmlspecialchars($orderId ?? '', ENT_QUOTES, 'UTF-8') ?></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><?= htmlspecialchars($order['product_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['product_quantity'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['product_price'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['discount'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['net_amount'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td style="text-transform:capitalize;"><?= htmlspecialchars($order['product_unit'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </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) {
                echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                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) {
                echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>
<br>    
    <div>
    <strong>Total Amount:</strong> Rs <?= htmlspecialchars((string)($discountedAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-<br>
    <strong>Previous Amount:</strong> Rs <?= htmlspecialchars((string)$pre, ENT_QUOTES, 'UTF-8') ?> /-<br>
    <strong>Grand Total:</strong> Rs <?= htmlspecialchars((string)($close ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-<br>
    <strong>Amount Received:</strong> Rs <?= htmlspecialchars((string)($cashAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-<br>
    <strong>Cash Remaining:</strong> Rs <?= htmlspecialchars((string)($changeAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-<br>
    </div>

    <div>
        <h3>Notes:</h3>
      <p>1. Exchanges are accepted within 7 days from the date of purchase.<br>
       2. Items must be in their original condition with all tags attached.<br>
       3. A valid receipt or proof of purchase is required for all exchanges.</p>
        <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>
