<?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-branches">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Branches</h4>
      <button id="btnNewBranch" class="btn btn-primary"><i class="bi bi-plus-lg"></i></button>
    </div>

<!-- Manage Branch Users Modal -->
<div class="modal fade" id="buModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Users - <span id="buBranchTitle"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <div class="small text-muted">Manage system users for this branch</div>
          <button class="btn btn-sm btn-primary" id="btnNewBranchUser"><i class="bi bi-plus-lg"></i> New User</button>
        </div>
        <div class="table-responsive">
          <table class="table table-hover align-middle" id="buTable">
            <thead><tr><th>Username</th><th>Name</th><th>Role</th><th>Status</th><th style="width:160px;">Actions</th></tr></thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
  </div>

<!-- Add/Edit Branch User Modal -->
<div class="modal fade" id="buUserModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="buModalFormTitle">Add User</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
      <form id="buForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="id" id="bu_user_id">
          <div class="mb-2"><label class="form-label">Username</label><input type="text" class="form-control" name="username" id="bu_username" required></div>
          <div class="mb-2"><label class="form-label">Full Name</label><input type="text" class="form-control" name="full_name" id="bu_full_name"></div>
          <div class="mb-2"><label class="form-label">Role</label>
            <select class="form-select" name="role" id="bu_role">
              <option value="sales_user">Sales User</option>
              <option value="inventory_user">Inventory User</option>
              <option value="account_user">Account User</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          <div class="mb-2"><label class="form-label">Password <span class="text-muted small">(required for new user)</span></label><input type="password" class="form-control" name="password" id="bu_password" autocomplete="new-password"></div>
          <div class="mb-2"><label class="form-label">Active</label><select class="form-select" name="is_active" id="bu_is_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>

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

<div class="modal fade" id="brModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Branch</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>
    <form id="brForm">
      <div class="modal-body">
        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        <input type="hidden" name="id" id="br_id">
        <div class="mb-2"><label class="form-label">Name</label><input type="text" class="form-control" name="name" id="br_name" required></div>
        <div class="mb-2"><label class="form-label">Address</label><input type="text" class="form-control" name="address" id="br_address"></div>
        <div class="mb-2"><label class="form-label">Phone</label><input type="text" class="form-control" name="phone" id="br_phone"></div>
        <div class="mb-2"><label class="form-label">Active</label><select class="form-select" name="is_active" id="br_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-branches').length) return;
  function load(){
    $.get('api/branches.php',{action:'list'}, function(res){
      const $tb=$('#brTable tbody'); $tb.empty(); const rows=res.data||[];
      if(!rows.length){ $tb.append('<tr><td colspan="4" class="text-center text-muted">No branches</td></tr>'); return; }
      rows.forEach(r=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(r.name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(r.phone||'').html()}</td>`);
        tr.append(`<td><span class="badge bg-${r.is_active==1?'success':'secondary'}">${r.is_active==1?'Active':'Inactive'}</span></td>`);
        const act=[
          `<button class=\"btn btn-sm btn-outline-secondary me-1 br-users\" data-id=\"${r.id}\" data-name=\"${$('<div>').text(r.name||'').html()}\" title=\"Manage Users\" aria-label=\"Manage Users\"><i class=\"bi bi-people\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-primary me-1 br-edit\" data-id=\"${r.id}\" title=\"Edit\" aria-label=\"Edit\"><i class=\"bi bi-pencil\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-danger br-del\" data-id=\"${r.id}\" title=\"Delete\" aria-label=\"Delete\"><i class=\"bi bi-trash\"></i></button>`
        ];
        tr.append(`<td>${act.join('')}</td>`); $tb.append(tr);
      });
    });
  }
  $('#btnNewBranch').on('click', function(){ $('#brForm')[0].reset(); $('#br_id').val(''); $('#br_active').val('1'); $('#brModal').modal('show'); });
  $(document).on('click','.br-edit', function(){
    const id=$(this).data('id');
    $.get('api/branches.php',{action:'get', id}, function(res){
      const d=res.data||{};
      $('#br_id').val(d.id);
      $('#br_name').val(d.name||'');
      $('#br_address').val(d.address||'');
      $('#br_phone').val(d.phone||'');
      $('#br_active').val(String(d.is_active??1));
      $('#brModal').modal('show');
    });
  });
  $('#brForm').on('submit', function(e){ e.preventDefault(); const fd=new FormData(this); const isUpd=!!$('#br_id').val(); fd.append('action', isUpd?'update':'create');
    $.ajax({ url:'api/branches.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(()=>{ $('#brModal').modal('hide'); load(); })
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||'Error'));
  });
  $(document).on('click','.br-del', function(){ if(!confirm('Delete this branch?')) return; const id=$(this).data('id'); const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('action','delete'); fd.append('id',id);
    $.ajax({ url:'api/branches.php', method:'POST', data:fd, contentType:false, processData:false }).done(load).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||'Error'));
  });

  // -------- Branch Users --------
  function loadBranchUsers(branchId){
    $('#buTable tbody').empty().append('<tr><td colspan="5" class="text-center text-muted">Loading...</td></tr>');
    $.get('api/branch_users.php', { action:'list', branch_id: branchId }, function(res){
      const $tb = $('#buTable tbody'); $tb.empty(); const list=res.data||[];
      if(!list.length){ $tb.append('<tr><td colspan="5" class="text-center text-muted">No users</td></tr>'); return; }
      list.forEach(u=>{
        const tr=$('<tr>');
        tr.append(`<td>${$('<div>').text(u.username||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(u.full_name||'').html()}</td>`);
        tr.append(`<td><span class=\"badge bg-secondary text-capitalize\">${u.role||''}</span></td>`);
        tr.append(`<td><span class=\"badge bg-${u.is_active? 'success':'secondary'}\">${u.is_active? 'Active':'Inactive'}</span></td>`);
        const act=[
          `<button class=\"btn btn-sm btn-outline-primary me-1 bu-edit\" data-id=\"${u.id}\" title=\"Edit\"><i class=\"bi bi-pencil\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-warning me-1 bu-reset\" data-id=\"${u.id}\" title=\"Reset Password\"><i class=\"bi bi-key\"></i></button>`,
          `<button class=\"btn btn-sm btn-outline-danger bu-disable\" data-id=\"${u.id}\" title=\"Disable\"><i class=\"bi bi-person-x\"></i></button>`
        ];
        tr.append(`<td>${act.join('')}</td>`);
        $tb.append(tr);
      });
    }).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error loading users'));
  }

  let currentBranchId=null;
  $(document).on('click','.br-users', function(){
    currentBranchId=$(this).data('id'); const name=$(this).data('name')||'Branch';
    $('#buBranchTitle').text(name);
    $('#buModal').modal('show');
    loadBranchUsers(currentBranchId);
  });

  $('#btnNewBranchUser').on('click', function(){
    $('#buForm')[0].reset(); $('#bu_user_id').val(''); $('#bu_role').val('sales_user'); $('#bu_is_active').val('1');
    $('#bu_username').prop('disabled', false);
    $('#buModalFormTitle').text('Add User');
    $('#buUserModal').modal('show');
  });

  $(document).on('click','.bu-edit', function(){
    // Load minimal into form from row
    const tr=$(this).closest('tr');
    $('#buForm')[0].reset(); $('#bu_user_id').val($(this).data('id'));
    $('#bu_username').val(tr.children().eq(0).text()).prop('disabled', true);
    $('#bu_full_name').val(tr.children().eq(1).text());
    $('#bu_role').val(tr.children().eq(2).text().toLowerCase());
    $('#bu_is_active').val(tr.children().eq(3).text()==='Active'?'1':'0');
    $('#buModalFormTitle').text('Edit User');
    $('#buUserModal').modal('show');
  });

  $('#buForm').on('submit', function(e){ e.preventDefault(); if(!currentBranchId) return alert('No branch');
    const fd=new FormData(this); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>');
    const isUpd=!!$('#bu_user_id').val(); fd.append('action', isUpd?'update':'create');
    if(!isUpd){ fd.append('branch_id', currentBranchId); if(!$('#bu_password').val()) return alert('Password required'); }
    $.ajax({ url:'api/branch_users.php', method:'POST', data:fd, contentType:false, processData:false })
      .done(function(){ $('#buUserModal').modal('hide'); loadBranchUsers(currentBranchId); })
      .fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error'));
  });

  $(document).on('click','.bu-reset', function(){ const id=$(this).data('id'); const pw=prompt('Enter new password'); if(!pw) return; const fd=new FormData(); fd.append('csrf','<?php echo htmlspecialchars(csrf_token()); ?>'); fd.append('action','reset_password'); fd.append('id',id); fd.append('password',pw);
    $.ajax({ url:'api/branch_users.php', method:'POST', data:fd, contentType:false, processData:false }).done(()=>loadBranchUsers(currentBranchId)).fail(xhr=>alert((xhr.responseJSON&&xhr.responseJSON.message)||xhr.responseText||'Error'));
  });

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