<?php
include "auth.php";
checkPermission(['admin','manager','staff']); // allow all roles here

require_once "db.php";

// Search/filter
$searchCustomer = isset($_GET['customer']) ? intval($_GET['customer']) : 0;
$searchFromDate = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$searchToDate   = isset($_GET['to_date']) ? $_GET['to_date'] : '';

// Fetch customers for filter dropdown
$custQuery = "SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC";
$customers = $conn->query($custQuery);

// Build sales query with optional params
$sql = "SELECT s.sale_id, s.sale_date, s.invoice_no, s.total, s.paid, s.due, s.payment_due_date, c.customer_name
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.customer_id
        WHERE 1";
$params = []; $types = "";
if ($searchCustomer > 0) { $sql .= " AND s.customer_id=?"; $types.="i"; $params[]=$searchCustomer;}
if ($searchFromDate) { $sql .= " AND s.sale_date>=?"; $types.="s"; $params[]=$searchFromDate;}
if ($searchToDate)   { $sql .= " AND s.sale_date<=?"; $types.="s"; $params[]=$searchToDate;}
$sql .= " ORDER BY s.sale_id DESC";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$sales = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sales List</title>
    <link rel="stylesheet" href="css/style.css" />
    <style>
        /* Minimal modal/table tweaks */
        .sales-list-table { width:100%; border-collapse:collapse; margin-top:12px; }
        .sales-list-table th, .sales-list-table td { border:1px solid #e6edf3; padding:8px; vertical-align:top; }
        .modal { display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.6); padding:40px 10px; box-sizing:border-box; }
        .modal .modal-content { background:#fff; margin:0 auto; max-width:1000px; width:100%; border-radius:8px; padding:16px; position:relative; }
        .modal .close { position:absolute; right:12px; top:8px; font-size:20px; cursor:pointer; }
        .form-row { display:flex; gap:12px; flex-wrap:wrap; }
        .form-group { flex:1; min-width:150px; }
        table#editProductTable, table#editProductTable th, table#editProductTable td { border:1px solid #e6edf3; border-collapse:collapse; padding:6px; }
        .summary { display:flex; gap:12px; align-items:center; margin-top:10px; flex-wrap:wrap; }
        .summary input { padding:6px; border-radius:4px; border:1px solid #ccc; }
        .btn { background:#2563eb;color:#fff;padding:8px 10px;border-radius:6px;border:0; cursor:pointer; }
        .btn-danger { background:#dc2626; }
        .btn-print { background:#10b981; }
    </style>
</head>
<body class="sales-list-page">
    <!-- Global header start -->
    <?php include("global/header.php"); ?>
    <!-- Global header end -->

    <main class="main">
        <header class="topbar">
            <button class="hamburger" id="hamburger" aria-label="Toggle menu">☰</button>
            <div style="margin-left:8px;font-weight:600">Dashboard <span class="topbar-menu-space"> > </span> Sales List</div>

            <!-- Global Notification start -->
            <?php include("global/notify.php"); ?>
            <!-- Global Notification end -->

            <div class="profile">
                <button class="profile-btn" id="profileBtn" aria-expanded="false">
                    <span>Welcome <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                    <img class="avatar" src="https://i.pravatar.cc/80" alt="Profile" />
                </button>
                <nav class="dropdown" id="profileDropdown">
                    <a href="profile.php">Profile Settings</a>
                    <a href="users.php">Users Settings</a>
                    <a href="logout.php">Logout</a>
                </nav>
            </div>
        </header>

        <section class="content">
            <div class="container">
                <form method="get" class="filter-box" style="display:flex;gap:12px;flex-wrap:wrap;">
                    <div class="form-group">
                        <label>Customer</label>
                        <select name="customer">
                            <option value="0">-- All Customers --</option>
                            <?php
                            // re-query customers for filter list (above $customers was consumed earlier)
                            $custQ2 = $conn->query("SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC");
                            while($c = $custQ2->fetch_assoc()):
                            ?>
                            <option value="<?php echo $c['customer_id'];?>" <?php if($searchCustomer==$c['customer_id']) echo "selected";?>><?php echo htmlspecialchars($c['customer_name']);?></option>
                            <?php endwhile;?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>From Date</label>
                        <input type="date" name="from_date" value="<?php echo htmlspecialchars($searchFromDate);?>">
                    </div>
                    <div class="form-group">
                        <label>To Date</label>
                        <input type="date" name="to_date" value="<?php echo htmlspecialchars($searchToDate);?>">
                    </div>
                    <div class="form-group" style="align-self:end;">
                        <button type="submit" class="btn">🔎︎ Search</button>
                    </div>
                </form>

                <table class="sales-list-table">
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Invoice</th>
                            <th>Date</th>
                            <th>Products</th>
                            <th>Total (৳)</th>
                            <th>Paid (৳)</th>
                            <th>Due (৳)</th>
                            <th style="text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($sales->num_rows>0): ?>
                            <?php while($s = $sales->fetch_assoc()): 
                                // fetch items for display
                                $stmtItems = $conn->prepare("SELECT product, size, rate, qty, subtotal FROM sale_items WHERE sale_id=?");
                                $stmtItems->bind_param("i", $s['sale_id']);
                                $stmtItems->execute();
                                $itemsResult = $stmtItems->get_result();
                            ?>
                            <tr>
                                <td><?php echo htmlspecialchars($s['customer_name']);?></td>
                                <td><?php echo htmlspecialchars($s['invoice_no']);?></td>
                                <td><?php echo htmlspecialchars($s['sale_date']);?></td>
                                <td>
                                    <?php while($item = $itemsResult->fetch_assoc()): ?>
                                        <?php
                                          // item['size'] may already be combined "size × size_qty"
                                          $sizeDisplay = htmlspecialchars($item['size']);
                                          echo htmlspecialchars($item['product']).' ('.$sizeDisplay.') - '.(int)$item['qty'].' x '.number_format($item['rate'],2).'<br>';
                                        ?>
                                    <?php endwhile;?>
                                </td>
                                <td style="text-align:right;"><?php echo number_format($s['total'],2);?></td>
                                <td style="text-align:right;"><?php echo number_format($s['paid'],2);?></td>
                                <td style="text-align:right;"><?php echo number_format($s['due'],2);?></td>
                                <td class="action-btn" style="text-align:center;">
                                    <!-- corrected: use $s not $row -->
                                    <button class="btn" type="button" onclick="openEditModal(<?= (int)$s['sale_id'] ?>)">Edit</button>
                                    <a href="sale_delete.php?id=<?php echo (int)$s['sale_id'];?>" class="btn btn-danger" onclick="return confirm('Delete this sale?')">Delete</a>
                                    <button class="btn btn-print" type="button" onclick="printInvoice(<?= (int)$s['sale_id'] ?>)">Print</button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align:center;color:#6b7280;">No sales found</td>
                            </tr>
                        <?php endif;?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- ================= Edit Sale Modal ================= -->
        <div id="editModal" class="modal" aria-hidden="true">
          <div class="modal-content" role="dialog" aria-modal="true">
            <span class="close" onclick="closeEditModal()">×</span>
            <h2>Edit Sale</h2>

            <form id="editSaleForm">
              <input type="hidden" name="sale_id" id="edit_sale_id">
              <input type="hidden" name="deleted_item_ids" id="edit_deleted_item_ids" value="">

              <div class="form-row">
                <div class="form-group">
                  <label>Customer</label>
                  <select name="customer_id" id="edit_customer_id" required>
                    <option value="">-- Select Customer --</option>
                    <?php
                    // customer list
                    $custQ3 = $conn->query("SELECT customer_id, customer_name FROM customers ORDER BY customer_name ASC");
                    while($c = $custQ3->fetch_assoc()):
                    ?>
                      <option value="<?= (int)$c['customer_id'] ?>"><?= htmlspecialchars($c['customer_name']) ?></option>
                    <?php endwhile; ?>
                  </select>
                </div>
                <div class="form-group">
                  <label>Sale Date</label>
                  <input type="date" name="sale_date" id="edit_sale_date" required>
                </div>
                <div class="form-group">
                  <label>Payment Due Date</label>
                  <input type="date" name="payment_due_date" id="edit_payment_due_date">
                </div>
              </div>

              <table id="editProductTable" style="width:100%; margin-top:10px;">
  <thead>
    <tr>
      <th>Product</th>
      <th>Size</th>
      <th>Size Qty</th>
      <th>Rate</th>
      <th>Qty</th>
      <th>Subtotal</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="edit_product_rows"></tbody>
</table>


              <div style="margin-top:8px;">
                <button type="button" class="btn" onclick="addEditRow()">+ Add Product</button>
              </div>

              <div class="summary">
                <div>Total: <input type="text" id="edit_total" name="total" readonly></div>
                <div>Paid: <input type="number" id="edit_paid" name="paid" min="0" step="0.01"></div>
                <div>Due: <input type="text" id="edit_due" name="due" readonly></div>
              </div>

              <div style="margin-top:12px;">
                <button type="submit" class="btn">Update Sale</button>
              </div>
            </form>
          </div>
        </div>




        <script>
            // Sidebar accordion: click ONLY the top-level buttons, not the whole LI.
            const submenuButtons = document.querySelectorAll(".has-submenu > .menu-link");
            submenuButtons.forEach((btn) => {
                btn.addEventListener("click", (e) => {
                    e.preventDefault(); // keep as a toggle, no page jump
                    const currentItem = btn.parentElement; // .has-submenu
                    const isOpen = currentItem.classList.contains("open");

                    // Close other open menus (accordion behavior)
                    document.querySelectorAll(".has-submenu.open").forEach((li) => {
                        if (li !== currentItem) {
                            li.classList.remove("open");
                            const b = li.querySelector(".menu-link");
                            if (b) b.setAttribute("aria-expanded", "false");
                        }
                    });

                    // Toggle current
                    currentItem.classList.toggle("open");
                    btn.setAttribute("aria-expanded", String(!isOpen));
                });
            });

            // Ensure clicks inside submenu DO NOT toggle/close the parent unintentionally
            document.querySelectorAll(".submenu").forEach((ul) => {
                ul.addEventListener("click", (e) => {
                    e.stopPropagation();
                });
            });

            // Mobile: show/hide sidebar
            const sidebar = document.getElementById("sidebar");
            const hamburger = document.getElementById("hamburger");
            hamburger.addEventListener("click", () => {
                sidebar.classList.toggle("active");
            });

            // Close sidebar when clicking outside on small screens
            document.addEventListener("click", (e) => {
                const isClickInside = sidebar.contains(e.target) || hamburger.contains(e.target);
                if (!isClickInside && sidebar.classList.contains("active")) {
                    sidebar.classList.remove("active");
                }
            });

            // Profile dropdown
            const profileBtn = document.getElementById("profileBtn");
            const profileDropdown = document.getElementById("profileDropdown");
            profileBtn.addEventListener("click", (e) => {
                e.stopPropagation();
                const open = profileDropdown.classList.toggle("open");
                profileBtn.setAttribute("aria-expanded", String(open));
            });
            document.addEventListener("click", () => profileDropdown.classList.remove("open"));
        </script>
 <script>
function openEditModal(saleId) {
  document.getElementById('edit_deleted_item_ids').value = '';
  fetch('get_sale_details.php?id=' + encodeURIComponent(saleId))
    .then(res => res.json())
    .then(data => {
      if (!data.success) {
        alert('Failed to load sale details.');
        return;
      }

      const sale = data.sale;
      const items = data.items || [];

      document.getElementById('edit_sale_id').value = sale.sale_id;
      document.getElementById('edit_customer_id').value = sale.customer_id;
      document.getElementById('edit_sale_date').value = sale.sale_date;
      document.getElementById('edit_payment_due_date').value = sale.payment_due_date || '';
      document.getElementById('edit_paid').value = parseFloat(sale.paid || 0).toFixed(2);

      const tbody = document.getElementById('edit_product_rows');
      tbody.innerHTML = '';

      items.forEach(item => {
        let s1 = 0, s2 = 1;
        if (item.size && (item.size.includes('×') || item.size.includes('x'))) {
          const parts = item.size.split(/[×xX]/);
          s1 = parseFloat(parts[0]) || 0;
          s2 = parseFloat(parts[1]) || 1;
        } else {
          s1 = parseFloat(item.size) || 0;
          s2 = item.size_qty ? parseFloat(item.size_qty) : 1;
        }

        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>
            <input type="hidden" name="item_id[]" value="${item.sale_item_id || ''}">
            <input type="text" name="product[]" value="${escapeHtml(item.product || '')}" required>
          </td>
          <td><input type="number" name="size[]" class="edit_size" min="0" step="0.01" value="${s1}"></td>
          <td><input type="number" name="size_qty[]" class="edit_size_qty" min="0" step="1" value="${s2}"></td>
          <td><input type="number" name="rate[]" class="edit_rate" min="0" step="0.01" value="${parseFloat(item.rate || 0)}"></td>
          <td><input type="number" name="qty[]" class="edit_qty" min="0" step="1" value="${parseFloat(item.qty || 0)}"></td>
          <td><input type="text" name="subtotal[]" class="edit_subtotal" readonly value="${parseFloat(item.subtotal || 0).toFixed(2)}"></td>
          <td><button type="button" class="btn btn-danger" onclick="removeEditRow(this)">Remove</button></td>
        `;
        tbody.appendChild(tr);
      });

      calculateEditTotals();
      document.getElementById('editModal').style.display = 'block';
    })
    .catch(err => {
      console.error(err);
      alert('Error fetching sale details.');
    });
}

function addEditRow() {
  const tbody = document.getElementById('edit_product_rows');
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td>
      <input type="hidden" name="item_id[]" value="">
      <input type="text" name="product[]" required>
    </td>
    <td><input type="number" name="size[]" class="edit_size" min="0" step="0.01" value="0"></td>
    <td><input type="number" name="size_qty[]" class="edit_size_qty" min="0" step="1" value="1"></td>
    <td><input type="number" name="rate[]" class="edit_rate" min="0" step="0.01" value="0"></td>
    <td><input type="number" name="qty[]" class="edit_qty" min="0" step="1" value="0"></td>
    <td><input type="text" name="subtotal[]" class="edit_subtotal" readonly value="0.00"></td>
    <td><button type="button" class="btn btn-danger" onclick="removeEditRow(this)">Remove</button></td>
  `;
  tbody.appendChild(tr);
}

const deletedIds = [];
function removeEditRow(btn) {
  const tr = btn.closest('tr');
  if (!tr) return;
  const hid = tr.querySelector('input[name="item_id[]"]');
  if (hid && hid.value) {
    deletedIds.push(hid.value);
    document.getElementById('edit_deleted_item_ids').value = deletedIds.join(',');
  }
  tr.remove();
  calculateEditTotals();
}

function calculateEditTotals() {
  let total = 0;
  const rows = document.querySelectorAll('#edit_product_rows tr');
  rows.forEach(row => {
    const size = parseFloat(row.querySelector('.edit_size')?.value || 0);
    const size_qty = parseFloat(row.querySelector('.edit_size_qty')?.value || 1);
    const rate = parseFloat(row.querySelector('.edit_rate')?.value || 0);
    const qty = parseFloat(row.querySelector('.edit_qty')?.value || 0);
    const subtotal = size * size_qty * rate * qty;
    const subEl = row.querySelector('.edit_subtotal');
    if (subEl) subEl.value = subtotal.toFixed(2);
    total += subtotal;
  });
  document.getElementById('edit_total').value = total.toFixed(2);
  const paid = parseFloat(document.getElementById('edit_paid')?.value || 0);
  let due = total - paid;
  if (due < 0) due = 0;
  document.getElementById('edit_due').value = due.toFixed(2);
}

document.addEventListener('input', function(e){
  if (e.target.matches('.edit_rate, .edit_qty, .edit_size, .edit_size_qty, #edit_paid')) {
    calculateEditTotals();
  }
});

document.getElementById('editSaleForm').addEventListener('submit', function(ev){
  ev.preventDefault();
  document.getElementById('edit_deleted_item_ids').value = deletedIds.join(',');
  const data = new FormData(ev.target);
  fetch('sale_update.php', { method: 'POST', body: data })
    .then(res => res.json())
    .then(json => {
      if (json && json.success) {
        alert('✅ Sale updated successfully.');
        closeEditModal();
        location.reload();
      } else {
        alert('❌ Update failed: ' + (json?.message || 'Unknown error'));
      }
    })
    .catch(err => {
      console.error(err);
      alert('Error while updating sale.');
    });
});

function closeEditModal() {
  document.getElementById('editModal').style.display = 'none';
}

function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function printInvoice(id) {
  window.open('sale_print.php?id=' + encodeURIComponent(id), '_blank', 'width=900,height=700');
}
</script>

        <script>
// When "View" or "Edit" button is clicked
function viewSaleDetails(saleId) {
    // Show loading spinner or disable button if you want
    fetch(`get_sale_details.php?sale_id=${saleId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const sale = data.sale;
                const items = data.items;

                // Fill sale info in modal header
                document.getElementById('modalCustomerName').textContent = sale.customer_name;
                document.getElementById('modalSaleDate').textContent = sale.sale_date;
                document.getElementById('modalTotal').textContent = sale.total;
                document.getElementById('modalPaid').textContent = sale.paid;
                document.getElementById('modalDue').textContent = sale.due;

                // Build items table
                const tbody = document.getElementById('modalItemsTableBody');
                tbody.innerHTML = '';

                let totalAmount = 0;
                let totalQty = 0;

                items.forEach((item, index) => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${item.product}</td>
                        <td>${item.size}</td>
                        <td>${item.qty}</td>
                        <td>${item.rate}</td>
                        <td>${item.subtotal}</td>
                    `;
                    tbody.appendChild(tr);

                    totalAmount += parseFloat(item.subtotal);
                    totalQty += parseFloat(item.qty);
                });

                // Update totals in modal footer
                document.getElementById('modalTotalQty').textContent = totalQty;
                document.getElementById('modalTotalAmount').textContent = totalAmount.toFixed(2);

                // Show the modal
                const modal = document.getElementById('saleDetailsModal');
                modal.style.display = 'block';
                document.body.classList.add('modal-open');
            } else {
                alert(data.message || 'Unable to load sale details.');
            }
        })
        .catch(err => {
            console.error('Error fetching sale details:', err);
            alert('Failed to load sale details.');
        });
}

// Close modal
function closeSaleModal() {
    const modal = document.getElementById('saleDetailsModal');
    modal.style.display = 'none';
    document.body.classList.remove('modal-open');
}

// Optional: close modal when clicking outside it
window.addEventListener('click', function(event) {
    const modal = document.getElementById('saleDetailsModal');
    if (event.target === modal) {
        closeSaleModal();
    }
});
</script>


    </main>
</body>
</html>
