<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';
?>

<div class="container mt-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4><i class="fa fa-leaf text-success"></i> Perishable Qty Per Person</h4>
    <div>
        <button class="btn btn-primary" onclick="window.location.href='perishable_items.php'">
            <i class="fa fa-arrow-left"></i> Add Perishable Item
        </button>
        <button class="btn btn-success ms-2" onclick="window.location.href='export_perishables_excel.php'">
            <i class="fa fa-file-excel"></i> Export to Excel
        </button>
    </div>
  </div>

  <hr>

  <!-- ===== ADD FORM ===== -->
  <div class="card mb-4">
      <div class="card-header bg-success text-white">
          <i class="fa fa-plus"></i> Assign Quantity Per Person
      </div>
      <div class="card-body">

          <form id="paramForm" class="row g-3">
              <input type="hidden" name="action" value="save">
              <input type="hidden" name="edit_id" value="">

              <div class="col-md-3">
                  <label class="form-label">Perishable Item</label>
                  <select name="perishable_id" class="form-control" required>
                      <option value="">Select Item</option>
                      <?php
                      $res = $conn->query("SELECT id, name, unit FROM perishables ORDER BY name ASC");
                      while($row = $res->fetch_assoc()){
                          $display = "{$row['name']} ({$row['unit']})";
                          echo "<option value='{$row['id']}'>{$display}</option>";
                      }
                      ?>
                  </select>
              </div>

              <div class="col-md-2">
                  <label class="form-label">Unit Cost</label>
                  <input type="number" step="0.01" name="unit_cost" class="form-control" required>
              </div>

              <div class="col-md-2">
                  <label class="form-label">Qty Per Person</label>
                  <input type="number" step="0.01" name="qty_per_person" class="form-control" required>
              </div>

              <div class="col-md-3">
                  <label class="form-label">Number of Items / Composition</label>
                  <input type="number" step="1" name="composition" class="form-control" required>
              </div>

              <div class="col-md-2 d-flex align-items-end">
                  <button class="btn btn-primary me-2">
                      <i class="fa fa-save"></i> Save
                  </button>
                  <button type="button" class="btn btn-secondary" onclick="resetForm()">
                      Cancel
                  </button>
              </div>
          </form>

      </div>
  </div>
<!-- ===== SEARCH ===== -->
<div class="mb-3">
    <input type="text" id="searchInput" class="form-control" placeholder="Search perishable items...">
</div>
  <div id="message" class="mb-3 text-success"></div>

  <!-- ===== TABLE ===== -->
  <table class="table table-bordered table-striped table-hover table-sm">
      <thead class="table-dark">
          <tr>
              <th>#</th>
              <th>Item</th>
              <th>Units</th>
              <th>Unit Cost</th>
              <th>Qty Per Person</th>
              <th>Composition</th>
              <th width="150">Action</th>
          </tr>
      </thead>
      <tbody id="paramsTable"></tbody>
  </table>

</div>

<script>
// ===== LOAD =====
function loadParams(){
    fetch('perishable_parameters_action.php', {
        method:'POST',
        body:new URLSearchParams({action:'list'})
    })
    .then(r=>r.json())
    .then(data=>{
        let tbody=document.getElementById('paramsTable');
        tbody.innerHTML='';

        if(data.length===0){
            tbody.innerHTML='<tr><td colspan="7" class="text-center">No data</td></tr>';
            return;
        }

        let i=1;
        data.forEach(row=>{
            tbody.innerHTML+=`
            <tr>
                <td>${i++}</td>
                <td>${row.name}</td>
                <td>${row.unit}</td>
                <td>${row.unit_cost}</td>
                <td>${row.qty_per_person}</td>
                <td>${row.composition}</td>
                <td>
                    <button class="btn btn-sm btn-warning me-1"
                        onclick="editRow(${row.id},${row.perishable_id},${row.qty_per_person},${row.composition},${row.unit_cost})">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger"
                        onclick="removeRow(${row.id})">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            </tr>`;
        });
    });
}

// ===== SAVE =====
document.getElementById('paramForm').addEventListener('submit',function(e){
    e.preventDefault();

    fetch('perishable_parameters_action.php',{
        method:'POST',
        body:new FormData(this)
    })
    .then(r=>r.text())
    .then(msg=>{
        document.getElementById('message').innerText=msg;
        setTimeout(()=>document.getElementById('message').innerText='',3000);
        this.reset();
        this.edit_id.value='';
        loadParams();
    });
});

// ===== EDIT =====
function editRow(id, perishable_id, qty, composition, unit_cost){
    document.querySelector('[name="edit_id"]').value = id;
    document.querySelector('[name="perishable_id"]').value = perishable_id;
    document.querySelector('[name="qty_per_person"]').value = qty;
    document.querySelector('[name="composition"]').value = composition;
    document.querySelector('[name="unit_cost"]').value = unit_cost;
}

// ===== DELETE =====
function removeRow(id){
    if(!confirm('Remove this item?')) return;

    fetch('perishable_parameters_action.php',{
        method:'POST',
        body:new URLSearchParams({action:'remove',id:id})
    })
    .then(r=>r.text())
    .then(msg=>{
        document.getElementById('message').innerText=msg;
        loadParams();
    });
}

function resetForm(){
    document.getElementById('paramForm').reset();
    document.querySelector('[name="edit_id"]').value='';
}

// initial load
loadParams();



// ===== LOAD =====
let allParams = []; // store all rows globally for filtering

function loadParams(){
    fetch('perishable_parameters_action.php', {
        method:'POST',
        body:new URLSearchParams({action:'list'})
    })
    .then(r=>r.json())
    .then(data=>{
        allParams = data; // store data
        renderTable(data);
    });
}

// ===== RENDER TABLE =====
function renderTable(data){
    let tbody=document.getElementById('paramsTable');
    tbody.innerHTML='';

    if(data.length===0){
        tbody.innerHTML='<tr><td colspan="7" class="text-center">No data</td></tr>';
        return;
    }

    let i=1;
    data.forEach(row=>{
        tbody.innerHTML+=`
        <tr>
            <td>${i++}</td>
            <td>${row.name}</td>
            <td>${row.unit}</td>
            <td>${row.unit_cost}</td>
            <td>${row.qty_per_person}</td>
            <td>${row.composition}</td>
            <td>
                <button class="btn btn-sm btn-warning me-1"
                    onclick="editRow(${row.id},${row.perishable_id},${row.qty_per_person},${row.composition},${row.unit_cost})">
                    <i class="fa fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-danger"
                    onclick="removeRow(${row.id})">
                    <i class="fa fa-trash"></i>
                </button>
            </td>
        </tr>`;
    });
}

// ===== LIVE SEARCH =====
document.getElementById('searchInput').addEventListener('input', function(){
    const query = this.value.toLowerCase();
    const filtered = allParams.filter(row => 
        row.name.toLowerCase().includes(query) ||
        row.unit.toLowerCase().includes(query) ||
        row.unit_cost.toString().includes(query) ||
        row.qty_per_person.toString().includes(query) ||
        row.composition.toString().includes(query)
    );
    renderTable(filtered);
});
</script>