<?php
require 'auth_check.php';
require_once 'db.php';

$stmt = $pdo->query("SELECT id, name FROM departments ORDER BY name ASC");
$departments = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT name FROM departments ORDER BY name ASC");
$stmt->execute();
$departmentsAutocomplete = $stmt->fetchAll(PDO::FETCH_COLUMN);

$contacts = [];
$stmt = $pdo->query("SELECT DISTINCT contact FROM transactions WHERE contact IS NOT NULL AND contact <> '' ORDER BY contact ASC");
while ($row = $stmt->fetch()) { $contacts[] = $row['contact']; }

$emails = [];
$stmt = $pdo->query("SELECT DISTINCT email FROM transactions WHERE email IS NOT NULL AND email <> '' ORDER BY email ASC");
while ($row = $stmt->fetch()) { $emails[] = $row['email']; }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Transaction Details | Mei Hotel Penang</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="assets/style.css">
<style>
/* ── Layout: full-height card with no page scroll ── */
html, body { height: 100%; overflow: hidden; }
.page-wrap  { display: flex; height: 100vh; overflow: hidden; }
.main-col   { flex: 1; display: flex; flex-direction: column; overflow: hidden; padding: 16px; min-width: 0; }
.card       { background: #fff; border-radius: 16px; box-shadow: 0 1px 4px rgba(0,0,0,.08);
              display: flex; flex-direction: column; flex: 1; overflow: hidden; padding: 20px 24px 16px; min-height: 0; }

/* ── Aligned table: fixed layout, thead+tbody same widths ── */
.tx-table-wrap { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border: 1px solid #e5e7eb; border-radius: 10px; }
.tx-table      { width: 100%; table-layout: fixed; border-collapse: collapse; }
.tx-table thead { display: table; width: 100%; background: #f3f4f6; }
.tx-table tbody { display: block; overflow-y: auto; height: calc(100vh - 270px); }
.tx-table tbody tr { display: table; width: 100%; table-layout: fixed; }

/* Column widths — must match between thead and tbody */
.tx-table .col-date   { width: 9%; }
.tx-table .col-item   { width: 26%; }
.tx-table .col-dept   { width: 17%; }
.tx-table .col-vendor { width: 20%; }
.tx-table .col-unit   { width: 6%; }
.tx-table .col-price  { width: 10%; }
.tx-table .col-terms  { width: 7%; }
.tx-table .col-action { width: 5%; }

.tx-table th { padding: 11px 12px; font-size: 13px; font-weight: 600; text-transform: uppercase;
               letter-spacing: .05em; color: #374151; border-bottom: 1px solid #e5e7eb; }
.tx-table td { padding: 10px 12px; font-size: 15px; color: #374151; border-bottom: 1px solid #f3f4f6;
               overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; }
.tx-table tbody tr:last-child td { border-bottom: none; }
.tx-table tbody tr:hover td { background: #eff6ff; }

/* Sortable header */
.tx-table th[data-sort] { cursor: pointer; user-select: none; }
.tx-table th[data-sort]:hover { background: #e5e7eb; }

/* ── Toast ── */
#toast-container { position:fixed; bottom:24px; right:24px; z-index:9999; display:flex; flex-direction:column; gap:8px; pointer-events:none; }
.toast { display:flex; align-items:center; gap:10px; padding:12px 16px; border-radius:10px; font-size:14px; font-weight:500;
         min-width:240px; max-width:360px; box-shadow:0 4px 16px rgba(0,0,0,.12); pointer-events:auto; animation:slideIn .25s ease; }
.toast.success { background:#dcfce7; color:#166534; border:1px solid #bbf7d0; }
.toast.error   { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }
@keyframes slideIn { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:none} }
@keyframes fadeOut { to{opacity:0;transform:translateY(8px)} }
.toast.hiding { animation:fadeOut .3s ease forwards; }

/* ── Pagination ── */
.page-btn { padding:5px 12px; border-radius:6px; border:1px solid #d1d5db; font-size:15px; cursor:pointer; background:#fff; color:#374151; transition:all .15s; }
.page-btn:hover:not(:disabled) { background:#f3f4f6; }
.page-btn.active { background:#2563eb; color:#fff; border-color:#2563eb; }
.page-btn:disabled { opacity:.4; cursor:not-allowed; }

/* ── Filter chips ── */
.chip { display:inline-flex; align-items:center; gap:4px; padding:2px 8px; background:#dbeafe; color:#1d4ed8; font-size:14px; border-radius:99px; }
.chip button { font-size:16px; line-height:1; color:#1d4ed8; cursor:pointer; background:none; border:none; }

/* ── Shimmer ── */
.shimmer-cell div { height:14px; border-radius:4px; background:linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%);
                    background-size:200% 100%; animation:shimmer 1.2s infinite; }
@keyframes shimmer { to{background-position:-200% 0} }

/* ── Modal sizing ── */
.modal-inner { max-height: 87vh; overflow-y: auto; }

input[type=date] { font-family:inherit; }
</style>
</head>
<body class="bg-gray-100">

<div id="toast-container"></div>

<div style="display:flex;flex-direction:row;height:100vh;overflow:hidden;width:100%;">
  <?php include 'sidebar.php'; ?>

  <div style="flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden;padding:16px;box-sizing:border-box;">
    <div style="background:#fff;border-radius:16px;box-shadow:0 1px 4px rgba(0,0,0,.08);display:flex;flex-direction:column;flex:1;overflow:hidden;padding:20px 24px 16px;min-height:0;box-sizing:border-box;">

      <!-- ── Header ── -->
      <div class="flex items-center justify-between mb-4 relative flex-shrink-0">
        <div class="flex gap-2">
          <button id="openDepartmentModal" class="px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-sm font-medium">Department</button>
          <button id="openPettyCashModal"  class="px-3 py-1.5 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition text-sm font-medium">Petty Cash</button>
        </div>
        <h1 class="text-xl font-bold text-gray-800 absolute left-1/2 -translate-x-1/2 whitespace-nowrap">Transaction Details</h1>
        <a href="transaction_form.php?action=add" title="Add Transaction (Alt+N)"
                style="padding:6px 14px;background:#16a34a;color:#fff;border-radius:8px;font-size:15px;font-weight:600;display:flex;align-items:center;gap:6px;text-decoration:none;transition:background .15s;"
                onmouseover="this.style.background='#15803d'" onmouseout="this.style.background='#16a34a'">
            <svg xmlns="http://www.w3.org/2000/svg" style="width:15px;height:15px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
            </svg>
            Add <span style="opacity:.6;font-size:11px;margin-left:2px" class="hidden md:inline">Alt+N</span>
        </a>
      </div>

      <!-- ── Search & Filter Row ── -->
      <div class="mb-2 grid grid-cols-5 gap-2 flex-shrink-0">
        <input type="text" id="searchItem"   placeholder="Search item…"       class="border rounded-lg px-3 py-1.5 text-base focus:outline-none focus:ring-2 focus:ring-blue-400">
        <input type="text" id="searchDept"   placeholder="Search department…" class="border rounded-lg px-3 py-1.5 text-base focus:outline-none focus:ring-2 focus:ring-blue-400">
        <input type="text" id="searchVendor" placeholder="Search vendor…"     class="border rounded-lg px-3 py-1.5 text-base focus:outline-none focus:ring-2 focus:ring-blue-400">
        <input type="date" id="dateFrom"     title="From date"                class="border rounded-lg px-3 py-1.5 text-base focus:outline-none focus:ring-2 focus:ring-blue-400">
        <input type="date" id="dateTo"       title="To date"                  class="border rounded-lg px-3 py-1.5 text-base focus:outline-none focus:ring-2 focus:ring-blue-400">
      </div>

      <!-- ── Filter chips ── -->
      <div id="filterChips" class="flex flex-wrap gap-1.5 mb-2 flex-shrink-0 hidden"></div>

      <!-- ── Table (single table, aligned) ── -->
      <div class="tx-table-wrap">
        <table class="tx-table">
          <thead>
            <tr>
              <th class="col-date  text-center" data-sort="inv_date">INV Date <span class="sort-icon">↕</span></th>
              <th class="col-item  text-left"   data-sort="item">Item <span class="sort-icon">↕</span></th>
              <th class="col-dept  text-left"   data-sort="department">Department <span class="sort-icon">↕</span></th>
              <th class="col-vendor text-left"  data-sort="vendor">Vendor <span class="sort-icon">↕</span></th>
              <th class="col-unit  text-center">Unit</th>
              <th class="col-price text-right"  data-sort="price">Unit Price (RM) <span class="sort-icon">↕</span></th>
              <th class="col-terms text-center">Terms</th>
              <th class="col-action text-center">Actions</th>
            </tr>
          </thead>
          <tbody id="transactionTableBody">
            <!-- rows injected by JS -->
          </tbody>
        </table>
      </div>

      <!-- ── Pagination + count ── -->
      <div class="flex items-center justify-between mt-3 flex-shrink-0 flex-wrap gap-2">
        <div id="recordCount" class="text-sm text-gray-500"></div>
        <div id="pagination" class="flex items-center gap-1 flex-wrap"></div>
      </div>

    </div><!-- /card -->
  </div><!-- /main-col -->
</div><!-- /page-wrap -->


<!-- ═══════════════════════ DEPARTMENT MODAL ═══════════════════════ -->
<div id="departmentModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white w-full max-w-3xl rounded-2xl shadow-xl p-6 relative flex flex-col" style="min-height:70vh;max-height:80vh">
    <div class="relative flex items-center justify-center flex-shrink-0 mb-4">
      <h2 class="text-xl font-bold text-gray-800">Departments</h2>
      <button onclick="document.getElementById('addDepartmentModal').classList.remove('hidden')" class="absolute left-0 px-3 py-1.5 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition">+ Add</button>
      <button id="closeDepartmentModal" class="absolute right-0 text-gray-400 hover:text-gray-600">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>
    <input type="text" id="departmentSearch" placeholder="Search department…"
           class="mb-3 w-full px-4 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
    <div class="flex-1 overflow-y-auto border rounded-lg">
      <table class="w-full text-sm">
        <thead class="bg-gray-100 sticky top-0">
          <tr>
            <th class="px-4 py-2 text-left font-semibold text-gray-700 uppercase text-xs">Name</th>
            <th class="px-4 py-2 text-center font-semibold text-gray-700 uppercase text-xs w-40">Actions</th>
          </tr>
        </thead>
        <tbody id="departmentTbody" class="divide-y">
          <?php foreach ($departments as $row): ?>
          <tr class="hover:bg-gray-50 transition">
            <td class="px-4 py-2 text-gray-800"><?= htmlspecialchars($row['name']) ?></td>
            <td class="px-4 py-2">
              <div class="flex gap-2 justify-center">
                <button class="edit-btn px-3 py-1 text-xs bg-yellow-400 text-white rounded hover:bg-yellow-500 transition"
                        data-dept-id="<?= $row['id'] ?>" data-dept-name="<?= htmlspecialchars($row['name'], ENT_QUOTES) ?>">Edit</button>
                <button class="dept-delete-btn px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 transition"
                        data-dept-id="<?= $row['id'] ?>" data-dept-name="<?= htmlspecialchars($row['name'], ENT_QUOTES) ?>">Delete</button>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ═══════════════════════ ADD DEPARTMENT MODAL ═══════════════════════ -->
<div id="addDepartmentModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[60] hidden">
  <div class="bg-white w-full max-w-md rounded-2xl shadow-xl p-6 relative">
    <div class="relative mb-4">
      <h2 class="text-xl font-bold text-gray-800 text-center">Add Department</h2>
      <button id="closeAddDepartmentModal" onclick="document.getElementById('addDepartmentModal').classList.add('hidden')" class="absolute right-0 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>
    <form id="addDepartmentForm">
      <div class="mb-4">
        <label for="departmentName" class="block text-gray-700 font-semibold mb-2">Department Name</label>
        <input type="text" id="departmentName" name="departmentName" placeholder="Enter department name"
               class="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
      </div>
      <button type="submit" class="w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
        Submit
      </button>
    </form>
  </div>
</div>

<!-- ═══════════════════════ CONFIRM MODAL ═══════════════════════ -->
<div id="confirmModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]">
  <div class="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 text-center">
    <h2 id="confirmTitle" class="text-lg font-semibold mb-3">Confirm</h2>
    <p id="confirmMessage" class="text-gray-600 mb-6 text-sm">Are you sure?</p>
    <div class="flex justify-center gap-3">
      <button id="confirmCancel" class="px-5 py-2 border rounded-lg hover:bg-gray-100 transition text-sm">Cancel</button>
      <button id="confirmOk"     class="px-5 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition text-sm">Yes, proceed</button>
    </div>
  </div>
</div>
<!-- Success Modal -->
<div id="successModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-2xl shadow-xl p-6 w-full max-w-md relative text-center">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Success</h2>
        <p id="successMessage" class="text-gray-700 mb-6">Department added successfully!</p>
        <button id="successOkBtn" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">OK</button>
    </div>
</div>

<!-- Add Transaction Modal -->
<div id="addTransactionModal" class="fixed inset-0 bg-black bg-opacity-40 backdrop-blur-sm flex items-center justify-center hidden z-50 transition-opacity duration-300">
  <div class="bg-white rounded-2xl shadow-2xl p-8 relative" style="max-height:87vh; overflow-y:auto; width:900px; max-width:95vw;">
    
    <!-- Header -->
    <div class="flex justify-between items-center mb-5 pb-3">
      <h2 class="text-2xl font-semibold text-center flex-1">Add Transaction</h2>
      <button id="closeModalBtn" class="text-gray-400 hover:text-gray-700 transition-transform hover:scale-110">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>

<form id="transactionForm" method="POST" class="space-y-5" enctype="multipart/form-data" action="add_transaction.php">

      <!-- Row 1 -->
      <div class="grid grid-cols-4 gap-4">
<div>
  <label class="font-medium">PO Date</label>
  <input type="date" name="po_date" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
</div>
        <div><label class="font-medium">PO Number</label><input type="text" name="po_number" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
        <div><label class="font-medium">INV Date</label><input type="date" name="inv_date" value="<?= date('Y-m-d') ?>" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
        <div><label class="font-medium">INV/PI/CN No</label><input type="text" name="inv_number" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required></div>
      </div>

      <!-- Row 2 -->
      <div class="grid grid-cols-2 gap-4">
<div class="relative w-full">
    <label class="font-medium">Vendor</label>
    <input
        type="text"
        id="vendorInputUnique"
        name="vendor"
        autocomplete="off"
        placeholder="Select or type vendor"
        class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none focus:ring-2 focus:ring-blue-400 box-border" required
    >

    <div
        id="vendorDropdownUnique"
        class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"
    ></div>
</div>
<div class="relative w-full">
    <label class="font-medium">Item</label>
    <input
        type="text"
        id="itemInputUnique"
        name="item"
        autocomplete="off"
        placeholder="Select or type item"
        class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none focus:ring-2 focus:ring-blue-400 box-border" required
    >

    <div
        id="itemDropdownUnique"
        class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"
    ></div>
</div>
</div>

      <!-- Row 3: Department + Department Remarks -->
      <div class="grid grid-cols-2 gap-4">
        <div class="relative">
          <label class="font-medium">Department</label>
          <input type="text" id="departmentInput" name="department" placeholder="Select Department" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off" required>
          <div id="departmentDropdown" class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"></div>
        </div>
        <div>
          <label class="font-medium">Department Remarks</label>
          <input type="text" name="department_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
        </div>
      </div>

      <!-- Row 4: Unit, UOM, Price, Row Remarks -->
<div class="grid grid-cols-4 gap-4">
  <div>
    <label class="font-medium">Unit</label>
    <input type="text" name="unit" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required>
  </div>
  <div>
    <label class="font-medium">UOM</label>
    <input type="text" name="uom" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
  </div>
  <div>
    <label class="font-medium">Prices (RM)</label>
    <input type="text" name="price" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required>
  </div>
  <div>
    <label class="font-medium">Price Remarks</label>
    <input type="text" name="row_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
  </div>
</div>

      <!-- Row 5: SST, Total Price, Min Amount -->
      <div class="grid grid-cols-3 gap-4">
        <div><label class="font-medium">SST (%)</label><input type="number" name="sst" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
<div>
  <label class="font-medium">Total Price (RM)</label>
  <input type="text" name="total_price" class="border border-gray-300 rounded-lg w-full p-3 bg-gray-50 focus:outline-none box-border" readonly>
</div>
<div>
  <label class="font-medium">Min Amount for Delivery (RM)</label>
  <input type="text" name="min_amount_for_delivery" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
</div>
      </div>

      <!-- Row 6: Contact, Email, Person in Charge -->
      <div class="grid grid-cols-3 gap-4">
<div class="relative contact-wrapper">
    <label class="font-medium">Contact</label>
    <input type="text" name="contact" class="contactInput border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off">
    <div class="contactDropdown absolute left-0 right-0 bg-white border border-gray-300 rounded shadow-md z-50 hidden max-h-60 overflow-auto"></div>
</div>
<div class="relative email-wrapper">
    <label class="font-medium">Email</label>
    <input type="email" name="email" class="emailInput border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off">
    <div class="emailDropdown absolute left-0 right-0 bg-white border border-gray-300 rounded shadow-md z-50 hidden max-h-60 overflow-auto"></div>
</div>
        <div><label class="font-medium">Person In Charge</label><input type="text" name="person_in_charge" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
      </div>

      <!-- Row 7: Terms + Payment Remarks -->
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="font-medium">Terms</label>
          <select name="terms" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
            <option value="Cash">Cash</option>
            <option value="Cash - Ms. Wong">Cash - Ms. Wong</option>
            <option value="Terms">Terms</option>
          </select>
        </div>
        <div>
          <label class="font-medium">Payment Remarks</label>
          <input type="text" name="payment_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
        </div>
      </div>

      <!-- Row 8: Remarks + Invoice Upload -->
      <div class="grid grid-cols-2 gap-4 items-start">
        <div>
          <label class="font-medium">Remarks</label>
          <textarea name="remarks" class="border border-gray-300 rounded-lg w-full p-3 resize-none focus:outline-none box-border"></textarea>
        </div>

        <div class="flex flex-col gap-1 h-20">
          <label class="font-medium">Upload Invoice</label>
          <input type="file" name="invoice_file" accept=".pdf,.jpg,.png,.jpeg"
                 class="border border-gray-300 rounded-lg w-full p-2 focus:outline-none box-border">
          <span class="text-sm text-gray-500">Allowed: PDF, JPG, PNG</span>
        </div>
      </div>

      <!-- Submit -->
      <div class="flex justify-end mt-6">
        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-6 py-3 rounded-lg shadow-md transition-transform hover:scale-105">
          Add Transaction
        </button>
      </div>

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

<!-- Edit Transaction Modal -->
<div id="editTransactionModal" class="fixed inset-0 bg-black bg-opacity-40 backdrop-blur-sm flex items-center justify-center hidden z-50 transition-opacity duration-300">
  <div class="bg-white rounded-2xl shadow-2xl p-8 relative" style="max-height:87vh; overflow-y:auto; width:900px; max-width:95vw;">
    
    <!-- Header -->
    <div class="flex justify-between items-center mb-5 pb-3">
      <h2 class="text-2xl font-semibold text-center flex-1">Edit Transaction</h2>
      <button id="closeEditModalBtn" class="text-gray-400 hover:text-gray-700 transition-transform hover:scale-110">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>

    <form id="editTransactionForm" method="POST" enctype="multipart/form-data" class="space-y-5">

      <!-- Hidden ID -->
      <input type="hidden" name="id" value="">

      <!-- Row 1 -->
      <div class="grid grid-cols-4 gap-4">
        <div><label class="font-medium">PO Date</label><input type="date" name="po_date" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
        <div><label class="font-medium">PO Number</label><input type="text" name="po_number" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
        <div><label class="font-medium">INV Date</label><input type="date" name="inv_date" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
<div>
    <label class="font-medium">INV/PI/CN No</label>
    <input type="text" name="inv_number" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required>
</div>
      </div>

      <!-- Row 2 -->
      <div class="grid grid-cols-2 gap-4">
<div class="relative w-full">
    <label class="font-medium">Vendor</label>
    <input
        type="text"
        id="vendorInputForm2"
        name="vendor"
        autocomplete="off"
        placeholder="Select or type vendor"
        class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none focus:ring-2 focus:ring-blue-400 box-border" required
    >

    <div
        id="vendorDropdownForm2"
        class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"
    ></div>
</div>
<div class="relative w-full">
    <label class="font-medium">Item</label>
    <input
        type="text"
        id="itemInputForm2"
        name="item"
        autocomplete="off"
        placeholder="Select or type item"
        class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none focus:ring-2 focus:ring-blue-400 box-border" required
    >

    <div
        id="itemDropdownForm2"
        class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"
    ></div>
</div>
</div>

      <!-- Row 3: Department + Remarks -->
      <div class="grid grid-cols-2 gap-4">
        <div class="relative">
          <label class="font-medium">Department</label>
          <input type="text" id="editDepartmentInput" name="department" placeholder="Select Department" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off" required>
          <div id="editDepartmentDropdown" class="absolute border border-gray-300 rounded-lg mt-1 max-h-40 overflow-y-auto hidden bg-white w-full z-50 box-border"></div>
        </div>
        <div>
          <label class="font-medium">Department Remarks</label>
          <input type="text" name="department_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
        </div>
      </div>

      <!-- Row 4: Unit, UOM, Price, Row Remarks -->
      <div class="grid grid-cols-4 gap-4">
<div>
  <label class="font-medium">Unit</label>
  <input type="text" name="unit" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required>
</div>
        <div><label class="font-medium">UOM</label><input type="text" name="uom" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
<div>
  <label class="font-medium">Prices (RM)</label>
  <input type="text" name="price" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" required>
</div>
        <div><label class="font-medium">Price Remarks</label><input type="text" name="row_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
      </div>

      <!-- Row 5: SST, Total Price, Min Amount -->
      <div class="grid grid-cols-3 gap-4">
        <div><label class="font-medium">SST (%)</label><input type="number" name="sst" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
        <div><label class="font-medium">Total Price (RM)</label><input type="text" name="total_price" class="border border-gray-300 rounded-lg w-full p-3 bg-gray-50 focus:outline-none box-border" readonly></div>
<div>
  <label class="font-medium">Min Amount for Delivery (RM)</label>
  <input type="text" name="min_amount_for_delivery" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
</div>
      </div>

      <!-- Row 6: Contact, Email, Person in Charge -->
      <div class="grid grid-cols-3 gap-4">
<div class="relative contact-wrapper">
    <label class="font-medium">Contact</label>
    <input type="text" name="contact" class="contactInput border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off">
    <div class="contactDropdown absolute left-0 right-0 bg-white border border-gray-300 rounded shadow-md z-50 hidden max-h-60 overflow-auto"></div>
</div>
<div class="relative email-wrapper">
    <label class="font-medium">Email</label>
    <input type="email" name="email" class="emailInput border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border" autocomplete="off">
    <div class="emailDropdown absolute left-0 right-0 bg-white border border-gray-300 rounded shadow-md z-50 hidden max-h-60 overflow-auto"></div>
</div>
        <div><label class="font-medium">Person In Charge</label><input type="text" name="person_in_charge" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border"></div>
      </div>

      <!-- Row 7: Terms + Payment Remarks -->
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="font-medium">Terms</label>
          <select name="terms" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
            <option value="Cash">Cash</option>
            <option value="Cash - Ms. Wong">Cash - Ms. Wong</option>
            <option value="Terms">Terms</option>
          </select>
        </div>
        <div>
          <label class="font-medium">Payment Remarks</label>
          <input type="text" name="payment_remarks" class="border border-gray-300 rounded-lg w-full p-3 focus:outline-none box-border">
        </div>
      </div>

      <!-- Row 8: Remarks + Invoice Upload -->
      <div class="grid gap-4 items-start">
        <div>
          <label class="font-medium">Remarks</label>
          <textarea name="remarks" class="border border-gray-300 rounded-lg w-full p-3 resize-none focus:outline-none box-border"></textarea>
        </div>
        </div>

      <!-- Save Button -->
      <div class="flex justify-end mt-6">
        <button type="submit" class="bg-green-600 hover:bg-green-700 text-white font-semibold px-6 py-3 rounded-lg shadow-md transition-transform hover:scale-105">
          Save Changes
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Department Validation Modal -->
<div id="deptValidationModal" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center hidden z-50">
  <div class="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full text-center">
    <p class="text-red-600 font-semibold mb-4">Please select a valid department from the list.</p>
    <button id="deptValidationOk" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">OK</button>
  </div>
</div>

<!-- Transaction Saved Modal -->
<div id="transactionSavedModal" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center hidden z-50">
  <div class="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full text-center">
    <p class="text-green-600 font-semibold mb-4">Transaction saved successfully!</p>
    <button id="transactionSavedOk" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">OK</button>
  </div>
</div>

<!-- Edit Department Modal -->
<div id="editDepartmentModal"
     class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">

    <div class="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
        <!-- Header -->
        <h2 class="text-lg font-semibold mb-4">Edit Department</h2>

        <!-- Form -->
        <form id="editDepartmentForm">
            <input type="hidden" id="editDepartmentId">

            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                    Department Name
                </label>
                <input
                    type="text"
                    id="editDepartmentName"
                    class="w-full border rounded-md px-3 py-2 focus:outline-none focus:ring focus:ring-blue-300"
                    required>
            </div>

            <!-- Buttons -->
            <div class="flex justify-end gap-3">
                <button type="button"
                        onclick="closeEditDepartmentModal()"
                        class="px-4 py-2 text-sm bg-gray-200 rounded-md hover:bg-gray-300">
                    Cancel
                </button>

                <button type="submit"
                        class="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700">
                    Save
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Error Modal -->
<div id="errorModal" class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-sm p-6 text-center">
        <h2 class="text-lg font-semibold mb-4 text-red-600">Error</h2>
        <p id="errorMessage" class="mb-4 text-gray-700"></p>
        <button id="errorOkBtn" class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition">
            OK
        </button>
    </div>
</div>

<!-- Confirm Edit Modal -->
<div id="confirmEditModal" class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-sm p-6 text-center">
        <h2 class="text-lg font-semibold mb-4 text-blue-600">Confirm Change</h2>
        <p id="confirmEditMessage" class="mb-4 text-gray-700"></p>
        <div class="flex justify-center gap-3">
            <button id="confirmEditCancel" class="px-4 py-2 bg-gray-200 rounded-md hover:bg-gray-300">Cancel</button>
            <button id="confirmEditOk" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Confirm</button>
        </div>
    </div>
</div>

<!-- Delete Transaction Modal -->
<div id="deleteTransactionModal"
     class="fixed inset-0 bg-black bg-opacity-40 backdrop-blur-sm hidden flex items-center justify-center z-50">

    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6 text-center">
        <h3 class="text-lg font-semibold mb-3 text-gray-800">
            Delete Transaction
        </h3>

        <p class="text-gray-600 mb-6">
            Are you sure you want to delete this transaction?<br>
            <span class="text-red-600 font-medium">This action cannot be undone.</span>
        </p>

        <div class="flex justify-center gap-4">
            <button id="cancelDeleteTransaction"
                    class="px-4 py-2 bg-gray-200 rounded-lg hover:bg-gray-300 transition">
                Cancel
            </button>

            <button id="confirmDeleteTransaction"
                    class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                Delete
            </button>
        </div>
    </div>
</div>

<!-- Normal Delete Department Modal -->
<div id="deptDeleteConfirmModal" class="fixed inset-0 bg-black/40 hidden flex items-center justify-center z-50">
  <div class="bg-white rounded-xl shadow-lg w-full max-w-sm p-6">
    <h2 class="text-lg font-semibold mb-3">Delete Department?</h2>
    <p class="text-sm text-gray-600 mb-6">This action cannot be undone.</p>
    <div class="flex justify-end gap-3">
      <button id="deptCancelDeleteBtn" class="px-4 py-2 rounded-md border hover:bg-gray-100">Cancel</button>
      <button id="deptConfirmDeleteBtn" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">Delete</button>
    </div>
  </div>
</div>

<!-- Department in use, reassign -->
<div id="deptReassignModal" class="fixed inset-0 bg-black/40 hidden flex items-center justify-center z-50">
  <div class="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6">
    <h2 class="text-lg font-semibold mb-2">Department In Use</h2>
    <p class="text-sm text-gray-600 mb-4">This department is used in transactions. Please reassign them first.</p>

    <!-- Searchable department dropdown -->
    <div class="relative mb-6">
      <input
        type="text"
        id="deptReassignInput"
        placeholder="Search department..."
        autocomplete="off"
        class="w-full border border-gray-300 rounded-xl p-3 focus:outline-none focus:ring-2 focus:ring-blue-500"
      >
      <div
        id="deptReassignDropdown"
        class="absolute mt-1 w-full bg-white border border-gray-200 rounded-xl shadow-lg max-h-48 overflow-y-auto hidden z-50"
      ></div>
      <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center text-gray-400">
        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
        </svg>
      </div>
    </div>

    <div class="flex justify-end gap-3">
      <button id="deptCancelReassignBtn" class="px-4 py-2 rounded-md border hover:bg-gray-100">Cancel</button>
      <button id="deptConfirmReassignBtn" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700">Reassign & Delete</button>
    </div>
  </div>
</div>

<!-- Success Modals -->
<div id="deptDeleteSuccessModal" class="fixed inset-0 bg-black/40 hidden flex items-center justify-center z-50">
  <div class="bg-white rounded-xl shadow-lg w-full max-w-sm p-6 text-center">
    <h2 class="text-lg font-semibold mb-3">Success</h2>
    <p id="deptDeleteSuccessMsg" class="text-sm text-gray-600 mb-6"></p>
    <button id="deptDeleteSuccessOkBtn" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">OK</button>
  </div>
</div>

<!-- View Attachment Modal -->
<div id="viewAttachmentModal" class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-6xl p-6 overflow-hidden min-h-[90vh] max-h-[90vh] flex flex-col">
        <h2 class="text-3xl font-semibold text-center mb-4">Transaction Attachments</h2>
        <!-- Hidden transaction ID -->
<input type="hidden" id="currentTransactionId" value="">
        <!-- Invoices Table -->
<div class="relative mb-2">
    <!-- Centered Heading -->
    <h3 class="font-bold text-2xl mt-2 text-center w-full">Invoices</h3>

    <!-- Right-aligned Upload Button -->
    <button
        id="uploadInvoiceBtn"
        class="absolute top-0 right-0 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
    >
        Upload
    </button>
</div>
<div class="border rounded-lg overflow-hidden">
    <table class="w-full border-collapse">
        <colgroup>
            <col class="w-3/4">
            <col class="w-1/4">
        </colgroup>
        <thead class="bg-gray-100 sticky top-0 z-10">
            <tr>
                <th class="px-4 py-2 text-center border">Filename</th>
                <th class="px-4 py-2 text-center border">Action</th>
            </tr>
        </thead>
    </table>
    <div class="overflow-y-auto min-h-60 max-h-60">
        <table class="w-full table-fixed border-collapse">
            <colgroup>
                <col class="w-3/4">
                <col class="w-1/4">
            </colgroup>
            <tbody id="invoiceTableBody">
                <!-- Rows inserted here -->
            </tbody>
        </table>
    </div>
</div>

        <!-- Warranty Table -->
<div class="relative mt-4 mb-2">
    <!-- Centered Heading -->
    <h3 class="font-bold text-2xl mt-2 text-center w-full">Warranty</h3>

    <!-- Right-aligned Upload Button -->
    <button
        id="uploadWarrantyBtn"
        class="absolute top-0 right-0 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
    >
        Upload
    </button>
</div>
<div class="border rounded-lg overflow-hidden">
    <!-- Header table -->
    <table class="w-full table-fixed border-collapse">
        <colgroup>
            <col class="w-3/4">
            <col class="w-1/4">
        </colgroup>
        <thead class="bg-gray-100 sticky top-0 z-10">
            <tr>
                <th class="px-4 py-2 text-center border">Filename</th>
                <th class="px-4 py-2 text-center border">Action</th>
            </tr>
        </thead>
    </table>
    <!-- Scrollable tbody -->
    <div class="overflow-y-auto min-h-60 max-h-60">
        <table class="w-full table-fixed border-collapse">
            <colgroup>
                <col class="w-3/4">
                <col class="w-1/4">
            </colgroup>
            <tbody id="warrantyTableBody">
                <!-- Rows inserted here -->
            </tbody>
        </table>
    </div>
</div>

<button id="closeViewModalBtn" class="w-32 px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 mx-auto mt-8">
    Close
</button>
    </div>
</div>

<!-- Edit File Name Modal -->
<div id="editFileModal" class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl w-96 p-6 flex flex-col">
        <h2 class="text-2xl font-semibold text-center mb-4">Edit File Name</h2>
        <input id="editFileNameInput" type="text" class="border rounded px-3 py-2 w-full mb-4" placeholder="Enter new file name">
        <div class="flex justify-end gap-2">
            <button id="cancelEditFileBtn" class="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400">Cancel</button>
            <button id="submitEditFileBtn" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Submit</button>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div id="editFileSuccessModal" class="fixed inset-0 bg-black bg-opacity-40 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl w-80 p-6 flex flex-col items-center">
        <h2 class="text-2xl font-semibold mb-4 text-center">File Name Updated Successfully!</h2>
        <button id="editFileSuccessOkBtn" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600">OK</button>
    </div>
</div>

<!-- Delete Confirm Modal -->
<div id="deleteFileConfirmModal" class="fixed inset-0 bg-black/40 hidden flex items-center justify-center z-50">
  <div class="bg-white rounded-2xl shadow-xl w-full max-w-md p-6 animate-fade-in">
    <h2 class="text-xl font-semibold text-gray-800 mb-3 text-center">
      Confirm Delete
    </h2>

    <p class="text-gray-600 text-center mb-6">
      Are you sure you want to delete this document?
    </p>

    <div class="flex justify-center gap-4">
      <button id="cancelDeleteFileBtn"
        class="px-4 py-2 rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-100">
        Cancel
      </button>

      <button id="confirmDeleteFileBtn"
        class="px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-700">
        Yes, Delete
      </button>
    </div>
  </div>
</div>

<!-- Delete Success Modal -->
<div id="deleteFileSuccessModal" class="fixed inset-0 bg-black/40 hidden flex items-center justify-center z-50">
  <div class="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 text-center">
    <svg class="w-14 h-14 text-green-500 mx-auto mb-3" fill="none" stroke="currentColor" stroke-width="2"
         viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round"
            d="M5 13l4 4L19 7"/>
    </svg>

    <h2 class="text-lg font-semibold text-gray-800 mb-2">
      Deleted Successfully
    </h2>

    <p class="text-gray-600 mb-4">
      The document has been removed.
    </p>

    <button id="closeDeleteSuccessBtn"
      class="px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700">
      OK
    </button>
  </div>
</div>

<!-- Modal Background -->
<div
    id="uploadInvoiceModal"
    class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center hidden z-50"
>
    <!-- Modal Container -->
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6 relative animate-fadeIn">
        <!-- Close Button -->
        <button
            id="closeUploadModal"
            class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl font-bold"
            aria-label="Close modal"
        >
            &times;
        </button>

        <!-- Modal Header -->
        <h2 class="text-2xl font-semibold mb-6 text-center text-gray-800">Upload Invoice</h2>

        <!-- Form -->
        <form id="uploadInvoiceForm" class="flex flex-col gap-4">
            <!-- File Name Input -->
            <div class="flex flex-col">
                <label class="text-gray-700 font-medium mb-1" for="invoiceFileName">File Name</label>
                <input
                    type="text"
                    id="invoiceFileName"
                    class="border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
                    placeholder="Enter file name"
                    required
                />
            </div>

            <!-- File Input -->
            <div class="flex flex-col">
                <label class="text-gray-700 font-medium mb-1" for="invoiceFileInput">Select File</label>
                <input
                    type="file"
                    id="invoiceFileInput"
                    class="file:border file:border-gray-300 file:px-4 file:py-2 file:rounded-lg file:bg-gray-50 file:text-gray-700 hover:file:bg-gray-100"
                    accept=".pdf,image/*"
                    required
                />
                <p class="text-sm text-gray-500 mt-1">Allowed: PDF, JPG, PNG</p>
            </div>

            <!-- Submit Button -->
            <button
                type="submit"
                class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 rounded-lg transition duration-200"
            >
                Upload
            </button>
        </form>
    </div>
</div>

<!-- Success Modal -->
<div
    id="uploadSuccessModal"
    class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50"
>
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm p-6 relative animate-fadeIn">
        <!-- Close Button -->
        <button
            id="closeSuccessModal"
            class="absolute top-3 right-3 text-gray-400 hover:text-gray-600 text-xl font-bold"
            aria-label="Close modal"
        >
            &times;
        </button>

        <!-- Success Icon -->
        <div class="flex justify-center mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
        </div>

        <!-- Success Message -->
        <h2 class="text-xl font-semibold text-center text-gray-800 mb-2">Upload Successful!</h2>
        <p class="text-center text-gray-600 mb-4">Your invoice has been uploaded successfully.</p>

        <!-- Close Button -->
        <div class="flex justify-center">
            <button
                id="okSuccessModal"
                class="bg-green-500 hover:bg-green-600 text-white px-6 py-2 rounded-lg font-semibold transition duration-200"
            >
                OK
            </button>
        </div>
    </div>
</div>

<div
    id="uploadWarrantyModal"
    class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center hidden z-50"
>
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md p-6 relative animate-fadeIn">
        <button
            id="closeWarrantyModal"
            class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl font-bold"
            aria-label="Close modal"
        >
            &times;
        </button>

        <h2 class="text-2xl font-semibold mb-6 text-center text-gray-800">Upload Warranty</h2>

        <form id="uploadWarrantyForm" class="flex flex-col gap-4">
            <div>
                <label class="text-gray-700 font-medium mb-1" for="warrantyFileName">File Name</label>
                <input
                    type="text"
                    id="warrantyFileName"
                    class="border border-gray-300 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
                    placeholder="Enter file name"
                    required
                />
            </div>

            <div>
                <label class="text-gray-700 font-medium mb-1" for="warrantyFileInput">Select File</label>
                <input
                    type="file"
                    id="warrantyFileInput"
                    class="file:border file:border-gray-300 file:px-4 file:py-2 file:rounded-lg file:bg-gray-50 file:text-gray-700 hover:file:bg-gray-100"
                    accept=".pdf,image/*"
                    required
                />
                <p class="text-sm text-gray-500 mt-1">Allowed: PDF, JPG, PNG</p>
            </div>

            <button
                type="submit"
                class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 rounded-lg transition duration-200"
            >
                Upload
            </button>
        </form>
    </div>
</div>

<!-- Petty Cash Modal -->
<div id="pettyCashModal"
     class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">

    <div style="background:#fff;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.25);width:100%;max-width:56rem;padding:24px;display:flex;flex-direction:column;max-height:92vh;box-sizing:border-box;">

        <!-- Header -->
        <div class="flex justify-between items-center mb-4" style="flex-shrink:0">
            <h2 class="text-2xl font-bold text-gray-800">Petty Cash</h2>
            <button id="closePettyCashModal" class="text-gray-500 hover:text-gray-700">✖</button>
        </div>

        <!-- Year Dropdown -->
        <div class="mb-4" style="flex-shrink:0">
            <label class="block text-gray-700 mb-1">Select Year</label>
            <select id="pettyCashYear"
                class="border rounded-lg px-4 py-2 w-full focus:ring-2 focus:ring-blue-400">
            </select>
        </div>

        <!-- Table: header always visible -->
        <div style="flex-shrink:0;background:#f3f4f6;border-radius:8px 8px 0 0;border:1px solid #e5e7eb;border-bottom:none;">
            <table style="width:100%;table-layout:fixed;border-collapse:collapse;">
                <thead>
                    <tr style="text-transform:uppercase;font-size:12px;font-weight:600;color:#374151;">
                        <th style="padding:10px 24px;text-align:left;width:50%">Month</th>
                        <th style="padding:10px 24px;text-align:right;width:50%">Monthly Expenses (RM)</th>
                    </tr>
                </thead>
            </table>
        </div>

        <!-- Month rows — scrollable, takes remaining space -->
        <div style="flex:1;overflow-y:auto;min-height:0;border:1px solid #e5e7eb;border-top:none;border-bottom:none;">
            <table style="width:100%;table-layout:fixed;border-collapse:collapse;">
                <tbody id="pettyCashMonthBody" style="display:table-row-group;">
                </tbody>
            </table>
        </div>

        <!-- Summary rows — always fully visible, never hidden -->
        <div style="flex-shrink:0;border:1px solid #e5e7eb;border-top:2px solid #d1d5db;border-radius:0 0 8px 8px;">
            <table style="width:100%;table-layout:fixed;border-collapse:collapse;">
                <tbody id="pettyCashSummaryBody" style="display:table-row-group;">
                </tbody>
            </table>
        </div>

        <!-- Footer -->
        <div class="flex justify-end mt-4" style="flex-shrink:0">
            <button id="closePettyCashModalBtn"
                class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                Close
            </button>
        </div>

    </div>
</div>


<script>
// ════════════════════════════════════════════════════════════
//  DYNAMIC TABLE BODY HEIGHT
// ════════════════════════════════════════════════════════════
function resizeTableBody() {
    var wrap = document.querySelector('.tx-table-wrap');
    var thead = document.querySelector('.tx-table thead');
    var tbody = document.getElementById('transactionTableBody');
    if (!wrap || !thead || !tbody) return;
    var available = wrap.getBoundingClientRect().height - thead.getBoundingClientRect().height;
    tbody.style.height = Math.max(available, 200) + 'px';
}
window.addEventListener('resize', resizeTableBody);

// ════════════════════════════════════════════════════════════
//  TOAST
// ════════════════════════════════════════════════════════════
function showToast(msg, type = 'success') {
    const icons = { success: '✓', error: '✕', info: 'i' };
    const el = document.createElement('div');
    el.className = `toast ${type}`;
    el.innerHTML = `<span style="font-weight:700;font-size:15px">${icons[type] || 'i'}</span> ${msg}`;
    document.getElementById('toast-container').appendChild(el);
    setTimeout(() => { el.classList.add('hiding'); setTimeout(() => el.remove(), 320); }, 3200);
}

// ════════════════════════════════════════════════════════════
//  CONFIRM MODAL
// ════════════════════════════════════════════════════════════
function showConfirm(title, msg, cb) {
    document.getElementById('confirmTitle').textContent = title;
    document.getElementById('confirmMessage').textContent = msg;
    document.getElementById('confirmModal').classList.remove('hidden');
    const ok = document.getElementById('confirmOk');
    const newOk = ok.cloneNode(true);
    ok.replaceWith(newOk);
    newOk.addEventListener('click', () => {
        document.getElementById('confirmModal').classList.add('hidden');
        cb();
    });
}
document.getElementById('confirmCancel').addEventListener('click', () =>
    document.getElementById('confirmModal').classList.add('hidden'));

// ════════════════════════════════════════════════════════════
//  TABLE STATE
// ════════════════════════════════════════════════════════════
let currentPage = 1;
let currentSort = 'inv_date';
let currentDir  = 'desc';
let debounceTimer;

function getFilters() {
    return {
        item:       document.getElementById('searchItem').value.trim(),
        department: document.getElementById('searchDept').value.trim(),
        vendor:     document.getElementById('searchVendor').value.trim(),
        date_from:  document.getElementById('dateFrom').value,
        date_to:    document.getElementById('dateTo').value,
    };
}

function loadTransactions(page) {
    page = page || 1;
    currentPage = page;
    const f = getFilters();
    updateChips(f);

    const params = new URLSearchParams(Object.assign({}, f, {
        page: page,
        sort: currentSort,
        dir:  currentDir
    }));

    showShimmer();

    fetch('search_transactions.php?' + params.toString())
        .then(function(r) { return r.json(); })
        .then(function(data) { renderTable(data); })
        .catch(function() { showToast('Failed to load transactions.', 'error'); });
}

// Override original refreshTransactionTable to use our paginated loader
function refreshTransactionTable() {
    loadTransactions(currentPage);
}

function showShimmer() {
    var tbody = document.getElementById('transactionTableBody');
    var row = '<tr>' +
        '<td class="col-date"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-item"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-dept"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-vendor"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-unit"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-price"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-terms"><div class="shimmer-cell"><div></div></div></td>' +
        '<td class="col-action"></td>' +
        '</tr>';
    tbody.innerHTML = Array(8).fill(row).join('');
}

// Format price: show 3 decimal places only if the 3rd digit is non-zero
function fmtPrice(val) {
    const n = parseFloat(val || 0);
    const s = n.toFixed(3);
    // If third decimal is 0, show 2 places; otherwise show 3
    return s.endsWith('0') ? n.toFixed(2) : s;
}

function esc(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;').replace(/</g, '&lt;')
        .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function renderTable(data) {
    var tbody = document.getElementById('transactionTableBody');

    if (!data.rows || data.rows.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;padding:40px;color:#9ca3af;font-size:14px">No records found.</td></tr>';
        document.getElementById('recordCount').textContent = '';
        document.getElementById('pagination').innerHTML = '';
        return;
    }

    tbody.innerHTML = data.rows.map(function(row) {
        return '<tr>' +
            '<td class="col-date  text-center" style="font-size:15px">' + esc(row.inv_date) + '</td>' +
            '<td class="col-item"  title="' + esc(row.item) + '" style="font-size:15px">' + esc(row.item) + '</td>' +
            '<td class="col-dept"  title="' + esc(row.department) + '" style="font-size:15px">' + esc(row.department) + '</td>' +
            '<td class="col-vendor" title="' + esc(row.vendor) + '" style="font-size:15px">' + esc(row.vendor) + '</td>' +
            '<td class="col-unit  text-center" style="font-size:15px">' + parseInt(row.unit || 0, 10).toLocaleString() + '</td>' +
            '<td class="col-price text-right font-medium" style="font-size:15px">' + fmtPrice(row.price) + '</td>' +
            '<td class="col-terms text-center" style="font-size:15px">' + esc(row.terms) + '</td>' +
            '<td class="col-action text-center">' +
                '<div style="display:flex;align-items:center;justify-content:center;gap:6px">' +
                    '<a href="transaction_form.php?action=edit&id=' + row.id + '" title="Edit" style="color:#3b82f6;display:inline-flex;">' +
                        '<svg xmlns="http://www.w3.org/2000/svg" style="width:16px;height:16px" fill="none" viewBox="0 0 24 24" stroke="currentColor">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2v-5M16.5 3.5l4 4L12 16H8v-4l8.5-8.5z"/></svg>' +
                    '</a>' +
                    '<button class="view-transaction-btn" data-id="' + row.id + '" title="View" style="color:#22c55e">' +
                        '<svg xmlns="http://www.w3.org/2000/svg" style="width:16px;height:16px" fill="none" viewBox="0 0 24 24" stroke="currentColor">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>' +
                    '</button>' +
                    '<button class="delete-transaction-btn" data-id="' + row.id + '" title="Delete" style="color:#ef4444">' +
                        '<svg xmlns="http://www.w3.org/2000/svg" style="width:16px;height:16px" fill="none" viewBox="0 0 24 24" stroke="currentColor">' +
                        '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>' +
                    '</button>' +
                '</div>' +
            '</td>' +
        '</tr>';
    }).join('');

    // Record count
    var start = (data.page - 1) * data.per_page + 1;
    var end   = Math.min(data.page * data.per_page, data.total);
    document.getElementById('recordCount').textContent =
        'Showing ' + start + '–' + end + ' of ' + data.total.toLocaleString() + ' records';

    renderPagination(data.page, data.total_pages);
    // Recalculate scrollable height after render
    setTimeout(resizeTableBody, 0);
}

function renderPagination(page, totalPages) {
    var container = document.getElementById('pagination');
    if (totalPages <= 1) { container.innerHTML = ''; return; }

    var html = '<button class="page-btn" onclick="loadTransactions(' + (page-1) + ')"' + (page<=1?' disabled':'') + '>← Prev</button>';

    var range = [];
    for (var i = Math.max(1, page-2); i <= Math.min(totalPages, page+2); i++) range.push(i);

    if (range[0] > 1) {
        html += '<button class="page-btn" onclick="loadTransactions(1)">1</button>';
        if (range[0] > 2) html += '<span style="padding:0 4px;color:#9ca3af">…</span>';
    }
    range.forEach(function(i) {
        html += '<button class="page-btn' + (i===page?' active':'') + '" onclick="loadTransactions(' + i + ')">' + i + '</button>';
    });
    if (range[range.length-1] < totalPages) {
        if (range[range.length-1] < totalPages-1) html += '<span style="padding:0 4px;color:#9ca3af">…</span>';
        html += '<button class="page-btn" onclick="loadTransactions(' + totalPages + ')">' + totalPages + '</button>';
    }
    html += '<button class="page-btn" onclick="loadTransactions(' + (page+1) + ')"' + (page>=totalPages?' disabled':'') + '>Next →</button>';
    container.innerHTML = html;
}

// ════════════════════════════════════════════════════════════
//  FILTER CHIPS
// ════════════════════════════════════════════════════════════
function updateChips(f) {
    var labels = { item:'Item', department:'Dept', vendor:'Vendor', date_from:'From', date_to:'To' };
    var chips = document.getElementById('filterChips');
    var active = Object.entries(f).filter(function(e) { return e[1] !== ''; });
    chips.innerHTML = active.map(function(e) {
        return '<span class="chip">' + labels[e[0]] + ': <strong>' + esc(e[1]) + '</strong>' +
               '<button onclick="clearFilter(\'' + e[0] + '\')" title="Clear">×</button></span>';
    }).join('');
    chips.classList.toggle('hidden', active.length === 0);
}

function clearFilter(key) {
    var map = { item:'searchItem', department:'searchDept', vendor:'searchVendor', date_from:'dateFrom', date_to:'dateTo' };
    var el = document.getElementById(map[key]);
    if (el) { el.value = ''; loadTransactions(1); }
}

// ════════════════════════════════════════════════════════════
//  SEARCH DEBOUNCE
// ════════════════════════════════════════════════════════════
['searchItem','searchDept','searchVendor','dateFrom','dateTo'].forEach(function(id) {
    document.getElementById(id).addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() { loadTransactions(1); }, 350);
    });
});

// ════════════════════════════════════════════════════════════
//  COLUMN SORT
// ════════════════════════════════════════════════════════════
document.querySelectorAll('th[data-sort]').forEach(function(th) {
    th.addEventListener('click', function() {
        var col = th.dataset.sort;
        if (currentSort === col) {
            currentDir = currentDir === 'asc' ? 'desc' : 'asc';
        } else {
            currentSort = col; currentDir = 'desc';
        }
        document.querySelectorAll('.sort-icon').forEach(function(s) { s.textContent = '↕'; });
        th.querySelector('.sort-icon').textContent = currentDir === 'asc' ? '↑' : '↓';
        loadTransactions(1);
    });
});

// ════════════════════════════════════════════════════════════
//  DELETE + VIEW (delegated)
// ════════════════════════════════════════════════════════════
document.getElementById('transactionTableBody').addEventListener('click', function(e) {
    // DELETE
    var del = e.target.closest('.delete-transaction-btn');
    if (del) {
        var delId = del.dataset.id;
        document.getElementById('deleteTransactionModal').classList.remove('hidden');
        document.getElementById('confirmDeleteTransaction').onclick = function() {
            document.getElementById('deleteTransactionModal').classList.add('hidden');
            fetch('delete_transaction.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'id=' + delId
            })
            .then(function(r) { return r.json(); })
            .then(function(d) {
                if (d.success) { showToast('Transaction deleted.'); loadTransactions(currentPage); }
                else showToast('Delete failed: ' + (d.error || 'Unknown error'), 'error');
            })
            .catch(function() { showToast('Delete failed.', 'error'); });
        };
        document.getElementById('cancelDeleteTransaction').onclick = function() {
            document.getElementById('deleteTransactionModal').classList.add('hidden');
        };
        return;
    }

    // VIEW — triggers the viewAttachmentModal via the original handler
    var view = e.target.closest('.view-transaction-btn');
    if (view) {
        var transactionId = view.dataset.id;
        document.getElementById('currentTransactionId').value = transactionId;
        if (typeof fetchAttachments === 'function') fetchAttachments(transactionId);
        document.getElementById('viewAttachmentModal').classList.remove('hidden');
        return;
    }
});

// ════════════════════════════════════════════════════════════
//  KEYBOARD SHORTCUTS
// ════════════════════════════════════════════════════════════
document.addEventListener('keydown', function(e) {
    if (e.altKey && e.key === 'n') { e.preventDefault(); window.location.href = 'transaction_form.php?action=add'; }
    if (e.key === 'Escape') { document.getElementById('confirmModal').classList.add('hidden'); }
});

// ════════════════════════════════════════════════════════════
//  DEPARTMENT MODAL OPEN/CLOSE
// ════════════════════════════════════════════════════════════
document.getElementById('openDepartmentModal').addEventListener('click', function() {
    document.getElementById('departmentModal').classList.remove('hidden');
});
document.getElementById('closeDepartmentModal').addEventListener('click', function() {
    document.getElementById('departmentModal').classList.add('hidden');
});

// ════════════════════════════════════════════════════════════
//  AFTER ADD/EDIT SUCCESS — show toast, refresh table
// ════════════════════════════════════════════════════════════
window.onTransactionSaved = function(action) {
    showToast(action === 'add' ? 'Transaction added!' : 'Transaction updated!');
    loadTransactions(currentPage);
};
window.onTransactionError = function(msg) {
    showToast(msg || 'An error occurred.', 'error');
};

// ════════════════════════════════════════════════════════════
//  INITIAL LOAD — NO date default, load all recent records
// ════════════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', function() {
    resizeTableBody();
    loadTransactions(1);

    // Logout is handled by sidebar.php's built-in modal
});
</script>
<script>

document.addEventListener('DOMContentLoaded', () => {
    const emailWrappers = document.querySelectorAll('.email-wrapper');

    // Replace with your emails from database
    const emailList = <?php 
        // Example: fetch distinct emails from DB
        $emails = [];
        $stmt = $pdo->query("SELECT DISTINCT email FROM transactions WHERE email IS NOT NULL AND email <> '' ORDER BY email ASC");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $emails[] = $row['email'];
        }
        echo json_encode($emails, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT);
    ?> || [];

    emailWrappers.forEach(wrapper => {
        const input = wrapper.querySelector('.emailInput');
        const dropdown = wrapper.querySelector('.emailDropdown');
        let filteredEmails = [];
        let activeIndex = -1;

        input.addEventListener('input', () => {
            const query = input.value.trim().toLowerCase();
            filteredEmails = emailList.filter(e => e.toLowerCase().includes(query));
            renderDropdown();
        });

        function renderDropdown() {
            dropdown.innerHTML = '';
            activeIndex = -1;

            if (!filteredEmails.length) {
                dropdown.classList.add('hidden');
                return;
            }

            filteredEmails.forEach((email, index) => {
                const div = document.createElement('div');
                div.textContent = email;
                div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';
                div.addEventListener('mousedown', e => {
                    e.preventDefault();
                    input.value = email;
                    dropdown.classList.add('hidden');
                });
                dropdown.appendChild(div);
            });

            dropdown.classList.remove('hidden');
        }

input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});

        function highlightActive(items) {
            Array.from(items).forEach((item, index) => {
                item.classList.toggle('bg-blue-100', index === activeIndex);
                if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
            });
        }

        document.addEventListener('click', e => {
            if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });

        input.addEventListener('blur', () => {
            setTimeout(() => dropdown.classList.add('hidden'), 100);
        });
    });
});


document.addEventListener('DOMContentLoaded', () => {
    const wrappers = document.querySelectorAll('.contact-wrapper');
    const contactList = <?php echo json_encode($contacts); ?> || [];

    wrappers.forEach(wrapper => {
        const input = wrapper.querySelector('.contactInput');
        const dropdown = wrapper.querySelector('.contactDropdown');
        let filteredContacts = [];
        let activeIndex = -1;

        input.addEventListener('input', () => {
            const query = input.value.trim().toLowerCase();
            filteredContacts = contactList.filter(c => c.toLowerCase().includes(query));
            renderDropdown();
        });

        function renderDropdown() {
            dropdown.innerHTML = '';
            activeIndex = -1;

            if (!filteredContacts.length) {
                dropdown.classList.add('hidden');
                return;
            }

            filteredContacts.forEach((contact, index) => {
                const div = document.createElement('div');
                div.textContent = contact;
                div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';
                div.addEventListener('mousedown', e => {
                    e.preventDefault();
                    input.value = contact;
                    dropdown.classList.add('hidden');
                });
                dropdown.appendChild(div);
            });

            dropdown.classList.remove('hidden');
        }

input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});

        function highlightActive(items) {
            Array.from(items).forEach((item, index) => {
                item.classList.toggle('bg-blue-100', index === activeIndex);
                if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
            });
        }

        document.addEventListener('click', e => {
            if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });

        input.addEventListener('blur', () => {
            setTimeout(() => dropdown.classList.add('hidden'), 100);
        });
    });
});

const pettyCashModal = document.getElementById('pettyCashModal');
const openPettyCashModalBtn = document.getElementById('openPettyCashModal');
const closePettyCashModal = document.getElementById('closePettyCashModal');
const closePettyCashModalBtn = document.getElementById('closePettyCashModalBtn');
const pettyCashYearSelect = document.getElementById('pettyCashYear');
const pettyCashMonthBodyEl = document.getElementById('pettyCashMonthBody');
const pettyCashTableBody = pettyCashMonthBodyEl; // alias for any legacy references

// Open modal
openPettyCashModalBtn.addEventListener('click', async () => {
    pettyCashModal.classList.remove('hidden');

    // Load years from DB
    const res = await fetch('get_petty_cash_years.php');
    const years = await res.json();

    pettyCashYearSelect.innerHTML = '';
    years.forEach(y => {
        const option = document.createElement('option');
        option.value = y.year;
        option.textContent = y.year;
        pettyCashYearSelect.appendChild(option);
    });

    // Load table for the first year
    if(years.length > 0){
        loadPettyCashTable(years[0].year);
    }
});

// Close modal
closePettyCashModal.addEventListener('click', () => pettyCashModal.classList.add('hidden'));
closePettyCashModalBtn.addEventListener('click', () => pettyCashModal.classList.add('hidden'));

// Change year
pettyCashYearSelect.addEventListener('change', () => {
    loadPettyCashTable(pettyCashYearSelect.value);
});

// Load table data
async function loadPettyCashTable(year) {
    const res = await fetch(`get_petty_cash_data.php?year=${year}`);
    const data = await res.json();

    pettyCashMonthBody.innerHTML = '';
    pettyCashSummaryBody.innerHTML = '';

    const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

    // MONTH ROWS — proper table rows, no flex
    const rowStyle = 'border-bottom:1px solid #f3f4f6;';
    const tdL = 'padding:10px 24px;text-align:left;width:50%;font-size:14px;color:#374151;';
    const tdR = 'padding:10px 24px;text-align:right;width:50%;font-size:14px;color:#374151;';
    monthNames.forEach((m, idx) => {
        const month = idx + 1;
        const val = data.monthly && data.monthly[month] ? Number(data.monthly[month]).toFixed(2) : '0.00';
        pettyCashMonthBody.innerHTML += `
            <tr style="${rowStyle}">
                <td style="${tdL}">${m}</td>
                <td style="${tdR}">${val}</td>
            </tr>
        `;
    });

    // SUMMARY ROWS — always fully visible beneath the scroll area
    const sumRows = [
        { label: 'Total Expenses',                            val: Number(data.total_year).toFixed(2),   bg: '#f9fafb' },
        { label: 'Average Monthly Expenses',                  val: Number(data.avg_year).toFixed(2),     bg: '#ffffff' },
        { label: 'Total Expenses — Previous 6 Months',        val: Number(data.total_6month).toFixed(2), bg: '#f9fafb' },
        { label: 'Avg Monthly Expenses — Previous 6 Months',  val: Number(data.avg_6month).toFixed(2),   bg: '#ffffff' },
    ];
    pettyCashSummaryBody.innerHTML = sumRows.map(r => `
        <tr style="background:${r.bg};border-bottom:1px solid #e5e7eb;">
            <td style="padding:11px 24px;font-weight:600;font-size:13px;color:#111827;width:50%">${r.label}</td>
            <td style="padding:11px 24px;text-align:right;font-weight:700;font-size:14px;color:#111827;width:50%">${r.val}</td>
        </tr>
    `).join('');
}


document.getElementById('transactionTableBody')
    .addEventListener('click', function (e) {

        const viewBtn = e.target.closest('button[title="View"]');
        if (!viewBtn) return;

        const transactionId = viewBtn.dataset.id;

        document.getElementById('currentTransactionId').value = transactionId;
        fetchAttachments(transactionId);
        viewAttachmentModal.classList.remove('hidden');
});

async function refreshTransactionTable() {
    // Delegates to the paginated loader defined above
    loadTransactions(currentPage);
}


async function refreshWarrantyTableUnique() {
    const transactionId = transactionIdInputUnique.value;
    if (!transactionId) return;

    try {
        const response = await fetch(`list_warranty.php?transactionId=${transactionId}`);
        const data = await response.json();

        if (data.success && Array.isArray(data.files)) {
            populateTable('warrantyTableBody', data.files, 'warranty');
        } else {
            console.error('Failed to fetch warranty files:', data);
        }
    } catch (err) {
        console.error('Error fetching warranty files:', err);
    }
}

// --- Unique Variables ---
const warrantyUploadBtnUnique = document.getElementById('uploadWarrantyBtn');
const warrantyModalUnique = document.getElementById('uploadWarrantyModal');
const warrantyCloseBtnUnique = document.getElementById('closeWarrantyModal');
const warrantyFormUnique = document.getElementById('uploadWarrantyForm');
const warrantyFileNameInputUnique = document.getElementById('warrantyFileName');
const warrantyFileInputUnique = document.getElementById('warrantyFileInput');
const transactionIdInputUnique1 = document.getElementById('currentTransactionId'); // outer

// --- Open Modal ---
warrantyUploadBtnUnique.addEventListener('click', () => warrantyModalUnique.classList.remove('hidden'));

// --- Close Modal ---
warrantyCloseBtnUnique.addEventListener('click', () => warrantyModalUnique.classList.add('hidden'));

// --- Click outside modal to close ---
warrantyModalUnique.addEventListener('click', (e) => {
    if (e.target === warrantyModalUnique) warrantyModalUnique.classList.add('hidden');
});

// --- Form Submit (AJAX Upload) ---
warrantyFormUnique.addEventListener('submit', async (event) => {
    event.preventDefault();

    const transactionId = transactionIdInputUnique1.value; // get value
    const fileNameUnique = warrantyFileNameInputUnique.value.trim();
    const fileUnique = warrantyFileInputUnique.files[0];

    if (!transactionId || !fileNameUnique || !fileUnique) {
        alert('Please fill all fields and select a file.');
        return;
    }

    const allowedTypesUnique = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
    if (!allowedTypesUnique.includes(fileUnique.type)) {
        alert('Only PDF or image files are allowed.');
        return;
    }

    const formDataUnique = new FormData();
    formDataUnique.append('transactionId', transactionId); // ✅ corrected
    formDataUnique.append('fileName', fileNameUnique);
    formDataUnique.append('file', fileUnique);

    try {
        const response = await fetch('upload_warranty.php', {
            method: 'POST',
            body: formDataUnique
        });
        const result = await response.json();

        if (result.success) {
            warrantyModalUnique.classList.add('hidden');
            warrantyFormUnique.reset();
            showUploadSuccessModalUnique();
            refreshWarrantyTableUnique();
        } else {
            alert('Upload failed: ' + result.message);
        }
    } catch (err) {
        console.error(err);
        alert('An error occurred while uploading the file.');
    }
});


// --- Refresh Table After Upload ---
async function refreshInvoiceTableUnique() {
    const transactionId = document.getElementById('currentTransactionId').value;
    if (!transactionId) return;

    try {
        const response = await fetch(`list_invoices.php?transactionId=${transactionId}`);
        const data = await response.json();

        if (data.success && Array.isArray(data.files)) {
            populateTable('invoiceTableBody', data.files, 'invoices');
        } else {
            console.error('Failed to fetch files:', data);
        }
    } catch (err) {
        console.error('Error fetching invoice files:', err);
    }
}

// Unique JS Variables
const uploadSuccessModalUnique = document.getElementById('uploadSuccessModal');
const closeSuccessModalUnique = document.getElementById('closeSuccessModal');
const okSuccessModalUnique = document.getElementById('okSuccessModal');

// --- Open Success Modal ---
function showUploadSuccessModalUnique() {
    uploadSuccessModalUnique.classList.remove('hidden');
}

// --- Close Success Modal ---
function closeUploadSuccessModalUnique() {
    uploadSuccessModalUnique.classList.add('hidden');
}

// --- Event Listeners ---
closeSuccessModalUnique.addEventListener('click', closeUploadSuccessModalUnique);
okSuccessModalUnique.addEventListener('click', closeUploadSuccessModalUnique);

// Close when clicking outside modal content
uploadSuccessModalUnique.addEventListener('click', (e) => {
    if (e.target === uploadSuccessModalUnique) closeUploadSuccessModalUnique();
});

// --- Unique IDs / Variables ---
const invoiceUploadButtonUnique = document.getElementById('uploadInvoiceBtn');
const invoiceUploadModalUnique = document.getElementById('uploadInvoiceModal');
const invoiceCloseModalButtonUnique = document.getElementById('closeUploadModal');
const invoiceUploadFormUnique = document.getElementById('uploadInvoiceForm');
const invoiceFileNameInputUnique = document.getElementById('invoiceFileName');
const invoiceFileInputUnique = document.getElementById('invoiceFileInput');
const transactionIdInputUnique = document.getElementById('currentTransactionId'); // hidden input
// --- Open Modal ---
function openInvoiceUploadModalUnique() {
    invoiceUploadModalUnique.classList.remove('hidden');
}

// --- Close Modal ---
function closeInvoiceUploadModalUnique() {
    invoiceUploadModalUnique.classList.add('hidden');
}

// --- Event: Upload Button Click ---
invoiceUploadButtonUnique.addEventListener('click', openInvoiceUploadModalUnique);

// --- Event: Close Button Click ---
invoiceCloseModalButtonUnique.addEventListener('click', closeInvoiceUploadModalUnique);

// --- Event: Click outside modal to close ---
invoiceUploadModalUnique.addEventListener('click', (event) => {
    if (event.target === invoiceUploadModalUnique) closeInvoiceUploadModalUnique();
});

// --- Form Submit Handler ---
invoiceUploadFormUnique.addEventListener('submit', async function (event) {
    event.preventDefault();

    const transactionIdUnique = transactionIdInputUnique.value;
    const fileNameUnique = invoiceFileNameInputUnique.value.trim();
    const fileUnique = invoiceFileInputUnique.files[0];

    if (!transactionIdUnique || !fileNameUnique || !fileUnique) {
        alert('Please fill all fields and select a file.');
        return;
    }

    // Validate file type
    const allowedTypesUnique = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
    if (!allowedTypesUnique.includes(fileUnique.type)) {
        alert('Only PDF or image files are allowed.');
        return;
    }

    // Prepare FormData
    const formDataUnique = new FormData();
    formDataUnique.append('transactionId', transactionIdUnique);
    formDataUnique.append('fileName', fileNameUnique);
    formDataUnique.append('file', fileUnique);

    try {
        const response = await fetch('upload_invoice.php', {
            method: 'POST',
            body: formDataUnique
        });

        const result = await response.json();

        if (result.success) {
            showUploadSuccessModalUnique();
            refreshInvoiceTableUnique(); // <-- refresh table dynamically
            invoiceUploadFormUnique.reset();
            invoiceUploadModalUnique.classList.add('hidden');

            // TODO: Optionally refresh the invoice table
        } else {
            alert('Upload failed: ' + result.message);
        }
    } catch (err) {
        console.error(err);
        alert('An error occurred while uploading the file.');
    }
});


document.addEventListener('click', function (e) {
    const btn = e.target.closest('button[title="ViewFile"]');
    if (!btn) return;

    const transactionId = document.getElementById('currentTransactionId').value;
    const folder = btn.dataset.folder;
    const file = btn.dataset.file;

    const timestamp = Date.now(); // cache buster

    window.open(
        `view_file.php?transactionId=${transactionId}` +
        `&folder=${folder}` +
        `&file=${encodeURIComponent(file)}` +
        `&t=${timestamp}`,
        '_blank'
    );
});

let deleteFileName = '';
let deleteFolder = '';
let deleteTransactionId = '';
let deleteRowElement = null;

const deleteConfirmModal = document.getElementById('deleteFileConfirmModal');
const deleteSuccessModal = document.getElementById('deleteFileSuccessModal');

const cancelDeleteBtn = document.getElementById('cancelDeleteFileBtn');
const confirmDeleteBtn = document.getElementById('confirmDeleteFileBtn');
const closeDeleteSuccessBtn = document.getElementById('closeDeleteSuccessBtn');

document.addEventListener('click', function(e) {
    const deleteBtn = e.target.closest('button[title="Delete"]');
    if (!deleteBtn) return;

    const tr = deleteBtn.closest('tr');
    deleteFileName = tr.querySelector('td:first-child').textContent.trim();
    deleteFolder = tr.querySelector('button[title="EditFile"]').dataset.folder;
    deleteTransactionId = document.getElementById('currentTransactionId').value
    deleteRowElement = tr;

    deleteConfirmModal.classList.remove('hidden');
});

cancelDeleteBtn.addEventListener('click', () => {
    deleteConfirmModal.classList.add('hidden');
});

confirmDeleteBtn.addEventListener('click', () => {
    fetch('delete_document.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            transactionId: deleteTransactionId,
            folder: deleteFolder,
            file: deleteFileName
        })
    })
    .then(res => res.json())
    .then(data => {
        deleteConfirmModal.classList.add('hidden');
        if (data.success) {
            deleteRowElement.remove();
            deleteSuccessModal.classList.remove('hidden');
        } else {
            alert(data.message);
        }
    });
});

closeDeleteSuccessBtn.addEventListener('click', () => {
    deleteSuccessModal.classList.add('hidden');
});


let currentFile = '';
let currentTbody = null;

// Event delegation for Edit buttons
document.addEventListener('click', function (e) {
    const btn = e.target.closest('button[title="EditFile"]');
    if (!btn) return;

    const tr = btn.closest('tr');

    currentFile = tr.querySelector('td:first-child').textContent;
    currentTbody = tr;

    // ✅ Get folder from button
    currentFolder = btn.dataset.folder;

    // ✅ Get transaction ID from hidden input
    currentTransactionId = document.getElementById('currentTransactionId').value;

    // Pre-fill input without extension
    const editInput = document.getElementById('editFileNameInput');
    const nameWithoutExt = currentFile.replace(/\.[^/.]+$/, '');
    editInput.value = nameWithoutExt;

    // Show Edit modal
    document.getElementById('editFileModal').classList.remove('hidden');
});


// Cancel button
document.getElementById('cancelEditFileBtn').addEventListener('click', () => {
    document.getElementById('editFileModal').classList.add('hidden');
});

// Submit button
document.getElementById('submitEditFileBtn').addEventListener('click', () => {
    const newName = document.getElementById('editFileNameInput').value.trim();
    if (!newName) return alert('File name cannot be empty!');

    const ext = currentFile.split('.').pop();
    const updatedFile = `${newName}.${ext}`;

    // Send rename request to PHP
    fetch('rename_file.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            transactionId: currentTransactionId, // optional, if needed to locate folder
            folder: currentFolder,
            oldName: currentFile,
            newName: updatedFile
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            // Update table cell
            currentTbody.querySelector('td:first-child').textContent = updatedFile;

            // Hide edit modal and show success
            document.getElementById('editFileModal').classList.add('hidden');
            document.getElementById('editFileSuccessModal').classList.remove('hidden');
            refreshInvoiceTableUnique(); // <-- refresh table dynamically
            refreshWarrantyTableUnique();
        } else {
            alert('Failed to rename file: ' + data.message);
        }
    });
});

// Success OK button
document.getElementById('editFileSuccessOkBtn').addEventListener('click', () => {
    document.getElementById('editFileSuccessModal').classList.add('hidden');
});


// Select modal and close button
const viewAttachmentModal = document.getElementById('viewAttachmentModal');
const closeViewModalBtn = document.getElementById('closeViewModalBtn');

// Open modal on button click
document.querySelectorAll('button[title="View"]').forEach(btn => {
    btn.addEventListener('click', () => {
        const transactionId = btn.dataset.id; // read from 'data-id'
        console.log('Transaction ID:', transactionId); // debug
                        // ✅ Save it in the hidden input
        document.getElementById('currentTransactionId').value = transactionId;

        fetchAttachments(transactionId);
        viewAttachmentModal.classList.remove('hidden');
    });
});

// Close modal
closeViewModalBtn.addEventListener('click', () => {
    viewAttachmentModal.classList.add('hidden');
});

// Fetch attachments from server
function fetchAttachments(transactionId) {
    fetch(`get_attachments.php?transactionId=${transactionId}`)
        .then(res => res.json())
        .then(data => {
            populateTable('invoiceTableBody', data.invoices, 'invoices');
            populateTable('warrantyTableBody', data.warranty, 'warranty');
        });
}

// Populate table function
function populateTable(tableId, files, folder) {
    const tbody = document.getElementById(tableId);
    tbody.innerHTML = '';

    files.forEach(file => {
        const tr = document.createElement('tr');
        tr.classList.add('table-row', 'border-b');

        tr.innerHTML = `
            <td class="px-4 py-2 text-center align-middle">${file}</td>

            <td class="px-4 py-2 whitespace-nowrap align-middle flex justify-center gap-2 items-center">
                
                <!-- Edit -->
                <button
                    class="text-yellow-500 hover:text-yellow-700"
                    title="EditFile"
                    data-folder="${folder}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-5" fill="none"
                         viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M11 5H6a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2v-5M16.5 3.5l4 4L12 16H8v-4l8.5-8.5z"/>
                    </svg>
                </button>
<!-- View -->
<button
    class="text-blue-500 hover:text-blue-700"
    title="ViewFile"
    data-folder="${folder}"
    data-file="${file}"
>
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
         viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
    </svg>
</button>

                <!-- Delete -->
                <button class="text-red-500 hover:text-red-700" title="Delete">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-5" fill="none"
                         viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </td>
        `;

        tbody.appendChild(tr);
    });
}



const deptDeleteSuccessModal = document.getElementById('deptDeleteSuccessModal');
const deptDeleteSuccessMsg = document.getElementById('deptDeleteSuccessMsg');
const deptDeleteSuccessOkBtn = document.getElementById('deptDeleteSuccessOkBtn');

deptDeleteSuccessOkBtn.onclick = () => {
    deptDeleteSuccessModal.classList.add('hidden');
};

// ====== Unique DOM Elements ======
const deptReassignInput = document.getElementById('deptReassignInput');
const deptReassignDropdown = document.getElementById('deptReassignDropdown');
const deptReassignModal = document.getElementById('deptReassignModal');
const deptDeleteModal = document.getElementById('deptDeleteConfirmModal');

// ====== State ======
let deptItems = [];
let activeIndex = -1;
let dept_deleteId = null;
let dept_deleteName = '';
let dept_deleteRow = null;

// ====== Render Dropdown List ======
function renderDeptDropdown(list) {
    deptReassignDropdown.innerHTML = '';
    activeIndex = -1;

    if (!list.length) {
        deptReassignDropdown.innerHTML = `<div class="px-4 py-3 text-sm text-gray-500">No results</div>`;
        return;
    }

    list.forEach((dept, index) => {
        const div = document.createElement('div');
        div.textContent = dept;
        div.className = 'px-4 py-3 cursor-pointer text-sm hover:bg-blue-50';

        div.addEventListener('mousedown', () => {
            deptReassignInput.value = dept;
            deptReassignDropdown.classList.add('hidden');
        });

        deptReassignDropdown.appendChild(div);
    });

    deptReassignDropdown.classList.remove('hidden');
}

// ====== Load Replacement Options ======
function loadDeptReplacementOptions(departments, currentName) {
    const filtered = Array.from(new Set(departments))
        .filter(d => d && d.trim() && d !== currentName && d.toLowerCase() !== 'undefined');
    deptItems = filtered;

    renderDeptDropdown([]); // hide initially
    deptReassignInput.value = '';
    deptReassignInput.focus();
}

// ====== Input Events ======
deptReassignInput.addEventListener('input', () => {
    const query = deptReassignInput.value.trim().toLowerCase();
    const filtered = deptItems.filter(d => d.toLowerCase().includes(query));
    renderDeptDropdown(filtered);
});

deptReassignInput.addEventListener('focus', () => {
    renderDeptDropdown(deptItems);
});

deptReassignInput.addEventListener('blur', () => {
    setTimeout(() => deptReassignDropdown.classList.add('hidden'), 150);
});

// ====== Keyboard Navigation ======
deptReassignInput.addEventListener('keydown', e => {
    const children = deptReassignDropdown.children;
    if (!children.length) return;

    if (e.key === 'ArrowDown') {
        e.preventDefault();
        activeIndex = Math.min(activeIndex + 1, children.length - 1);
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        activeIndex = Math.max(activeIndex - 1, 0);
    } else if (e.key === 'Enter') {
        e.preventDefault();
        if (activeIndex >= 0) {
            deptReassignInput.value = children[activeIndex].textContent;
            deptReassignDropdown.classList.add('hidden');
        }
    }

    [...children].forEach((el, i) => el.classList.toggle('bg-blue-100', i === activeIndex));
});

// ====== Delete Button Logic ======
document.addEventListener('click', e => {
    const btn = e.target.closest('.dept-delete-btn');
    if (!btn) return;

    dept_deleteId = btn.dataset.deptId;
    dept_deleteName = btn.dataset.deptName;
    dept_deleteRow = btn.closest('tr');

    fetch(`check_department_usage.php?id=${dept_deleteId}`)
        .then(res => res.json())
        .then(resp => {
            if (resp.in_use) {
                loadDeptReplacementOptions(resp.departments, dept_deleteName);
                deptReassignModal.classList.remove('hidden');
            } else {
                deptDeleteModal.classList.remove('hidden');
            }
        });
});

// ====== Modal Buttons ======
document.getElementById('deptCancelDeleteBtn').onclick =
document.getElementById('deptCancelReassignBtn').onclick = () => {
    deptReassignModal.classList.add('hidden');
    deptDeleteModal.classList.add('hidden');
};

document.getElementById('deptConfirmDeleteBtn').onclick = () => {
    executeDeptDelete();
};

document.getElementById('deptConfirmReassignBtn').onclick = () => {
    const newDept = deptReassignInput.value.trim();
    if (!newDept) {
        alert('Please select a department to reassign.');
        return;
    }
    executeDeptDelete(newDept);
};

// ====== Delete Function ======
function executeDeptDelete(reassignTo = null) {
    fetch('delete_department.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            id: dept_deleteId,
            reassign_to: reassignTo
        })
    })
    .then(res => res.json())
    .then(resp => {
        if (resp.success && dept_deleteRow) {
            dept_deleteRow.remove();

            // Show appropriate success message
            if (reassignTo) {
                deptDeleteSuccessMsg.textContent = `Department records reassigned to "${reassignTo}" and department successfully deleted.`;
            } else {
                deptDeleteSuccessMsg.textContent = `Department successfully deleted.`;
            }
            deptDeleteSuccessModal.classList.remove('hidden');
        } else {
            alert(resp.message || 'Delete failed');
        }

        // Close other modals
        deptReassignModal.classList.add('hidden');
        deptDeleteModal.classList.add('hidden');
    });
}

function deptCloseAllModals() {
    document.getElementById('deptDeleteConfirmModal').classList.add('hidden');
    document.getElementById('deptReassignModal').classList.add('hidden');
}

// Delete handler is handled by the new delegated listener above (shows toast + reloads page)


(function () {
    const input = document.getElementById('editDepartmentInput');
    const dropdown = document.getElementById('editDepartmentDropdown');

    let deptList = [];
    let activeIndex = -1;

    input.addEventListener('input', async () => {
        activeIndex = -1;
        const query = input.value.trim();

        if (!query) {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(`fetch_departments.php?q=${encodeURIComponent(query)}`);
            deptList = await res.json();
        } catch (err) {
            console.error('Fetch error:', err);
            deptList = [];
        }

        renderDropdown();
    });

    function renderDropdown() {
        dropdown.innerHTML = '';

        if (deptList.length === 0) {
            dropdown.classList.add('hidden');
            return;
        }

        deptList.forEach((dept, index) => {
            const div = document.createElement('div');
            div.textContent = dept;
            div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';
            if (index === activeIndex) div.classList.add('bg-blue-100');

            div.addEventListener('mousedown', (e) => {
                e.preventDefault();
                selectDepartment(dept);
            });

            dropdown.appendChild(div);
        });

        dropdown.classList.remove('hidden');
    }

    function selectDepartment(value) {
        input.value = value;
        dropdown.classList.add('hidden');
        activeIndex = -1;
        moveToNextField();
    }

    // Keyboard navigation
    input.addEventListener('keydown', (e) => {
        const items = dropdown.children;
        if (!items.length || dropdown.classList.contains('hidden')) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            activeIndex = (activeIndex + 1) % items.length;
            renderDropdown();
        } 
        else if (e.key === 'ArrowUp') {
            e.preventDefault();
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            renderDropdown();
        } 
        else if (e.key === 'Enter') {
            e.preventDefault();

            // ✅ Auto-select first item if none highlighted
            const indexToSelect = activeIndex >= 0 ? activeIndex : 0;

            if (items[indexToSelect]) {
                selectDepartment(items[indexToSelect].textContent);
            }
        } 
        else if (e.key === 'Escape') {
            dropdown.classList.add('hidden');
        }
    });

    function moveToNextField() {
        const form = input.closest('form');
        if (!form) return;

        const inputs = Array.from(form.querySelectorAll('input, select, textarea'));
        const index = inputs.indexOf(input);

        if (index > -1 && index < inputs.length - 1) {
            inputs[index + 1].focus();
        }
    }

    // Hide dropdown when clicking outside
    document.addEventListener('click', (e) => {
        if (!input.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });

input.addEventListener('blur', () => {
    setTimeout(async () => {
        const value = input.value; // exact value, spaces included

        if (value === '') {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(
                `validate_department.php?name=${encodeURIComponent(value)}`
            );
            const data = await res.json();

            if (!data.valid) {
                deptValidationModal.classList.remove('hidden');
                deptValidationOk.focus();

                deptValidationOk.onclick = () => {
                    deptValidationModal.classList.add('hidden');
                    input.focus();
                };
            } else {
                dropdown.classList.add('hidden');
            }
        } catch (err) {
            console.error('Validation error:', err);
        }
    }, 100);
});
})();


(function() {
    const input = document.getElementById('itemInputForm2');
    const dropdown = document.getElementById('itemDropdownForm2');

    let itemList = [];
    let activeIndex = -1;

    input.addEventListener('input', async () => {
        const query = input.value.trim();
        if (!query) {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(`fetch_items.php?q=${encodeURIComponent(query)}`);
            itemList = await res.json();
        } catch (err) {
            console.error('Fetch error:', err);
            itemList = [];
        }

        renderDropdown();
    });

    function renderDropdown() {
        dropdown.innerHTML = '';
        activeIndex = -1;

        if (itemList.length === 0) {
            dropdown.classList.add('hidden');
            return;
        }

        itemList.forEach((item) => {
            const div = document.createElement('div');
            div.textContent = item;
            div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';

            div.addEventListener('mousedown', (e) => {
                e.preventDefault();
                selectItem(item);
            });

            dropdown.appendChild(div);
        });

        dropdown.classList.remove('hidden');
    }

    function selectItem(value) {
        input.value = value;
        dropdown.classList.add('hidden');
    }

    // Keyboard navigation
input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});


    function highlightActive(items) {
        Array.from(items).forEach((item, index) => {
            item.classList.toggle('bg-blue-100', index === activeIndex);
            if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
        });
    }

    // Close dropdown on blur
    input.addEventListener('blur', () => {
        setTimeout(() => {
            dropdown.classList.add('hidden');
        }, 100);
    });
})();

(function() {
    const input = document.getElementById('vendorInputForm2');
    const dropdown = document.getElementById('vendorDropdownForm2');

    let vendorList = [];
    let activeIndex = -1;

    input.addEventListener('input', async () => {
        const query = input.value.trim();
        if (!query) {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(`fetch_vendors.php?q=${encodeURIComponent(query)}`);
            vendorList = await res.json();
        } catch (err) {
            console.error('Fetch error:', err);
            vendorList = [];
        }

        renderDropdown();
    });

    function renderDropdown() {
        dropdown.innerHTML = '';
        activeIndex = -1;

        if (vendorList.length === 0) {
            dropdown.classList.add('hidden');
            return;
        }

        vendorList.forEach((vendor) => {
            const div = document.createElement('div');
            div.textContent = vendor;
            div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';

            div.addEventListener('mousedown', (e) => {
                e.preventDefault();
                selectVendor(vendor);
            });

            dropdown.appendChild(div);
        });

        dropdown.classList.remove('hidden');
    }

    function selectVendor(value) {
        input.value = value;
        dropdown.classList.add('hidden');
    }

    // Keyboard navigation
input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});


    function highlightActive(items) {
        Array.from(items).forEach((item, index) => {
            item.classList.toggle('bg-blue-100', index === activeIndex);
            if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
        });
    }

    // Close dropdown on blur
    input.addEventListener('blur', () => {
        setTimeout(() => {
            dropdown.classList.add('hidden');
        }, 100);
    });

})();

const minAmountInput = document.querySelector('input[name="min_amount_for_delivery"]');

minAmountInput.addEventListener('blur', () => {
    let value = minAmountInput.value.trim();

    // Only format if it's a valid number
    if (!isNaN(value) && value !== '') {
        minAmountInput.value = parseFloat(value).toFixed(2);
    }
});

(function() {
    const input = document.getElementById('itemInputUnique');
    const dropdown = document.getElementById('itemDropdownUnique');

    let itemList = [];
    let activeIndex = -1;

    input.addEventListener('input', async () => {
        const query = input.value.trim();
        if (!query) {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(`fetch_items.php?q=${encodeURIComponent(query)}`);
            itemList = await res.json();
        } catch (err) {
            console.error('Fetch error:', err);
            itemList = [];
        }

        renderDropdown();
    });

    function renderDropdown() {
        dropdown.innerHTML = '';
        activeIndex = -1;

        if (itemList.length === 0) {
            dropdown.classList.add('hidden');
            return;
        }

        itemList.forEach((item, index) => {
            const div = document.createElement('div');
            div.textContent = item;
            div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';
            
            div.addEventListener('mousedown', (e) => {
                e.preventDefault();
                selectItem(item);
            });

            dropdown.appendChild(div);
        });

        dropdown.classList.remove('hidden');
    }

    function selectItem(value) {
        input.value = value;
        dropdown.classList.add('hidden');
    }

    // Keyboard navigation
input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});


    function highlightActive(items) {
        Array.from(items).forEach((item, index) => {
            item.classList.toggle('bg-blue-100', index === activeIndex);
            if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
        });
    }

    // Close dropdown if clicking outside
    document.addEventListener('click', e => {
        if (!input.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });

    // Close dropdown on blur
    input.addEventListener('blur', () => {
        setTimeout(() => {
            dropdown.classList.add('hidden');
        }, 100);
    });
})();

(function() {
    const input = document.getElementById('vendorInputUnique');
    const dropdown = document.getElementById('vendorDropdownUnique');

    let vendorList = [];
    let activeIndex = -1;

    input.addEventListener('input', async () => {
        const query = input.value.trim();
        if (!query) {
            dropdown.classList.add('hidden');
            return;
        }

        try {
            const res = await fetch(`fetch_vendors.php?q=${encodeURIComponent(query)}`);
            vendorList = await res.json();
        } catch (err) {
            console.error('Fetch error:', err);
            vendorList = [];
        }

        renderDropdown();
    });

    function renderDropdown() {
        dropdown.innerHTML = '';
        activeIndex = -1;

        if (vendorList.length === 0) {
            dropdown.classList.add('hidden');
            return;
        }

        vendorList.forEach((vendor, index) => {
            const div = document.createElement('div');
            div.textContent = vendor;
            div.className = 'px-4 py-2 cursor-pointer hover:bg-blue-100';
            
            div.addEventListener('mousedown', (e) => {
                // Use mousedown instead of click to select before blur
                e.preventDefault();
                selectVendor(vendor);
            });

            dropdown.appendChild(div);
        });

        dropdown.classList.remove('hidden');
    }

    function selectVendor(value) {
        input.value = value;
        dropdown.classList.add('hidden');
    }

    // Keyboard navigation
input.addEventListener('keydown', e => {
    const items = dropdown.children;

    if (e.key === 'Enter') {
        if (!items.length || dropdown.classList.contains('hidden')) {
            // No dropdown → move to next field
            e.preventDefault();
            moveToNextField(input);
        } else {
            // ✅ Select the first item if none is highlighted
            e.preventDefault();
            const itemToSelect = activeIndex >= 0 ? items[activeIndex] : items[0];
            input.value = itemToSelect.textContent;
            dropdown.classList.add('hidden');
        }
    } else if (e.key === 'ArrowDown') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex + 1) % items.length;
            highlightActive(items);
        }
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        if (items.length) {
            activeIndex = (activeIndex - 1 + items.length) % items.length;
            highlightActive(items);
        }
    }
});


    function highlightActive(items) {
        Array.from(items).forEach((item, index) => {
            item.classList.toggle('bg-blue-100', index === activeIndex);
            if (index === activeIndex) item.scrollIntoView({ block: "nearest" });
        });
    }

    // Close dropdown if clicking outside
    document.addEventListener('click', e => {
        if (!input.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });

    // Close dropdown on blur (lose focus)
    input.addEventListener('blur', () => {
        // small timeout allows mousedown selection to register
        setTimeout(() => {
            dropdown.classList.add('hidden');
        }, 100);
    });
})();



// Unique variables for Edit Transaction Modal
const editTransactionModal = document.getElementById('editTransactionModal');
const closeEditTransactionModalBtn = document.getElementById('closeEditModalBtn');
const editTransactionForm = document.getElementById('editTransactionForm');

// Close modal
closeEditTransactionModalBtn.addEventListener('click', () => {
    editTransactionModal.classList.add('hidden');
});

// Open modal and load data
document.addEventListener('click', function (e) {
    const btn = e.target.closest('.edit-transaction-btn');
    if (!btn) return;

    const transactionId = btn.dataset.id;

    fetch(`get_transaction.php?id=${transactionId}`)
        .then(res => res.json())
        .then(data => {
            // Fill form fields
Object.entries(data).forEach(([key, value]) => {
  const input = editTransactionForm.querySelector(`[name="${key}"]`);
  if (!input) return;

  if (key === 'unit' || key === 'price' || key === 'total_price') {
    const num = parseFloat(value.replace(/,/g, '')) || 0;
    input.value = num.toLocaleString('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
  } else {
    input.value = value;
  }
});

            // Ensure hidden ID
            editTransactionForm.querySelector('[name="id"]').value = data.id;

            // Show modal
            editTransactionModal.classList.remove('hidden');
        })
        .catch(err => console.error(err));
});

// AJAX submit for Edit Modal
editTransactionForm.addEventListener('submit', function (e) {
    e.preventDefault();

    // Check HTML5 validation for the form
    if (!editTransactionForm.checkValidity()) {
        editTransactionForm.reportValidity(); // Focus and show warning for the first invalid field
        return; // Stop submission
    }

    const formData = new FormData(editTransactionForm);

    fetch('update_transaction.php', {
        method: 'POST',
        body: formData
    })
    .then(res => res.text())
    .then(resp => {
        // Show success modal
        transactionSavedModal.classList.remove('hidden');
        transactionSavedOk.focus();

        // OK button handler
        transactionSavedOk.onclick = () => {
            transactionSavedModal.classList.add('hidden');

            // Close edit modal
            editTransactionModal.classList.add('hidden');

            // Refresh table
            if (typeof refreshTransactionTable === 'function') {
                refreshTransactionTable();
            }
        };
    })
    .catch(err => {
        console.error('Update failed:', err);
    });
});

document.getElementById('departmentTbody').addEventListener('click', function(e) {
    const btn = e.target.closest('.edit-btn');
    if (!btn) return;

    const id = btn.dataset.deptId;
    const name = btn.dataset.deptName;

    editDepartment(id, name); // Now both id and name are always available
});

function editDepartment(deptId, deptName) {
    const nameInput = document.getElementById('editDepartmentName');
    document.getElementById('editDepartmentId').value = deptId;

    nameInput.value = deptName;
    nameInput.setAttribute('data-original', deptName);

    document.getElementById('editDepartmentModal').classList.remove('hidden');
}

function closeEditDepartmentModal() {
    document.getElementById('editDepartmentModal').classList.add('hidden');
}

const editForm = document.getElementById('editDepartmentForm');

editForm.addEventListener('submit', function (e) {
    e.preventDefault();

    const id = document.getElementById('editDepartmentId').value;
    const name = document.getElementById('editDepartmentName').value.trim();
    const originalName = document.getElementById('editDepartmentName').getAttribute('data-original');

    // Show confirm modal
    const confirmModal = document.getElementById('confirmEditModal');
    const confirmMessage = document.getElementById('confirmEditMessage');
    const confirmOk = document.getElementById('confirmEditOk');
    const confirmCancel = document.getElementById('confirmEditCancel');

    confirmMessage.textContent = `Are you sure you want to change the department from "${originalName}" to "${name}"?`;
    confirmModal.classList.remove('hidden');

    confirmCancel.onclick = function() {
        confirmModal.classList.add('hidden');
    };

    confirmOk.onclick = function() {
        confirmModal.classList.add('hidden');

        fetch('update_department.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&department=${encodeURIComponent(name)}`
        })
        .then(res => res.text())
        .then(response => {
            if (response.trim() === 'duplicate') {
                showErrorModal('This department already exists!');
                return;
            }

            if (response.trim() === 'success') {
                closeEditDepartmentModal();
                const searchValue = document.getElementById('departmentSearch').value || '';
                refreshDepartmentTable(searchValue);
            } else {
                showErrorModal(response); // display other errors
            }
        });
    };
});

// Old filterTransactions removed — replaced by loadTransactions() above

// Unique variable for this modal form
const addTransactionModalForm = document.getElementById('transactionForm');
const transactionSavedModal = document.getElementById('transactionSavedModal');
const transactionSavedOk = document.getElementById('transactionSavedOk');

addTransactionModalForm.addEventListener('submit', function(e) {
    e.preventDefault();

    const addTransactionFormData = new FormData(addTransactionModalForm);

    fetch('add_transaction.php', {
        method: 'POST',
        body: addTransactionFormData
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            // Reset form
            addTransactionModalForm.reset();

            // Hide Add Transaction modal
            const addTransactionModal = document.getElementById('addTransactionModal');

            // Show success modal
            transactionSavedModal.classList.remove('hidden');
            transactionSavedOk.focus();

            // Handle OK button click
            transactionSavedOk.onclick = () => {
                addTransactionModal.classList.add('hidden');
                transactionSavedModal.classList.add('hidden');
                showToast('Transaction added successfully!');
                loadTransactions(currentPage);
            };
        }
    })
    .catch(error => console.error('Error:', error));
});

const deptAutoList = <?php echo json_encode($departmentsAutocomplete); ?>;

const deptAutoInput = document.getElementById('departmentInput');
const deptAutoDropdown = document.getElementById('departmentDropdown');

let highlightedIndex = -1; // Track current highlighted item

function renderDropdown(filtered) {
    deptAutoDropdown.innerHTML = '';
    if (filtered.length === 0) {
        deptAutoDropdown.classList.add('hidden');
        return;
    }

    filtered.forEach((d, index) => {
        const div = document.createElement('div');
        div.textContent = d;
        div.className = 'px-3 py-2 hover:bg-blue-100 cursor-pointer';
        if (index === highlightedIndex) div.classList.add('bg-blue-100');

        div.addEventListener('click', () => {
            deptAutoInput.value = d;
            deptAutoDropdown.classList.add('hidden');
            moveToNextField();
        });

        deptAutoDropdown.appendChild(div);
    });

    deptAutoDropdown.classList.remove('hidden');
}

function moveToNextField(currentInput) {
    const form = currentInput.closest('form');
    if (!form) return;
    const inputs = Array.from(form.querySelectorAll('input, select, textarea'));
    const currentIndex = inputs.indexOf(currentInput);
    if (currentIndex >= 0 && currentIndex < inputs.length - 1) {
        inputs[currentIndex + 1].focus();
    }
}

// Handle input event
deptAutoInput.addEventListener('input', () => {
    highlightedIndex = -1; // reset highlight
    const value = deptAutoInput.value.toLowerCase();
    const filtered = deptAutoList.filter(d => d.toLowerCase().includes(value));
    renderDropdown(filtered);
});

// Handle keyboard navigation
deptAutoInput.addEventListener('keydown', (e) => {
    const items = Array.from(deptAutoDropdown.children);
    if (items.length === 0) return;

    if (e.key === 'ArrowDown') {
        e.preventDefault();
        highlightedIndex = (highlightedIndex + 1) % items.length;
        renderDropdown(Array.from(items).map(i => i.textContent));
    } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        highlightedIndex = (highlightedIndex - 1 + items.length) % items.length;
        renderDropdown(Array.from(items).map(i => i.textContent));
    } else if (e.key === 'Enter') {
    e.preventDefault();

    // Auto-select first item if none highlighted
    const indexToSelect = highlightedIndex >= 0 ? highlightedIndex : 0;

    if (items[indexToSelect]) {
        deptAutoInput.value = items[indexToSelect].textContent;
        deptAutoDropdown.classList.add('hidden');
        highlightedIndex = -1;
        moveToNextField();
    }
} else if (e.key === 'Escape') {
        deptAutoDropdown.classList.add('hidden');
    }
});

// Hide dropdown if clicked outside
document.addEventListener('click', (e) => {
    if (!deptAutoInput.contains(e.target) && !deptAutoDropdown.contains(e.target)) {
        deptAutoDropdown.classList.add('hidden');
    }
});

deptAutoInput.addEventListener('blur', (e) => {
    setTimeout(() => { // allow click event to fire first
        const deptValue = deptAutoInput.value; 

        // If input is empty, just hide dropdown
        if (deptValue === '') {
            deptAutoDropdown.classList.add('hidden');
            return;
        }

        // If value is not in list, show validation modal
        if (!deptAutoList.includes(deptValue)) {
            deptValidationModal.classList.remove('hidden');
            deptValidationOk.focus();
            deptValidationOk.onclick = () => {
                deptValidationModal.classList.add('hidden');
                deptAutoInput.focus();
            };
        } else {
            deptAutoDropdown.classList.add('hidden');
        }
    }, 100); // 100ms delay allows click event to trigger
});

document.addEventListener('DOMContentLoaded', () => {

    function initTotalCalculator(formId) {
        const form = document.getElementById(formId);
        if (!form) return;

        const unitInput  = form.querySelector('input[name="unit"]');
        const priceInput = form.querySelector('input[name="price"]');
        const sstInput   = form.querySelector('input[name="sst"]');
        const totalInput = form.querySelector('input[name="total_price"]');

        if (!unitInput || !priceInput || !totalInput) return;

        function formatNumberWithCommas(value) {
            const num = parseFloat(value.toString().replace(/,/g, '')) || 0;
            return num.toLocaleString('en-US', {
                minimumFractionDigits: 3,
                maximumFractionDigits: 3
            });
        }

        function calculateTotal() {
            const unit  = parseFloat(unitInput.value.replace(/,/g, '')) || 0;
            const price = parseFloat(priceInput.value.replace(/,/g, '')) || 0;
            const sst   = parseFloat(sstInput?.value.replace(/,/g, '')) || 0;

            let total = unit * price;
            if (sst > 0) total *= (1 + sst / 100);

            totalInput.value = formatNumberWithCommas(total);
        }

        // 🔒 Restrict input
        function allowOnlyNumbers(e) {
    const input = e.target;
    const key = e.key;

    // Allow control keys
    if (['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(key)) return;

    // Allow digits
    if (/[0-9]/.test(key)) return;

    // Allow ONE decimal point
    if (key === '.' && !input.value.includes('.')) return;

    // Allow ONE minus sign at the beginning only
    if (key === '-' && input.selectionStart === 0 && !input.value.includes('-')) return;

    e.preventDefault();
}


        // Input listeners
        [unitInput, priceInput, sstInput].forEach(input => {
            if (!input) return;

            input.addEventListener('input', calculateTotal);
            input.addEventListener('keydown', allowOnlyNumbers);
            input.addEventListener('blur', e => {
                e.target.value = formatNumberWithCommas(e.target.value);
            });
        });

        calculateTotal();
    }

    // Apply to both forms
    initTotalCalculator('transactionForm');
    initTotalCalculator('editTransactionForm');

});


document.addEventListener('DOMContentLoaded', () => {

    function enableEnterToNext(formId) {
        const form = document.getElementById(formId);
        if (!form) return;

        const inputs = Array.from(
            form.querySelectorAll('input, textarea')
        ).filter(el => !el.readOnly && !el.disabled);

        inputs.forEach((input, index) => {
            input.addEventListener('keydown', e => {
                if (e.key === 'Enter') {
                    e.preventDefault();

                    const next = inputs[index + 1];
                    if (next) {
                        next.focus();
                    }
                }
            });
        });
    }

    // ✅ Apply to both forms
    enableEnterToNext('transactionForm');
    enableEnterToNext('editTransactionForm');

});

const openTransactionBtn = document.getElementById('openAddTransactionBtn');
const transactionModal = document.getElementById('addTransactionModal');
const closeTransactionBtn = document.getElementById('closeModalBtn');

if (openTransactionBtn && transactionModal) {
    openTransactionBtn.addEventListener('click', () => {
        transactionModal.classList.remove('hidden');
    });
}

if (closeTransactionBtn && transactionModal) {
    closeTransactionBtn.addEventListener('click', () => {
        transactionModal.classList.add('hidden');
        if (typeof transactionForm !== 'undefined') transactionForm.reset();
    });
}

function refreshDepartmentTable(query = '') {
    let tbody = document.getElementById('departmentTbody');
    tbody.innerHTML = '';

    fetch('search_department.php?q=' + encodeURIComponent(query))
        .then(response => response.json())
        .then(data => {
            if (data.length === 0) {
                let row = document.createElement('tr');
                row.innerHTML = `<td colspan="2" class="px-4 py-2 text-gray-500 text-center">No departments found.</td>`;
                tbody.appendChild(row);
                return;
            }
            data.forEach(dept => {
                let row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition';
                row.innerHTML = `
    <td class="px-4 py-2 text-gray-800">${dept.name}</td>
    <td class="px-4 py-2">
        <div class="flex gap-2">
            <button class="edit-btn px-3 py-1 text-xs bg-yellow-400 text-white rounded hover:bg-yellow-500 transition"
                data-dept-id="${dept.id}" data-dept-name="${dept.name}">Edit</button>
            <button class="dept-delete-btn px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 transition"
                data-dept-id="${dept.id}" data-dept-name="${dept.name}">Delete</button>
        </div>
    </td>`;
                tbody.appendChild(row);
            });
        });
}

document.getElementById('departmentSearch').addEventListener('input', function() {
    let query = this.value;
    fetch('search_department.php?q=' + encodeURIComponent(query))
        .then(response => response.json())
        .then(data => {
            let tbody = document.getElementById('departmentTbody');
            tbody.innerHTML = '';
            data.forEach(dept => {
                let row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition';
                row.innerHTML = `
                    <td class="px-4 py-2 text-gray-800">${dept.name}</td>
                    <td class="px-4 py-2">
                        <div class="flex gap-2">
                            <button class="edit-btn px-3 py-1 text-xs bg-yellow-400 text-white rounded hover:bg-yellow-500 transition"
                                data-dept-id="${dept.id}" data-dept-name="${dept.name}">Edit</button>
                            <button class="dept-delete-btn px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 transition"
                                data-dept-id="${dept.id}" data-dept-name="${dept.name}">Delete</button>
                        </div>
                    </td>`;
                tbody.appendChild(row);
            });
        });
});

// Modal Elements
var addModal = document.getElementById('addDepartmentModal');
var closeAddBtn = document.getElementById('closeAddDepartmentModal');

// Success Modal Elements
var successModal = document.getElementById('successModal');
var successMessage = document.getElementById('successMessage');
var successOkBtn = document.getElementById('successOkBtn');

// Table body
var tableBody = document.getElementById('departmentTbody');

// Close Add Department Modal
closeAddBtn.onclick = function() {
    addModal.classList.add('hidden');
};

// Handle Add Department Form Submission
document.getElementById('addDepartmentForm').onsubmit = function(e){
    e.preventDefault();
    var nameInput = document.getElementById('departmentName');
    var name = nameInput.value.trim();

    if(name === '') {
        showErrorModal('Please enter a department name.');
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'add_department.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onload = function() {
        if(xhr.status === 200) {
            if(xhr.responseText.trim() === 'duplicate') {
                showErrorModal('This department already exists!');
                return;
            }

            // Close Add Department modal
            addModal.classList.add('hidden');
            nameInput.value = '';

            // Show Success Modal
            successMessage.textContent = xhr.responseText;
            successModal.classList.remove('hidden');

            successOkBtn.onclick = function() {
                successModal.classList.add('hidden');
                // Refresh the table instead of adding a new row
                refreshDepartmentTable(document.getElementById('departmentSearch').value);
            };

        } else {
            showErrorModal('Error adding department.');
        }
    };

    xhr.send('name=' + encodeURIComponent(name));
};

// Function to show your custom error modal
function showErrorModal(msg) {
    var errorModal = document.getElementById('errorModal');
    var errorMessage = document.getElementById('errorMessage');
    var errorOkBtn = document.getElementById('errorOkBtn');

    errorMessage.textContent = msg;
    errorModal.classList.remove('hidden');

    errorOkBtn.onclick = function() {
        errorModal.classList.add('hidden');
    };
}


    const departmentModal = document.getElementById('departmentModal');
    const openBtn = document.getElementById('openDepartmentModal');
    const closeBtn = document.getElementById('closeDepartmentModal');

    openBtn.addEventListener('click', () => {
        departmentModal.classList.remove('hidden');
    });

    closeBtn.addEventListener('click', () => {
        departmentModal.classList.add('hidden');
        refreshTransactionTable();
    });
    
// Select all unit and price inputs inside both modals
const numberInputs = document.querySelectorAll(
  '#addTransactionModal input[name="unit"], #addTransactionModal input[name="price"], \
   #editTransactionModal input[name="unit"], #editTransactionModal input[name="price"]'
);

function allowOnlyNumbers(e) {
  // Allow digits, dot, backspace, delete, arrows, tab
  if (!/[0-9.]|\b/.test(e.key) && !['Backspace','Delete','ArrowLeft','ArrowRight','Tab'].includes(e.key)) 
    // Allow ONE minus sign at the beginning
  if (key === '-' && input.selectionStart === 0 && !input.value.includes('-'))
  {
    e.preventDefault();
  }
}

function formatNumberWithCommas(value) {
  let num = parseFloat(value.replace(/,/g, ''));
  if (!isNaN(num)) {
    return num.toLocaleString('en-US', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
  }
  return '0.00';
}

// Bind events for all inputs
numberInputs.forEach(input => {
  input.addEventListener('keydown', allowOnlyNumbers);

  input.addEventListener('blur', () => {
    if (input.value.trim() !== '') {
      input.value = formatNumberWithCommas(input.value);
    }
  });
});
</script>


</body>
</html>
