<?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['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();

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Invoice - BOOK POINT</title>
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;600;700&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Quicksand', sans-serif;
      background: #fff;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 210mm;
      margin: auto;
      padding: 20px;
      background: #fff;
      box-shadow: 0 0 5px rgba(0,0,0,0.1);
    }
    .header {
      text-align: center;
      margin-bottom: 20px;
    }
    .header h2 {
      margin: 0;
      font-weight: 700;
      text-transform: uppercase;
    }
    .header p {
      margin: 3px 0;
      font-size: 14px;
    }
    .details, .totals, .notes {
      margin: 15px 0;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
    }
    th, td {
      border: 1px solid #000;
      padding: 6px;
      font-size: 14px;
      text-align: center;
    }
    th {
      background: #f2f2f2;
    }
    .text-center { text-align: center; }
    .totals strong { display: inline-block; width: 200px; }
    .footer {
      margin-top: 30px;
      text-align: center;
    }
    .no-print { margin-top: 20px; }
    @media print {
      body {
        width: 210mm;
        height: 297mm;
        margin: 0;
        padding: 0;
      }
      .container {
        box-shadow: none;
        border: none;
        margin: 0;
        width: 100%;
        height: auto;
        page-break-after: always;
      }
      .no-print { display: none !important; }
    }
  </style>
</head>
<body>
<div class="container">
  <!-- Header -->
  <div class="header">
    <h2>BOOK POINT</h2>
    <p><?= htmlspecialchars($outletAddress ?? 'Near Nonarian Pull Gulshan-e-ravi Ravi, Lahore.', ENT_QUOTES, 'UTF-8') ?></p>
    <p>PHONE: M Sameer 03089267746 | PHONE: M Hamza 03040452492</p>
    <p><strong>Date:</strong> <?= htmlspecialchars($dateTime ?? '', ENT_QUOTES, 'UTF-8') ?></p>
  </div>

  <!-- Customer Info -->
  <div class="details">
    <p><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>

  <!-- Order Table -->
  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Qty</th>
        <th>B.Qty</th>
        <th>T.Qty</th>
        <th>Price</th>
        <th>Dis</th>
        <th>PKR</th>
        <th>Unit</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['bonus_quantity'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($order['total_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><?= htmlspecialchars($order['product_unit'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

<?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 closin_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>";
            }
        }
    }
}
?>
  <div class="totals">
    <p><strong>Total Amount:</strong> Rs <?= htmlspecialchars((string)($discountedAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-</p>
    <p><strong>Previous Amount:</strong> Rs <?= htmlspecialchars((string)$pre, ENT_QUOTES, 'UTF-8') ?> /-</p>
    <p><strong>Grand Total:</strong> Rs <?= htmlspecialchars((string)($close ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-</p>
    <p><strong>Amount Received:</strong> Rs <?= htmlspecialchars((string)($cashAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-</p>
    <p><strong>Cash Remaining:</strong> Rs <?= htmlspecialchars((string)($changeAmount ?? '0'), ENT_QUOTES, 'UTF-8') ?> /-</p>
  </div>

  <!-- Notes -->
  <div class="notes">
    <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>
  </div>

  <!-- Footer -->
  <div class="footer">
    <h3>Thanks For Visiting.</h3>
    <p>Authorized Signature: ____________________</p>
  </div>

  <!-- Print Buttons -->
  <div class="text-center no-print">
    <button 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>
