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

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) {
            // 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 {
            // 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(), '$loginUser', '$userRole', '$outletName', '$outletAddress'
            )";
            $insertResult = mysqli_query($connection, $insertQuery);

            if ($insertResult) {
                echo "<script type='text/javascript'>window.location.href = 'mainpos.php';</script>";
                exit;
            }
        }
    }
}
?>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Invoice</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root { --page-width:210mm; --page-height:297mm; }
    body { background:#fff; font-family: Arial, Helvetica, sans-serif; font-size:12px; }
    .page { width:var(--page-width); min-height:var(--page-height); margin:0 auto; background:#fff; padding:15mm; box-sizing:border-box; color:#000; }
    .invoice-title { font-size:72px; font-weight:bold; letter-spacing:1px; }
    .logo-circle { width:100px; height:100px; border:2px solid #000; border-radius:50%; display:flex; align-items:center; justify-content:center; font-weight:bold; font-size:18px; }
    .border-box { border:1px solid #000; padding:6px; }
    .items-table th, .items-table td { border:1px solid #000; text-align:center; }
    .items-table th { font-weight:bold; }
    .payment-box, .totals-box, .notes-box { border:1px solid #000; padding:8px; }
    .totals-box td { border:1px solid #000; padding:4px; }
    .thank { text-align:center; font-weight:bold; margin-top:10px; }
    @page { size:A4; margin:0; }
    @media print { .page { margin:0; box-shadow:none; } .no-print { display:none; } }
  </style>
</head>
<body>
  <div class="page">
    <div class="row">
      <div class="col-8">
        <div class="invoice-title">INVOICE</div>
      </div>
      <div class="col-4 d-flex justify-content-end">
        <img src="../img/logo231.png" width="135" height="135" alt="Logo" style="border-radius:25px;">
      </div>
    </div>

    <div class="row mt-3">
      <div class="col-4">
        <div class="border-box">
          <div>INVOICE #: <?php echo htmlspecialchars($orderId); ?></div>
          <div>INVOICE DATE: <?php echo htmlspecialchars($dateTime); ?></div>
        </div>
      </div>
      <div class="col-4">
        <div class="border-box">
          <div><?php echo htmlspecialchars($customerName); ?></div>
          <div><?php echo htmlspecialchars($customerPhone); ?></div>
          <div><?php echo htmlspecialchars($paidBy); ?></div>
        </div>
      </div>
      <div class="col-4 text-end">
        <div><?php echo htmlspecialchars($outletName); ?><br><?php echo htmlspecialchars($outletAddress); ?></div>
      </div>
    </div>

    <div class="row mt-4">
      <div class="col-12">
        <table class="table items-table w-100">
          <thead>
            <tr>
              <th style="width:10%">Sr #</th>
              <th style="width:50%">DESCRIPTION</th>
              <th style="width:10%">QTY</th>
              <th style="width:15%">PRICE</th>
              <th style="width:15%">TOTAL</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!empty($orderDetails)): $i=1; foreach ($orderDetails as $item): ?>
            <tr>
              <td><?php echo $i++; ?></td>
              <td><?php echo htmlspecialchars($item['product_name']); ?></td>
              <td><?php echo htmlspecialchars($item['product_quantity']); ?></td>
              <td><?php echo htmlspecialchars($item['product_price']); ?></td>
              <td><?php echo htmlspecialchars($item['net_amount']); ?></td>
            </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="row mt-2">
      <div class="col-6">
        <div class="payment-box">
          <div><strong>PAYMENT DETAILS</strong></div>
          <div>Payment: <?php echo htmlspecialchars($paidBy); ?></div>
          <div>Cash Received: <?php echo htmlspecialchars($cashAmount); ?></div>
          <div>Remaining: <?php echo htmlspecialchars($changeAmount); ?></div>
        </div>
      </div>
      <div class="col-6 d-flex justify-content-end">
        <table class="totals-box">
          <tr><td>SUBTOTAL:</td><td><?php echo htmlspecialchars($pre); ?></td></tr>
          <tr><td>DISCOUNT:</td><td><?php echo htmlspecialchars($discountedAmount); ?></td></tr>
          <tr><td>TAX:</td><td><?php echo htmlspecialchars($taxAmount); ?></td></tr>
          <tr><td>TOTAL:</td><td><?php echo htmlspecialchars($close); ?></td></tr>
        </table>
      </div>
    </div>

    <div class="row mt-4">
      <div class="col-12">
        <div class="notes-box">
          <h6>NOTES:</h6>
          <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>
        </div>
      </div>
    </div>

    <div class="thank">THANK YOU FOR YOUR BUSINESS!</div>

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

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>
