<?php
include 'db.php';
include 'pos_header.php';
include 'pos_modals.php'; 
include 'linkrel.php';


include 'auth.php';
require_right('Access POS');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}


$last_sale = null;
$last_items = [];

if (!empty($_SESSION['last_sale_id'])) {
    $sale_id = $_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;
    }

    // Optional: unset to prevent showing same data next time
    unset($_SESSION['last_sale_id']);
}

 if ($last_sale): ?>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const receiptModal = new bootstrap.Modal(document.getElementById('payment-completed'));
        receiptModal.show();
    });
</script>
<?php endif;




// shift module
$user_id = $_SESSION['user_id'] ?? null;

$active_shift = null;
if ($user_id) {
$stmt = $conn->prepare("SELECT * FROM shifts WHERE user_id = ? AND end_time IS NULL LIMIT 1");

    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $active_shift = $result->fetch_assoc();
    $stmt->close();
}

$show_shift_modal = false;
if (!$active_shift) {
    $show_shift_modal = true;
}




// Helper to get tax rate
function getTaxRate($tax_rate_id, $conn) {
    if (!$tax_rate_id) return 0.00;
    $res = $conn->query("SELECT rate FROM tax_rates WHERE id = $tax_rate_id");
    if ($row = $res->fetch_assoc()) {
        return (float)$row['rate'];
    }
    return 0.00;
}

$categories = $conn->query("SELECT * FROM categories");
$items = $conn->query("SELECT items.*, categories.name AS category_name 
                       FROM items 
                       LEFT JOIN categories ON items.category_id = categories.id");
$customers = $conn->query("SELECT * FROM customers");



// sales order enable
$orderTypes = [];
$enabledModes = [];

$query = "
    SELECT code, name 
    FROM settings 
    WHERE category_id = 4 
      AND is_active = 1 
      AND value = '1'
";

$result = $conn->query($query);

while ($row = $result->fetch_assoc()) {
    $orderTypes[] = $row; // contains both code and name
    $enabledModes[] = $row['code']; // e.g. dine_in, take_away
}



// sales order enable


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>POS System</title>
 


</head>
<form id="order-form" method="post" action="save_sale.php" style="display:none;">
    <input type="hidden" name="customer_name" id="form-customer">
    <input type="hidden" name="cart_json" id="form-cart">
    <input type="hidden" name="tax_amount" id="form-tax">
    <input type="hidden" name="total_amount" id="form-total">

    <!-- 🆕 Added for mode and table tracking -->
    <input type="hidden" name="order_mode" id="selected-order-mode">
    <input type="hidden" name="table_id" id="selected-table-id">
</form>





<body>
<!-- 🔁 Unified Button + Search + Customer -->
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 p-2 bg-light border-bottom sticky-top"
     style="z-index: 1040; margin-top: 60px;">
  
  <!-- 🔍 Left: Search Bar -->
  <div class="flex-grow-1 me-3">
    <input type="text" id="product-search" class="form-control" placeholder="Search product...">
    <div id="autocomplete-list" class="autocomplete-items"></div>
  </div>

  <!-- 👤 Right: Customer Dropdown -->
  <div class="d-flex align-items-center gap-2">
    <select class="form-select form-select-sm" id="top-customer-select" style="min-width: 180px;">
      <?php mysqli_data_seek($customers, 0); while ($cust = $customers->fetch_assoc()): ?>
        <option><?= htmlspecialchars($cust['name']) ?></option>
      <?php endwhile; ?>
    </select>
    <a href="#" class="btn btn-sm btn-primary btn-icon" data-bs-toggle="modal" data-bs-target="#create">
      <i data-feather="user-plus" class="feather-16"></i>
    </a>
  </div>



  <!-- 🔘 Right: Order/Action Buttons -->
  <div class="d-flex flex-wrap gap-2">
    <?php foreach ($orderTypes as $order): ?>
        <?php $code = $order['code']; $name = $order['name']; ?>
        <a href="#"
           class="btn btn-sm btn-outline-dark order-mode-btn <?= ($code === 'dine_in') ? 'me-1' : '' ?>"
           data-mode="<?= $code ?>"
           <?= ($code === 'dine_in') ? 'data-bs-toggle="modal" data-bs-target="#dineInModal"' : '' ?>>
          <i data-feather="package" class="me-1"></i><?= htmlspecialchars($name) ?>
        </a>
    <?php endforeach; ?>

    <a href="#" class="btn btn-sm btn-secondary" data-bs-toggle="modal" data-bs-target="#orders">
      <i data-feather="shopping-cart" class="me-1"></i>Hold Orders
    </a>
    <a href="#" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#recents">
      <i data-feather="refresh-ccw" class="me-1"></i>Transaction
    </a>
  </div>
</div>








                <div class="row align-items-start pos-wrapper">
                    <!-- Left Section: Categories & Products -->
                    <div class="col-md-12 col-lg-8">
                        <div class="pos-categories tabs_wrapper">
                            <ul class="tabs owl-carousel pos-category">
    <li data-category="all">
        <a href="javascript:void(0);"><img src="assets/img/categories/category-01.png" alt=""></a>
        <h6><a href="javascript:void(0);">All</a></h6>
    </li>
    <?php while ($cat = $categories->fetch_assoc()): ?>
        <li data-category="<?= $cat['id'] ?>">
            <a href="javascript:void(0);"><img src="assets/img/categories/category-01.png" alt=""></a>
            <h6><a href="javascript:void(0);"><?= htmlspecialchars($cat['name']) ?></a></h6>
        </li>
    <?php endwhile; ?>
</ul>


                            <div class="pos-products">
                                <h5 class="mb-3">Products</h5>
                                <div class="tabs_container">
                                    <div class="tab_content active" data-tab="all">
                                        <div class="row" id="product-list">
                                            <?php mysqli_data_seek($items, 0); while ($item = $items->fetch_assoc()): 
                                                $taxRate = getTaxRate($item['tax_rate_id'], $conn);
                                            ?>
                                                <div class="col-sm-2 col-md-6 col-lg-3 col-xl-3">
                                                    <div class="product-info default-cover card"
     data-id="<?= $item['id'] ?>"                          
     data-category-id="<?= $item['category_id'] ?>"
     data-tax-type="<?= $item['tax_type'] ?>"
     data-tax-rate="<?= $taxRate ?>">

                                                        <a href="#" class="img-bg">
                                                           
                                                           <?php
$image = !empty($item['product_image']) ? $item['product_image'] : 'default.png';

?>
<img src="assets/img/products/<?= htmlspecialchars($image) ?>" alt="Product" onerror="this.onerror=null;this.src='assets/img/products/default.png';">

                                                            <span><i data-feather="check" class="feather-16"></i></span>
                                                        </a>
                                                        <h6 class="cat-name"><a href="#"><?php echo htmlspecialchars($item['category_name']) ?></a></h6>
                                                        <h6 class="product-name"><a href="#"><?php echo htmlspecialchars($item['name']) ?></a></h6>
                                                        <div class="d-flex justify-content-between price">
                                                            <span><?= $item['item_type'] === 'bulk' ? $item['bulk_qty'] . ' Units' : 'Loose' ?></span>
                                                            <p>Rs <?= number_format($item['retail_price']) ?></p>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endwhile; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Section: Cart -->
                    <!-- Right Section: Cart -->
<div class="col-md-12 col-lg-4 ps-0">
  <aside class="product-order-list">

    <!-- Order List Header -->
    <div class="head d-flex justify-content-between">
      <div>
        <h5>Order List</h5>
        <span>Transaction ID : #<?= time() ?></span>
      </div>
      <a href="#" class="confirm-text"><i data-feather="trash-2" class="text-danger"></i></a>
    </div>

    <!-- Product Cart Section -->
    <div class="product-added block-section" style="padding-top: 10px; padding-bottom: 10px;">
      <div class="product-wrap"></div>
    </div>

    <!-- Totals & Taxes -->
    <div class="block-section pt-2 pb-2">
      <div class="selling-info row mb-2">
        <div class="col-sm-4">
          <label>Order Tax</label>
          <input type="text" class="form-control form-control-sm" placeholder="0%" readonly>
        </div>
        <div class="col-sm-4">
          <label>Shipping</label>
          <input type="text" class="form-control form-control-sm" placeholder="0.00" readonly>
        </div>
        <div class="col-sm-4">
          <label>Discount</label>
          <input type="text" class="form-control form-control-sm" placeholder="0%" readonly>
        </div>
      </div>

      <div class="order-total">
        <table class="table table-borderless mb-1">
          <tr><td>Sub Total</td><td class="text-end" id="subtotal">Rs 0.00</td></tr>
          <tr><td>Total</td><td class="text-end" id="total">Rs 0.00</td></tr>
        </table>
      </div>
    </div>

    <!-- Grand Total -->
    <div class="d-grid btn-block mt-2 mb-2">
      <a class="btn btn-secondary btn-sm" href="#">Grand Total : Rs 0.00</a>
    </div>

    <!-- Action Buttons -->
    <div class="btn-row d-sm-flex justify-content-between gap-2 mt-1">
      <a href="#" class="btn btn-info btn-sm flex-fill" id="hold-order-btn">
        <i data-feather="pause"></i> Hold
      </a>
      <a href="#" class="btn btn-danger btn-sm flex-fill">
        <i data-feather="trash-2"></i> Void
      </a>
      <a href="#" class="btn btn-success btn-sm flex-fill" id="payment-btn">
        <i data-feather="credit-card"></i> Payment
      </a>
    </div>

  </aside>
</div>

    <?php if (isset($show_shift_modal) && $show_shift_modal): ?>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    const modal = new bootstrap.Modal(document.getElementById('shiftModal'), {
      backdrop: 'static',
      keyboard: false
    });
    modal.show();
  });
</script>
<?php endif; ?>


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

  fetch('close_shift.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.status === 'success') {
      Swal.fire({
  icon: 'success',
  title: 'Shift Closed',
  text: 'Shift closed successfully!',
  confirmButtonColor: '#3085d6',
  confirmButtonText: 'OK'
}).then(() => {
  window.location.href = 'logout.php';
});

      window.location.href = 'logout.php'; // or wherever appropriate
    } else {
    Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: data.message || 'Error closing shift',
  confirmButtonColor: '#d33'
});

    }
  })
  .catch(err => {
    alert('Network/server error.');
  });
});
</script>



<script>
  window.enabledOrderModes = <?= json_encode($enabledModes); ?>;



  document.querySelector('.confirm-text')?.addEventListener('click', function (e) {
  e.preventDefault();
  if (confirm('Clear all cart items?')) {
    document.querySelector('.product-wrap').innerHTML = '';
    updateTotal();
  }
});

</script>


</body>
</html>

