<?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['inv_id']) ? mysqli_real_escape_string($connection, $_GET['inv_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM purchase WHERE inv_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;">
        Near Nonarian Pull Gulshan-e-ravi  <br>Ravi, Lahore.</p>
        <p class="mb-0" style="margin-top:-2px;font-weight:600;">PHONE: M sameer 03089267746<br>PHONE: </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>Total</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['product_total'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['discount'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($order['net_amount'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
  
<br>    
    <div>
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && is_numeric($changeAmount)) {
        $checkQuery = "SELECT 1 FROM supplier_closing WHERE supplier_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

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

            if ($updateResult) {
                echo "<script type='text/javascript'>window.location.href = 'purchase_n.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
            }
        } else {
            // Record doesn't exist: insert
            $insertQuery = "INSERT INTO supplier_closing (
               supplier_name, opening_cash, cash_purchase, credit_purchase,
                	cash_paid, closing_balance, user_name, user_role,
                outlet_name, outlet_address, date_time
            ) VALUES (
                '$customerName', 0, 0, 0, 0, $changeAmount, '$userName', '$useRole', '$outlet_name', '$outlet_address', NOW()
            )";

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

            if ($insertResult) {
                echo "<script type='text/javascript'>window.location.href = 'purchase_n.php';</script>";
                exit;
            } else {
                echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
            }
        }
    }
}
?>
    <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>

       
       <a href="purchase_detail_v.php">     <button type="button"  class="no-print">Exit</button></a>
       
    </div>
</div>
</body>
</html>
