<?php
include("../db/cn.php");
ob_start();

$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_sale 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['user_name'];
        $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'];
        @$preAmount = $order['pre_amount'];
        $grandAmount = $order['grand_total'];
        $cashAmount = $order['cash_amount'];
        $changeAmount = $order['change_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);

$currentDate = date("Y-m-d");
$billQuery = "SELECT COUNT(DISTINCT order_id) AS total_orders FROM log_user_sale WHERE DATE(date_time) = '$currentDate'";
$billResult = mysqli_query($connection, $billQuery);
$billRow = mysqli_fetch_assoc($billResult);
$newBillNo = sprintf('%04d', $billRow['total_orders'] + 1);
?>

<!DOCTYPE html>
<html lang="ur" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>رسید</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
  <style>
    body {
        font-family: 'Quicksand', sans-serif;
        direction: rtl;
        text-align: right;
    }
    .form-control, label, select, th, td {
        text-align: right !important;
        direction: rtl !important;
    }
    .table th, .table td {
        text-align: right !important;
    }
    .input-group-text { text-align: right; }
    .btn { direction: rtl; }
    .dropdown-menu {
        right: 0;
        left: auto;
        text-align: right;
    }
    p { font-weight:700; }
    .fixed-col {
        width: 80px;
        min-width: 80px;
        max-width: 80px;
        text-align: center !important;
        white-space: nowrap;
    }
@media print {
    .no-print {
        display: none !important;
    }

    table {
        page-break-inside: auto;
        border-collapse: collapse !important;
        width: 100% !important;
        table-layout: fixed;
    }

    thead {
        display: table-header-group !important;
    }

    tfoot {
        display: table-footer-group !important;
    }

    tr {
        page-break-inside: avoid !important;
        page-break-after: auto;
    }

    td, th {
        background: none !important;
        color: #000 !important;
        font-size: 12px;
        padding: 2px;
        word-break: break-word;
    }

    body {
        margin: 0;
        padding: 0;
        width: 100% !important;
    }

    .container,
    .invoice-box {
        width: 100% !important;
        max-width: 100% !important;
        margin: 0 auto !important;
        padding: 10px !important;
        box-sizing: border-box;
        border: none !important;
    }

    .ltr {
        direction: ltr !important;
        text-align: left !important;
    }

    @page {
        size: A4 portrait;
        margin: 10mm;
    }

    h2, h5 {
        text-align: center !important;
        margin: 0;
    }

    .header-info p {
        margin: 0;
        padding: 2px 0;
        text-align: left;
        font-weight: 700;
    }
}
  </style>
</head>
<body>
<div class="invoice-box" style="border:1px solid #E1E1E2; margin-top:50px; max-width: 800px; margin:0 auto;">
<!--<div class="text-center">
  <h2>  &nbsp; &nbsp; &nbsp;Almas Copy House</h2>
  <h5>Urdu Bazar Lahore</h5>
</div>-->

<div class="header-info" style="margin-bottom: 10px;">
  <p>Bill#: <?php echo $newBillNo; ?> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Name: <?php echo strtoupper($customerName); ?></p>


  <p></p>
</div>

  <?php foreach ($orderDetails as $order): ?>
    <?php
    $totalQ = 0;
    for ($i = 1; $i <= 10; $i++) {
        $totalQ += floatval($order['pr' . $i]);
    }
    if ($totalQ === 0) continue;

    $thLabels = [
        1 => 'کھلا رول',
        2 => 'چار لائن',
        3 => 'خانہ',
        4 => 'تنگ',
        5 => 'بړا خانہ',
        6 => 'بړا چار لائن',
        7 => 'سفید',
        8 => 'کھلا سائنس',
        9 => 'تنگ سائنس',
        10 => 'مکس'
    ];
    ?>
    <table class="table table-striped text-center table-sm " >
      <thead>
        <tr>
          <th>نام</th>
          <?php for ($i = 1; $i <= 10; $i++): ?>
            <?php if (floatval($order['pr' . $i])): ?>
              <th><?php echo $thLabels[$i]; ?></th>
            <?php endif; ?>
          <?php endfor; ?>
          <th class="fixed-col">کل بنڈل</th>
          <th class="fixed-col">ریٹ</th>
          <th class="fixed-col">ٹوٹل</th>
        </tr>
      </thead>
      <tbody>
        <tr style='border-bottom:2px solid #000;'>
          <td><?php echo htmlspecialchars($order['product_name']); ?></td>
          <?php for ($i = 1; $i <= 10; $i++): ?>
            <?php if (floatval($order['pr' . $i])): ?>
              <td><?php echo floatval($order['pr' . $i]); ?></td>
            <?php endif; ?>
          <?php endfor; ?>
          <td class="fixed-col"><?php echo htmlspecialchars($totalQ); ?></td>
          <td class="fixed-col"><?php echo htmlspecialchars($order['product_price']); ?></td>
          <td class="fixed-col"><?php echo htmlspecialchars(floatval($order['product_price']) * $totalQ); ?></td>
        </tr>
      </tbody>
    </table>
  <?php endforeach; ?>

  <div class="mt-4">
    <p>بل رقم :<?php echo '&nbsp;' . $totalAmount; ?> </p>
    <p> سابقہ  رقم:<?php echo '&nbsp;' . $preAmount; ?> </p>
    <p>بقایا رقم
      <?php echo '&nbsp;' . $grandAmount; ?> </p>

  </div>

  <div>
    <?php
      $date = new DateTime();
      echo $date->format('l, F j, Y g:i:s A');
    ?>
  </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) {
              $updateQuery = "UPDATE creditor_closing SET remain_balance = $changeAmount WHERE creditor_name = '$customerName'";
              $updateResult = mysqli_query($connection, $updateQuery);

              if ($updateResult) {
                  echo "<script>alert('Back to Add Sale'); location.href='mainpo.php';</script>";
                  exit;
              } else {
                  echo "<p style='color:red;'>Update failed: " . mysqli_error($connection) . "</p>";
              }
          } else {
              $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) {
                  header("Location: mainpo.php");
                  exit;
              } else {
                  echo "<p style='color:red;'>Insert failed: " . mysqli_error($connection) . "</p>";
              }
          }
      }
  }
  ?>

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