<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); if (!has_role(['admin','super_admin'])) { http_response_code(403); echo 'Forbidden'; exit; } ?>
<div class="page-store-locations">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Store Locations</h4>
      <button id="btnNewStore" class="btn btn-primary"><i class="bi bi-plus-lg"></i></button>
    </div>

    <div class="card shadow-sm mb-3"><div class="card-body">
      <div class="row g-2 align-items-end">
        <div class="col-md-4">
          <label class="form-label">Branch</label>
          <select id="fltBranch" class="form-select"></select>
        </div>
        <div class="col-md-2">
          <button id="btnSearch" class="btn btn-outline-secondary w-100"><i class="bi bi-search"></i></button>
        </div>
      </div>
    </div></div>

    <div class="card shadow-sm"><div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover align-middle" id="stTable">
          <thead><tr><th>Name</th><th>Branch</th><th>Status</th><th style="width:140px">Actions</th></tr></thead>
          <tbody></tbody>
        </table>
      </div>
    </div></div>
  </div>
</div>

<div class="modal fade" id="stModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Store Location</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
    <form id="stForm">
      <div class="modal-body">
        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        <input type="hidden" name="id" id="st_id">
        <div class="mb-2"><label class="form-label">Name</label><input type="text" class="form-control" name="name" id="st_name" required></div>
        <div class="mb-2"><label class="form-label">Branch</label><select class="form-select" name="branch_id" id="st_branch"></select></div>
        <div class="mb-2"><label class="form-label">Notes</label><input type="text" class="form-control" name="notes" id="st_notes"></div>
        <div class="mb-2"><label class="form-label">Active</label><select class="form-select" name="is_active" id="st_active"><option value="1">Active</option><option value="0">Inactive</option></select></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(){
  if (!$('.page-store-locations').length) return;

  function loadBranches(){
    $.get('api/branches.php', { action:'list' }, function(res){
      const opts=['<option value="">All</option>']; const eopts=['<option value="">Select</option>'];
      (res.data||[]).forEach(b=>{ opts.push(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`); eopts.push(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`); });
      $('#fltBranch').html(opts.join('')); $('#st_branch').html(eopts.join(''));
    });
  }

  function load(){
    const params={ action:'list' };
    const b=$('#fltBranch').val(); if(b) params.branch_id=b; // admins can filter; non-admins ignored by API
    $.get('api/store_locations.php', params, function(res){
      const $tb=$('#stTable tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No stores</td></tr>'); return; }
      const mapBr = {}; $('#st_branch option').each(function(){ const v=$(this).val(); if(v) mapBr[v]=$(this).text(); });
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(mapBr[r.branch_id]||'').html()}</td>`);
        tr.append(`<td><span class="badge bg-${r.is_active? 'success':'secondary'}">${r.is_active? 'Active':'Inactive'}</span></td>`);
        const act=[
          `<button class=\"btn btn-sm btn-outline-primary me-1 st-edit\" data-id=\"${r.id}\" data-branch=\"${r.branch_id??''}\" title=\"Edit\"><i class=\"bi bi-pencil\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-danger st-del\" data-id=\"${r.id}\" title=\"Delete\"><i class=\"bi bi-trash\"></i></button>`
        ];
        tr.append(`<td>${act.join('')}</td>`);
        $tb.append(tr);
      });
    }).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error loading stores'));
  }

  $('#btnSearch').on('click', load);
  $('#btnNewStore').on('click', function(){ $('#stForm')[0].reset(); $('#st_id').val(''); $('#st_active').val('1'); $('#stModal').modal('show'); });

  $(document).on('click','.st-edit', function(){
    const tr=$(this).closest('tr'); $('#stForm')[0].reset(); $('#st_id').val($(this).data('id'));
    $('#st_name').val(tr.children().eq(0).text());
    const bId = $(this).data('branch');
    $('#st_branch').val(bId != null ? String(bId) : '');
    $('#st_active').val(tr.children().eq(2).text()==='Active'?'1':'0');
    $('#stModal').modal('show');
  });

  $('#stForm').on('submit', function(e){ e.preventDefault(); const fd=new FormData(this); const isUpd=!!$('#st_id').val(); fd.append('action', isUpd?'update':'create');
    $.ajax({ url:'api/store_locations.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#stModal').modal('hide'); load(); })
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error'));
  });

  $(document).on('click','.st-del', function(){ if(!confirm('Delete this store?')) return; const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('action','delete'); fd.append('id', $(this).data('id'));
    $.ajax({ url:'api/store_locations.php', method:'POST', data:fd, contentType:false, processData:false }).done(load).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error'));
  });

  loadBranches(); load();
})();
</script>
