<?php
session_start();
$pageTitle = 'Sales';
require_once('./config/db.php');
require_once("./includes/auth.php");
include('./includes/header.php');

// Load products
$products = $pdo->query("SELECT ProductID, Name, SellingPrice, StockQuantity, Photo FROM products ORDER BY Name ASC")->fetchAll();
$cartCount = isset($_SESSION['cart']) ? array_sum(array_column($_SESSION['cart'], 'Qty')) : 0;
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h3><i class="bi bi-cart-plus"></i> New Sale</h3>
  <div>
    <a href="cart.php" class="btn btn-outline-primary">
      Cart <span class="badge bg-primary"><?= $cartCount ?></span>
    </a>
  </div>
</div>

<div class="row g-4">
  <!-- LEFT FORM -->
  <div class="col-lg-5">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <form id="addToCartForm" method="post" action="./actions/add_to_cart.php">

          <div class="mb-3">
            <label class="form-label">Product</label>
            <select class="form-select" name="ProductID" id="ProductID" required>
              <option value="">— Select product —</option>
              <?php foreach ($products as $p): ?>
                <option value="<?= htmlspecialchars($p['ProductID']) ?>"
                  data-name="<?= htmlspecialchars($p['Name']) ?>"
                  data-price="<?= htmlspecialchars($p['SellingPrice']) ?>"
                  data-stock="<?= (int)$p['StockQuantity'] ?>">
                  <?= htmlspecialchars($p['Name']) ?> (Stock: <?= (int)$p['StockQuantity'] ?>)
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Price</label>
            <input type="number" step="0.01" name="PricePerUnit" id="PricePerUnit" class="form-control" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Quantity</label>
            <input type="number" name="Quantity" id="Quantity" min="1" class="form-control" value="1" required>
            <div class="form-text" id="stockHint"></div>
          </div>

          <input type="hidden" name="Name" id="ProductName">

          <button class="btn btn-primary w-100" type="submit">
            <i class="bi bi-plus-lg"></i> Add to cart
          </button>

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

  <!-- RIGHT PRODUCT GRID -->
  <div class="col-lg-7">
    <div class="card shadow-sm border-0">
      <div class="card-body">
        <h6 class="mb-3">Quick product list</h6>

        <!-- SEARCH BAR (ONE TIME ONLY) -->
        <div class="mb-3">
          <label class="form-label">Search Product</label>
          <input type="text" id="productSearch" class="form-control" placeholder="Search by name...">
        </div>

        <div class="row" id="productList">
          <?php foreach ($products as $p): ?>
            <div class="col-12 col-md-6 mb-3 product-card-item"
              data-name="<?= strtolower(htmlspecialchars($p['Name'])) ?>">

              <!-- CLICKABLE PRODUCT CARD -->
              <div class="d-flex align-items-center gap-3 p-2 border rounded clickable-product"
                data-id="<?= $p['ProductID'] ?>"
                data-name="<?= htmlspecialchars($p['Name']) ?>"
                data-price="<?= $p['SellingPrice'] ?>"
                data-stock="<?= (int)$p['StockQuantity'] ?>">

                <div style="width:64px;">
                  <?php if (!empty($p['Photo'])): ?>
                    <img src="./uploads/<?= htmlspecialchars($p['Photo']) ?>" class="img-fluid rounded">
                  <?php else: ?>
                    <div class="bg-light text-center py-2 rounded">No Image</div>
                  <?php endif; ?>
                </div>

                <div class="flex-grow-1">
                  <div class="fw-semibold"><?= htmlspecialchars($p['Name']) ?></div>
                  <small class="text-muted">
                    <?= number_format($p['SellingPrice'], 2) ?> — Stock: <?= (int)$p['StockQuantity'] ?>
                  </small>
                </div>

              </div>

            </div>
          <?php endforeach; ?>
        </div>

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

</div>

<!-- JS: Auto-fill form when clicking product -->
<script>
  const sel = document.getElementById('ProductID');
  const qty = document.getElementById('Quantity');
  const ppu = document.getElementById('PricePerUnit');
  const stockHint = document.getElementById('stockHint');
  const pname = document.getElementById('ProductName');

  // Select dropdown changes form
  sel.addEventListener('change', function() {
    const opt = this.selectedOptions[0];
    if (!opt) return;

    ppu.value = opt.dataset.price;
    pname.value = opt.dataset.name;
    qty.value = 1;
    stockHint.textContent = "Available: " + opt.dataset.stock;
  });

  // Clickable product cards
  document.querySelectorAll('.clickable-product').forEach(card => {
    card.addEventListener('click', function() {

      const id = this.dataset.id;
      const name = this.dataset.name;
      const price = this.dataset.price;
      const stock = this.dataset.stock;

      // Set dropdown to selected product
      sel.value = id;

      // Update form fields
      ppu.value = price;
      qty.value = 1;
      pname.value = name;
      stockHint.textContent = "Available: " + stock;

      // Highlight clicked card (optional)
      document.querySelectorAll('.clickable-product').forEach(c => c.classList.remove('border-primary'));
      this.classList.add('border-primary');
    });
  });

  // Prevent over-quantity
  qty.addEventListener('input', function() {
    const stock = sel.selectedOptions[0]?.dataset.stock || 0;
    if (parseInt(this.value) > parseInt(stock)) {
      this.classList.add('is-invalid');
    } else {
      this.classList.remove('is-invalid');
    }
  });

  // CLICK PRODUCT → AUTO FILL LEFT FORM
  document.querySelectorAll('.clickable-product').forEach(card => {
    card.addEventListener('click', function() {

      document.getElementById('ProductID').value = this.dataset.id;
      document.getElementById('PricePerUnit').value = this.dataset.price;
      document.getElementById('Quantity').value = 1;
      document.getElementById('stockHint').textContent = "Available: " + this.dataset.stock;
      document.getElementById('ProductName').value = this.dataset.name;

      // Highlight selected product (optional)
      document.querySelectorAll('.clickable-product').forEach(c => c.classList.remove('selected'));
      this.classList.add('selected');
    });
  });


  // PRODUCT SEARCH (RIGHT SIDE)
  document.getElementById('productSearch').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();

    document.querySelectorAll('.product-card-item').forEach(card => {
      let name = card.getAttribute('data-name');

      card.style.display = name.includes(filter) ? "" : "none";
    });
  });
</script>

<?php include('./includes/footer.php'); ?>