<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include 'db.php';


$branch_info = null;
$branch_result = $conn->query("SELECT branch_name, branch_address FROM branch_info LIMIT 1");
if ($branch_result && $branch_result->num_rows > 0) {
    $branch_info = $branch_result->fetch_assoc();
}


$last_sale = null;
$last_items = [];

// Load FBR config
$fbr_enabled = false;
$fbr_result = $conn->query("SELECT is_enabled FROM fbr_config LIMIT 1");
if ($fbr_result && $fbr_row = $fbr_result->fetch_assoc()) {
    $fbr_enabled = intval($fbr_row['is_enabled']) === 1;
}

if (!empty($_SESSION['last_sale_id'])) {
    $sale_id = intval($_SESSION['last_sale_id']);
    $sale_result = $conn->query("SELECT * FROM sales WHERE id = $sale_id LIMIT 1");
    $last_sale = $sale_result->fetch_assoc();

    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    while ($item = $items_result->fetch_assoc()) {
        $last_items[] = $item;
    }
}
?>
<!-- Payment Method Selection Modal -->
<!-- Payment Method Modal -->
<div class="modal fade" id="select-payment-method" tabindex="-1" aria-labelledby="paymentMethodLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="paymentMethodLabel">Select Payment Method</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <div class="modal-body text-center">
        <div class="btn-group w-100 gap-2 flex-wrap mb-2" role="group">
          <button type="button" class="btn btn-outline-primary payment-option" data-method="cash">Cash</button>
          <button type="button" class="btn btn-outline-secondary payment-option" data-method="card">Card</button>
          <button type="button" class="btn btn-outline-success payment-option" data-method="upi">UPI</button>
          <button type="button" class="btn btn-outline-warning payment-option" data-method="credit">Credit</button>
          <button type="button" class="btn btn-outline-info payment-option" data-method="bank">Bank</button>
        </div>

        <div id="bank-account-wrapper" class="d-none mt-3">
          <label for="bank-account-select" class="form-label">Select Bank Account</label>
          <select id="bank-account-select" class="form-select">
            <option value="">-- Select --</option>
            <?php
            $banks = $conn->query("SELECT id, account_title FROM bank_accounts WHERE is_active = 1");
            while ($bank = $banks->fetch_assoc()):
            ?>
              <option value="<?= $bank['id'] ?>"><?= htmlspecialchars($bank['account_title']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>

      </div>
    </div>
  </div>
</div>


<!-- Payment Completed -->
<div class="modal fade modal-default" id="payment-completed" aria-labelledby="payment-completed">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body text-center">
                <form action="pos.php">
                    <div class="icon-head">
                        <a href="#"><i data-feather="check-circle" class="feather-40"></i></a>
                    </div>
                    <h4>Payment Completed</h4>
                    <p class="mb-0">Do you want to Print Receipt for the Completed Order</p>
                    <div class="modal-footer d-sm-flex justify-content-between">
                        <button type="button" class="btn btn-primary flex-fill" data-bs-toggle="modal" data-bs-target="#print-receipt">Print Receipt</button>
                        <button type="submit" class="btn btn-secondary flex-fill">Next Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Print Receipt -->
<!-- Print Receipt -->
 
<div class="modal fade modal-default" id="print-receipt" tabindex="-1" aria-labelledby="print-receipt" aria-hidden="true" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="d-flex justify-content-end">
                <button type="button" class="close p-0" data-bs-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">

                <div class="icon-head text-center">
                    <img src="assets/img/logo.png" width="100" alt="Receipt Logo">
                </div>

                <?php if (!empty($branch_info)): ?>
                    <div class="text-center">
                        <h6><?= htmlspecialchars($branch_info['branch_name']) ?></h6>
                        <p><?= nl2br(htmlspecialchars($branch_info['branch_address'])) ?></p>
                    </div>
                <?php endif; ?>

                <?php if (!empty($last_sale)): ?>
                    <div class="tax-invoice">
                        <h6 class="text-center">Tax Invoice</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <div><strong>Name:</strong> <?= htmlspecialchars($last_sale['customer_name'] ?? 'N/A') ?></div>
                                <div><strong>Invoice No:</strong> <?= htmlspecialchars($last_sale['invoice_number'] ?? 'N/A') ?></div>
                                <?php if (!empty($fbr_enabled) && !empty($last_sale['fbr_invoice_number'])): ?>
                                    <div><strong>FBR Inv#:</strong> <?= htmlspecialchars($last_sale['fbr_invoice_number']) ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-6">
                                <div><strong>Date:</strong> <?= date('d.m.Y', strtotime($last_sale['sale_date'] ?? $last_sale['created_at'])) ?></div>
                            </div>
                        </div>
                    </div>

                    <table class="table-borderless w-100 table-fit">
                        <thead>
                            <tr>
                                <th># Item</th>
                                <th>Price</th>
                                <th>Qty</th>
                                <th class="text-end">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                                $i = 1; 
                                $subtotal = 0;
                                foreach ($last_items as $item): 
                                    $line_total = $item['unit_price'] * $item['quantity'];
                                    $subtotal += $line_total;
                            ?>
                                <tr>
                                    <td><?= $i++ ?>. <?= htmlspecialchars($item['item_name']) ?></td>
                                    <td>Rs <?= number_format($item['unit_price'], 2) ?></td>
                                    <td><?= $item['quantity'] ?></td>
                                    <td class="text-end">Rs <?= number_format($line_total, 2) ?></td>
                                </tr>
                            <?php endforeach; ?>

                            <tr>
                                <td colspan="4">
                                    <table class="table-borderless w-100">
                                        <tr>
                                            <td>Sub Total :</td>
                                            <td class="text-end">Rs <?= number_format($subtotal, 2) ?></td>
                                        </tr>
                                        <tr>
                                            <td>Discount :</td>
                                            <td class="text-end">
                                                <?php
                                                if (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'percent') {
                                                    echo number_format($last_sale['discount_value'], 2) . '%';
                                                } elseif (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'fixed') {
                                                    echo 'Rs ' . number_format($last_sale['discount_value'], 2);
                                                } else {
                                                    echo 'Rs ' . number_format($last_sale['discount_amount'] ?? 0, 2);
                                                }
                                                ?>
                                                (Rs <?= number_format($last_sale['discount_amount'] ?? 0, 2) ?>)
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>Shipping :</td>
                                            <td class="text-end">Rs 0.00</td>
                                        </tr>
                                        <tr>
                                            <td>Tax :</td>
                                            <td class="text-end">Rs <?= number_format($last_sale['tax_amount'] ?? 0, 2) ?></td>
                                        </tr>
                                        <tr>
                                            <td>Total Bill :</td>
                                            <td class="text-end">Rs <?= number_format($last_sale['total_amount'] ?? 0, 2) ?></td>
                                        </tr>
                                        <tr>
                                            <td>Total Payable :</td>
                                            <td class="text-end fw-bold">Rs <?= number_format($last_sale['net_amount'] ?? 0, 2) ?></td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="text-center invoice-bar mt-3">
                        <p>Thanks for your business!</p>
                        <img src="assets/img/barcode/qr-code.png" alt="Barcode">
                        <p>Sale #<?= htmlspecialchars($last_sale['id']) ?></p>
                        <a href="print_receipt.php?sale_id=<?= urlencode($last_sale['id']) ?>" class="btn btn-primary" target="_blank">Print Receipt</a>
                        <a href="pos.php" class="btn btn-secondary mt-2">Close Bill</a>
                
                    </div>
                <?php else: ?>
                    <div class="text-center p-4 text-muted">No sale data found.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>


<!-- Create Customer -->
<div class="modal fade" id="create" tabindex="-1" aria-labelledby="create" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Create Customer</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close"><span>×</span></button>
            </div>
            <div class="modal-body">
                <form action="add_customer.php" method="post">
                    <div class="row">
                        <div class="col-lg-6 mb-3">
                            <label>Customer Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label>Phone</label>
                            <input type="text" name="phone" class="form-control">
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label>Email</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label>Address</label>
                            <input type="text" name="address" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer d-sm-flex justify-content-end">
                        <button type="button" class="btn btn-cancel" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-submit">Submit</button>
                    </div>
                </form>
            </div>					
        </div>
    </div>
</div>



<!-- Hold Order -->
<div class="modal fade modal-default pos-modal" id="hold-order" aria-labelledby="hold-order">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header p-4">
                <h5>Hold Order</h5>
                <button type="button" class="close" data-bs-dismiss="modal"><span>×</span></button>
            </div>
            <div class="modal-body p-4">
                <form action="hold_order.php" method="post">
                    <h2 class="text-center p-4">Rs 0.00</h2>
                    <div class="mb-3">
                        <label>Order Reference</label>
                        <input class="form-control" type="text" name="reference" placeholder="Enter reference">
                    </div>
                    <p>This order will be set on hold. You can retrieve it later.</p>
                    <div class="modal-footer justify-content-end">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Confirm</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>



<!-- View Held Orders -->
<div class="modal fade" id="orders" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Held Orders</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <table class="table table-striped" id="held-orders-table">
          <thead>
            <tr>
              <th>Ref</th>
              <th>Customer</th>
              <th>Order Mode</th> <!-- 🆕 -->
              <th>Table</th>       <!-- 🆕 -->
              <th>Total</th>
              <th>Date</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <!-- JavaScript will populate -->
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>



<!-- Recent Transactions -->
<?php
// Fetch recent sales (limit 10)
$recent_sales = [];
$recent_result = $conn->query("SELECT id, invoice_number, customer_name, net_amount, created_at FROM sales ORDER BY id DESC LIMIT 10");
if ($recent_result && $recent_result->num_rows > 0) {
    while ($row = $recent_result->fetch_assoc()) {
        $recent_sales[] = $row;
    }
}
?>

<div class="modal fade pos-modal" id="recents" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header p-4">
                <h5>Recent Transactions</h5>
                <button type="button" class="close" data-bs-dismiss="modal"><span>×</span></button>
            </div>
            <div class="modal-body p-4">
                <ul class="nav nav-tabs" id="recentTabs" role="tablist">
                    <li class="nav-item">
                        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#sales">Sales</button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#returns">Returns</button>
                    </li>
                </ul>
                <div class="tab-content mt-3">
                    <div class="tab-pane fade show active" id="sales">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Invoice</th>
                                    <th>Customer</th>
                                    <th>Amount</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($recent_sales)): ?>
                                    <?php foreach ($recent_sales as $sale): ?>
                                        <tr>
                                            <td><?= date('d M Y', strtotime($sale['created_at'])) ?></td>
                                            <td><?= htmlspecialchars($sale['invoice_number']) ?></td>
                                            <td><?= htmlspecialchars($sale['customer_name'] ?: 'Walk-in') ?></td>
                                            <td>Rs <?= number_format($sale['net_amount'], 2) ?></td>
                                            <td>
                                                <a href="print_receipt.php?sale_id=<?= urlencode($sale['id']) ?>" target="_blank" class="btn btn-sm btn-primary" title="Print Receipt">
                                                    <i class="feather-printer"></i> Print
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center">No recent transactions found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="tab-pane fade" id="returns">
                        <p class="text-muted">No returns yet.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
!-- shift module -->
 <!-- Bootstrap Modal for Shift -->
<div class="modal fade" id="shiftModal" tabindex="-1" aria-labelledby="shiftModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="openShiftForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Open Shift</h5>
        </div>
        <div class="modal-body">
          <label>Opening Cash:</label>
          <input type="number" name="opening_cash" class="form-control" required>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Start Shift</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- shift closed  -->

<div class="modal fade" id="closeShiftModal" tabindex="-1" aria-labelledby="closeShiftModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="closeShiftForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Close Shift</h5>
        </div>
        <div class="modal-body">
          <label>Closing Cash:</label>
          <input type="number" name="closing_cash" class="form-control" required>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger">Confirm Close</button>
        </div>
      </div>
    </form>
  </div>
</div>





<script>

     <!-- Bootstrap Modal for Shift -->

document.getElementById('openShiftForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const formData = new FormData(this);

  fetch('start_shift.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.status === 'success') {
      location.reload();
    } else {
      alert(data.message || 'Error starting shift');
    }
  })
  .catch(err => {
    alert('Server error. Please try again.');
  });
});
</script>

<<!-- Dine In Modal -->
<div class="modal fade" id="dineInModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5>Select a Table</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">

        <?php
        $floors = $conn->query("SELECT * FROM dinein_floors WHERE is_active = 1");
        while ($floor = $floors->fetch_assoc()):
        ?>
        <div class="mb-3">
          <h6><?= htmlspecialchars($floor['name']) ?></h6>
          <div class="d-flex flex-wrap gap-2">
            <?php
            $floor_id = $floor['id'];
           $tables = $conn->query("
  SELECT t.*, 
    EXISTS (
      SELECT 1 FROM hold_orders h 
      WHERE h.table_id = t.id
    ) AS is_held
  FROM dinein_tables t 
  WHERE t.floor_id = $floor_id AND t.is_active = 1
");

            while ($table = $tables->fetch_assoc()):
            ?>
            <?php $btnClass = $table['is_held'] ? 'btn-danger' : 'btn-outline-primary'; ?>

<button type="button" class="btn <?= $btnClass ?> select-table-btn"
  data-table-id="<?= $table['id'] ?>"
  data-table-name="<?= htmlspecialchars($table['table_name']) ?>">
  <?= htmlspecialchars($table['table_name']) ?> (<?= $table['seats'] ?>)
</button>

            <?php endwhile; ?>
          </div>
        </div>
        <?php endwhile; ?>

      </div>
    </div>
  </div>
</div>

<!-- Optional: display active table name in the UI -->
<span id="active-table-name" class="badge bg-info mt-2 d-none"></span>

<script>
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll('.select-table-btn').forEach(btn => {
    btn.addEventListener('click', function () {
      const tableId = this.dataset.tableId;
      const tableName = this.dataset.tableName;

      // ✅ Set global variable for JS logic
      window.selectedOrderMode = 'dine_in';
      window.selectedTableId = tableId;

      // ✅ Set hidden inputs for form submission
      const tableInput = document.getElementById('selected-table-id');
      const modeInput = document.getElementById('selected-order-mode');
      if (tableInput) tableInput.value = tableId;
      if (modeInput) modeInput.value = 'dine_in';

      // ✅ Close modal
      const modal = bootstrap.Modal.getInstance(document.getElementById('dineInModal'));
      if (modal) modal.hide();

      // ✅ Show selected table somewhere (optional)
      const badge = document.getElementById('active-table-name');
      if (badge) {
        badge.textContent = 'Table: ' + tableName;
        badge.classList.remove('d-none');
      }

      Swal.fire({
        icon: 'success',
        title: 'Table Selected',
        text: `${tableName} is now active.`,
        timer: 1500,
        showConfirmButton: false
      });
    });
  });
});
</script>
