<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-production">
  <div class="container-fluid p-4">
    <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />
    <input type="hidden" id="isAdmin" value="<?php echo has_role(['admin','super_admin']) ? '1' : '0'; ?>">
    <input type="hidden" id="userBranchId" value="<?php echo htmlspecialchars($_SESSION['branch_id'] ?? ''); ?>">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Production Inventory</h4>
      <div class="d-flex gap-2">
        <button id="btnAddProd" class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i>Add Item</button>
        <button id="btnReloadProd" class="btn btn-outline-secondary"><i class="bi bi-arrow-repeat"></i></button>
      </div>
    </div>

    <div class="card shadow-sm mb-3"><div class="card-body">
      <div class="row g-2">
        <div class="col-md-3">
          <label class="form-label">Type</label>
          <select id="prodTypeFilter" class="form-select"><option value="">All</option></select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Color</label>
          <select id="prodColorFilter" class="form-select"><option value="">All</option></select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Finish</label>
          <select id="prodFinishFilter" class="form-select"><option value="">All</option></select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Availability</label>
          <select id="prodAvailFilter" class="form-select">
            <option value="">All</option>
            <option value="available">Available</option>
            <option value="reserved">Reserved</option>
            <option value="sold">Sold</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Search</label>
          <div class="input-group">
            <input id="prodSearch" class="form-control" placeholder="Notes contains...">
            <button id="btnProdSearch" class="btn btn-outline-secondary"><i class="bi bi-search"></i></button>
          </div>
        </div>
        <div class="col-md-3">
          <label class="form-label">Branch</label>
          <select id="prodBranchFilter" class="form-select"><option value="">All</option></select>
        </div>
      </div>
    </div></div>

    <div class="card shadow-sm"><div class="card-body">
      <div class="table-responsive">
        <table id="prod-table" class="table table-hover align-middle">
          <thead><tr>
            <th>ID</th><th>Name</th><th>Type</th><th>Color</th><th>Finish</th><th class="text-end">Length</th><th class="text-end">Width</th><th class="text-end">Thickness</th><th class="text-end">Qty</th><th>Availability</th><th>Branch</th><th>Notes</th><th></th>
          </tr></thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>
  </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="prodModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">Production Item</h5><button class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
      <form id="prodForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="action" value="create">
          <input type="hidden" name="id" id="prodId">
          <div class="row g-2">
            <div class="col-md-12">
              <label class="form-label">Name</label>
              <input type="text" name="name" id="prodName" class="form-control" placeholder="Item name (optional)">
            </div>
            <div class="col-md-6">
              <label class="form-label">Type</label>
              <select name="type_id" id="prodType" class="form-select" required></select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Color</label>
              <select name="color_id" id="prodColor" class="form-select"></select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Finish</label>
              <select name="finish_id" id="prodFinish" class="form-select"></select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Length</label>
              <input type="number" step="0.01" min="0" name="length" id="prodLength" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Width</label>
              <input type="number" step="0.01" min="0" name="width" id="prodWidth" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Thickness</label>
              <input type="number" step="0.01" min="0" name="thickness" id="prodThickness" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Quantity</label>
              <input type="number" step="1" min="1" name="quantity" id="prodQty" class="form-control" value="1" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Availability</label>
              <select name="availability" id="prodAvail" class="form-select">
                <option value="available">Available</option>
                <option value="reserved">Reserved</option>
                <option value="sold">Sold</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Branch <span class="text-danger">*</span></label>
              <select name="branch_id" id="prodBranch" class="form-select" required></select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Notes</label>
              <input type="text" name="notes" id="prodNotes" class="form-control">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function($){
$(function(){
  if (!$('.page-production').length) return;
  function loadLookups(){
    const isAdmin = $('#isAdmin').val() === '1';
    const userBranchId = $('#userBranchId').val();

    // Types from materials API
    $.get('api/materials.php', { action:'list_types' }, function(res){
      const types=(res.data||res.types||[]);
      $('#prodType, #prodTypeFilter').each(function(){
        const isFilter=this.id==='prodTypeFilter';
        const opts=types.map(t=>`<option value="${t.id}">${$('<div>').text(t.name).html()}</option>`).join('');
        $(this).html((isFilter?'<option value="">All</option>':'')+opts);
      });
    });
    // Colors from materials API
    $.get('api/materials.php', { action:'list_colors' }, function(res){
      const colors=(res.data||res.colors||[]);
      $('#prodColor, #prodColorFilter').each(function(){
        const isFilter=this.id==='prodColorFilter';
        const opts=colors.map(c=>`<option value="${c.id}">${$('<div>').text(c.name).html()}</option>`).join('');
        $(this).html((isFilter?'<option value="">All</option>':'')+opts);
      });
    });
    // Finishes from materials API
    $.get('api/materials.php', { action:'list_finishes' }, function(res){
      const finishes=(res.data||res.finishes||[]);
      $('#prodFinish, #prodFinishFilter').each(function(){
        const isFilter=this.id==='prodFinishFilter';
        const opts=finishes.map(f=>`<option value="${f.id}">${$('<div>').text(f.name).html()}</option>`).join('');
        $(this).html((isFilter?'<option value="">All</option>':'')+opts);
      });
    });
    // Branches for filter
    $.get('api/branches.php', { action:'list' }, function(res){
      const branches=(res.data||[]).filter(b=>parseInt(b.is_active));
      const opts=['<option value="">All</option>'];
      branches.forEach(b=>opts.push(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`));
      $('#prodBranchFilter').html(opts.join(''));

      // For non-admin users: auto-select their branch and disable the filter
      if (!isAdmin && userBranchId) {
        $('#prodBranchFilter').val(userBranchId).prop('disabled', true);
      }
    });

    // Branches for modal (no "All" option, for selection)
    $.get('api/branches.php', { action:'list' }, function(res){
      const branches=(res.data||[]).filter(b=>parseInt(b.is_active));
      const opts=[];
      branches.forEach(b=>opts.push(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`));
      $('#prodBranch').html(opts.join(''));
    });
  }

  function loadProd(){
    const isAdmin = $('#isAdmin').val() === '1';
    const userBranchId = $('#userBranchId').val();
    const params={ action:'list' };
    const t=$('#prodTypeFilter').val(); if(t) params.type_id=t;
    const av=$('#prodAvailFilter').val(); if(av) params.availability=av;
    const cf=$('#prodColorFilter').val(); if(cf) params.color_id=cf;
    const ff=$('#prodFinishFilter').val(); if(ff) params.finish_id=ff;
    const q=$('#prodSearch').val(); if(q) params.q=q;
    // For non-admin users, always use their assigned branch
    const branchId = isAdmin ? $('#prodBranchFilter').val() : (userBranchId || $('#prodBranchFilter').val());
    if(branchId) params.branch_id=branchId;
    $.get('api/production_items.php', params, function(res){
      const $tb=$('#prod-table tbody'); $tb.empty();
      const rows=res.data||[]; if(!rows.length){ $tb.append('<tr><td colspan="13" class="text-center text-muted">No items</td></tr>'); return; }
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${r.id}</td>`);
        tr.append(`<td>${$('<div>').text(r.name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.type_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.color_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.finish_name||'').html()}</td>`);
        tr.append(`<td class="text-end">${Number(r.length||0).toFixed(2)}</td>`);
        tr.append(`<td class="text-end">${Number(r.width||0).toFixed(2)}</td>`);
        tr.append(`<td class="text-end">${Number(r.thickness||0).toFixed(2)}</td>`);
        tr.append(`<td class="text-end">${Number(r.quantity||0)}</td>`);
        tr.append(`<td>${$('<div>').text(r.availability||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.branch_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.notes||'').html()}</td>`);
        const act=[
          `<button class=\"btn btn-sm btn-outline-primary me-1 btn-edit\" data-id=\"${r.id}\"><i class=\"bi bi-pencil\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-danger btn-del\" data-id=\"${r.id}\"><i class=\"bi bi-trash\"></i></button>`
        ];
        tr.append(`<td>${act.join('')}</td>`);
        $tb.append(tr);
      });
    });
  }

  function showModalById(id){
    const el=document.getElementById(id); if(!el) return;
    if (window.bootstrap && bootstrap.Modal){ bootstrap.Modal.getOrCreateInstance(el).show(); }
    else if (window.jQuery && typeof jQuery.fn.modal==='function'){ $('#'+id).modal('show'); }
    else { el.style.display='block'; }
  }

  // Add item
  $('#btnAddProd').on('click', function(){
    const frm=$('#prodForm')[0]; if(frm) frm.reset();
    $('#prodForm [name="action"]').val('create');
    $('#prodId').val('');
    // Set default branch for non-admin users
    const isAdmin = $('#isAdmin').val() === '1';
    const userBranchId = $('#userBranchId').val();
    if (!isAdmin && userBranchId) {
      $('#prodBranch').val(userBranchId).prop('disabled', true);
    } else {
      $('#prodBranch').prop('disabled', false);
    }
    showModalById('prodModal');
  });

  // Edit item
  $(document).on('click','.btn-edit', function(){
    const id=$(this).data('id');
    $.get('api/production_items.php', { action:'list', id }, function(res){
      const row=(res.data||[]).find(x=>String(x.id)===String(id));
      if(!row) return;
      $('#prodForm')[0].reset();
      $('#prodForm [name="action"]').val('update');
      $('#prodId').val(row.id);
      $('#prodName').val(row.name||'');
      $('#prodType').val(row.type_id);
      $('#prodColor').val(row.color_id||'');
      $('#prodFinish').val(row.finish_id||'');
      $('#prodBranch').val(row.branch_id||'').prop('disabled', false);
      // quality removed from modal; keep filter only
      $('#prodLength').val(row.length);
      $('#prodWidth').val(row.width);
      $('#prodThickness').val(row.thickness);
      $('#prodQty').val(row.quantity);
      $('#prodAvail').val(row.availability);
      $('#prodNotes').val(row.notes||'');
      const el=document.getElementById('prodModal'); if (window.bootstrap && bootstrap.Modal){ bootstrap.Modal.getOrCreateInstance(el).show(); } else { $('#prodModal').modal('show'); }
    });
  });

  // Delete
  $(document).on('click','.btn-del', function(){
    if(!confirm('Delete this item?')) return;
    const id=$(this).data('id');
    const fd=new FormData(); fd.append('csrf',$('#csrf').val()); fd.append('action','delete'); fd.append('id', id);
    $.ajax({ url:'api/production_items.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(()=>loadProd())
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||'Error'));
  });

  // Save form
  $('#prodForm').on('submit', function(e){
    e.preventDefault();
    // Client-side validation because preventDefault disables native required checks
    const typeId = $('#prodType').val();
    const length = parseFloat($('#prodLength').val()||'0');
    const width = parseFloat($('#prodWidth').val()||'0');
    const thick = parseFloat($('#prodThickness').val()||'0');
    const qty = parseInt($('#prodQty').val()||'0',10);
    if(!typeId){ alert('Please select Type'); return; }
    if(!(length>0)){ alert('Length must be greater than 0'); return; }
    if(!(width>0)){ alert('Width must be greater than 0'); return; }
    if(!(thick>0)){ alert('Thickness must be greater than 0'); return; }
    if(!(qty>=1)){ alert('Quantity must be at least 1'); return; }

    const fd=new FormData(this);
    const act=$('#prodForm [name="action"]').val()||'create';
    fd.set('action', act);
    const $btn=$(this).find('button[type="submit"]'); const oldTxt=$btn.text();
    $btn.prop('disabled', true).text('Saving...');
    $.ajax({ url:'api/production_items.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(()=>{ 
        const el=document.getElementById('prodModal');
        if (el && window.bootstrap && bootstrap.Modal){ bootstrap.Modal.getOrCreateInstance(el).hide(); }
        else { $('#prodModal').modal('hide'); }
        loadProd();
      })
      .fail(xhr=>{
        const msg=(xhr.responseJSON&&xhr.responseJSON.message)||xhr.statusText||'Error';
        alert('Failed to save: '+msg);
      })
      .always(()=>{ $btn.prop('disabled', false).text(oldTxt); });
  });

  $('#btnProdSearch').on('click', loadProd);
  $('#btnReloadProd').on('click', loadProd);
  $('#prodTypeFilter,#prodAvailFilter,#prodColorFilter,#prodFinishFilter,#prodBranchFilter').on('change', loadProd);
  $('#prodSearch').on('keydown', function(e){ if(e.key==='Enter') loadProd(); });

  loadLookups();
  loadProd();
});
})(window.jQuery);
</script>
