<?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'];
        $lot_no = $order['lot_no'];
        $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'];
        $totalAmount = $order['total_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">
<title>Sales Tax Invoice</title>
<style>
  @page {
  size: A4;
  margin: 10mm; /* adjust as needed */
}

body {
  font-family: "Times New Roman", serif;
  font-size: 14px;
  margin: 0;
  padding: 0;
  background: #fdfdfd;
}

.page {
  width: 210mm;
  height: 297mm; /* strict A4 height */
  margin: 0 auto;
  background: #fff;
  position: relative;
  overflow: hidden; /* force everything inside single page */
  padding: 0;
  box-sizing: border-box;
}

.header {
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 190mm;
  text-align: center;
  background: #fff;
  border-bottom: 1px solid #000;
  padding: 5mm 0;
}

.header img {
  max-width: 100%;
  height: auto;
}

.content {
  margin-top: 40mm;   /* space for header */
  margin-bottom: 40mm; /* space for footer */
  padding: 0 5mm;
  height: calc(100% - 80mm); /* fit within page */
  overflow: hidden;
  box-sizing: border-box;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 190mm;
  text-align: center;
  background: #fff;
  border-top: 1px solid #000;
  padding: 5mm 0;
}

.footer img {
  max-width: 100%;
  height: auto;
}

table {
  border-collapse: collapse;
  width: 100%;
  margin: auto;
}

td, th {
  border: 1px solid #000;
  padding: 4px 6px;
  vertical-align: top;
}

.no-border td {
  border: none !important;
}

.center {
  text-align: center;
}

.right {
  text-align: right;
}

.bold {
  font-weight: bold;
}

.heading {
  font-size: 16px;
  font-weight: bold;
}

.small {
  font-size: 12px;
}

.no-print {
  display: inline-block;
  margin: 5px;
}

@media print {
  .no-print {
    display: none !important;
  }
  body, .page {
    margin: 0;
    box-shadow: none;
  }
}

.ceo-block {
  position: absolute;
  bottom: 50mm; /* sits above footer */
  font-size: 20px;
  left: 20mm;
  text-align: left;
}

.signature-block {
margin-top: 40px;
text-align: right;
padding-right: 40px;
}
.signature-block p {
margin: 0;
}

</style>
</head>
<body>
  <div class="page">
    <!-- Fixed Header -->
    <div class="header">
      <img src="../img/h.png" alt="Header Logo">
    </div>

    <div class="content">
      <!-- Bank Info -->
      <br>
      <br>
      <br>
      <table class="no-border" style="font-size:12px;">
          <tr>
            <td class="center bold small">
              Bank A/C World Diagnostic #: PK32 UNIL 0109 0003 2483 6141<br>
              Bank/Branch: United Bank (UBL), Jinnah Chowk Multan, City/State/Zip: 60000
            </td>
          </tr>
      </table>

      <!--<hr style="border:1px dotted #000; margin:4px 0;">-->

      <!-- Invoice Heading -->
      <table class="no-border">
        <tr>
          <td class="center heading">SALES INVOICE</td>
        </tr>
      </table>

      <!-- NTN -->
      <table>
        <tr>
          <td class="center bold" style="width:20%;">NTN#</td>
          <td class="center" style="width:80%;">G194453-8</td>
        </tr>
      </table>

      <!-- Customer + Invoice Details -->
      <table>
        <tr>
          <td rowspan="2" style="width:60%;">
            <b>Sold To: <?php echo $customerName; ?></b>
            <br><?php echo $customerPhone; ?>
          </td>
          <td style="width:20%;"><b>Invoice</b></td>
          <td style="width:20%;"><?php echo $orderId; ?></td>
        </tr>
        <tr>
          <td><b>Date</b></td>
          <td><?php echo $dateTime; ?></td>
        </tr>
      </table>

      <!-- Products Table -->
      <table>
        <tr class="bold center">
          <td style="width:30%;">Product Name</td>
          <td style="width:10;">Lot No.</td>
          <td style="width:20;">Expiry</td>
          <td style="width:10%;">QTY</td>
          <td style="width:10%;">Per unit price</td>
          <td style="width:10%;">Total Amount (PKR)</td>
          <td style="width:10%;">Dis(%)</td>
          <td style="width:10%;">Dis (PKR)</td>
          <td style="width:20%;">Total Amount (PKR)</td>
        </tr>
        <?php foreach ($orderDetails as $order): ?>
        <tr class="center">
          <td><?php echo $order['product_name']; ?></td>
          <td><?php echo $order['lot_no']; ?></td>
          <td><?php echo $order['expiry'];?></td>
          <td><?php echo $order['product_quantity']; ?></td>
          <td><?php echo $order['product_price']; ?></td>
          <td><?php echo $order['product_price'] * $order['product_quantity']; ?></td>
          <td><?php echo $order['discount']; ?></td>
          <td><?php echo $order['tax']; ?></td>
          <td><?php echo $order['net_amount']; ?></td>
        </tr>
        <?php endforeach; ?>
      </table>

      <?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;
      ?>

      <!-- Totals -->
      <table style="margin-top:10px; margin-left:auto; margin-right:0; width:40%; font-size:12px;">
  <tr>
    <td style="width:70%; text-align:right;"><strong>Total Amount:</strong></td>
    <td style="width:30%; text-align:right;">Rs <?php echo $discountedAmount; ?> /-</td>
  </tr>
  <tr>
    <td style="text-align:right;"><strong>Previous Amount:</strong></td>
    <td style="text-align:right;">Rs <?= (string)($pre ?? '0') ?> /-</td>
  </tr>
  <tr>
    <td style="text-align:right;"><strong>Grand Total:</strong></td>
    <td style="text-align:right;">Rs <?php echo $close; ?> /-</td>
  </tr>
  <tr>
    <td style="text-align:right;"><strong>Amount Received:</strong></td>
    <td style="text-align:right;">Rs <?php echo $cashAmount; ?> /-</td>
  </tr>
  <tr>
    <td style="text-align:right;"><strong>Cash Remaining:</strong></td>
    <td style="text-align:right;">Rs <?php echo $changeAmount; ?> /-</td>
  </tr>
</table>
<br><br>
<div class="signature-block" style="float:left;">
<p>-----------------------------</p>
<p>Authorized Signature</p>
</div>
<br><br>
      <!-- Thank you Note -->
      <div style="text-align:center; margin-top:20px;">
        <!--<p>Thank you so much for Considering Us.<br>Regards</p>-->

        <!-- Buttons (hidden in print) -->
        <div class="no-print" style="margin-top:10px;">
          <button class="no-print" onclick="window.print()">Print</button>
          <a href="../pages/dashboard.php" class="no-print">
              <button type="button">Exit</button>
          </a>
          <a href="delivery_c.php?order_id=<?php echo $orderId; ?>" class="no-print">
            <button type="button">Delivery Challan</button>
          </a>
        </div>
      </div>
    </div>

   

    <!-- Footer Image -->
    <div class="footer">
      <img src="../img/f.png" alt="Footer Logo">
    </div>
  </div>
</body>
</html>
