<?php
session_start();
if (!isset($_SESSION['admin'])) {
  echo "<script>document.location.href='logout.php';</script>";
  exit;
}

require_once '../core/conn.php';

/** Admin */
$rs = mysqli_query($con, "SELECT id, username FROM admin WHERE id=".(int)$_SESSION['admin']." LIMIT 1");
$admin = ($rs && mysqli_num_rows($rs)) ? mysqli_fetch_assoc($rs) : ['id'=>0,'username'=>'Admin'];

/** Branches */
$branches = [];
$q = mysqli_query($con, "SELECT id, company_name, state, lga, status
                         FROM branches
                         ORDER BY id DESC");
if ($q) while ($b = mysqli_fetch_assoc($q)) $branches[] = $b;

require_once 'include/header.php';
?>

<!-- Bootstrap + DataTables (for table + modal styling) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/v/bs4/dt-1.13.8/datatables.min.css">

<style>
  .modal-content{border-radius:18px; overflow:hidden;}
  .modal-header{background:#f7fbff; border-bottom:1px solid rgba(15,23,42,.08);}
  .modal-title{font-weight:900; color:#0b2a66;}
  .form-control{border-radius:14px;}
  .btn{border-radius:14px; font-weight:800;}
</style>

<div class="main">
  <div class="content">

    <div class="page-title">
      <div>
        <h2>Branches</h2>
        <p>Hello, <?= htmlspecialchars($admin['username']) ?> — manage branches here</p>
      </div>

      <div class="actions">
        <button type="button" class="btnx primary" data-toggle="modal" data-target="#modalAddBranch">
          ➕ Add Branch
        </button>
      </div>
    </div>

    <div class="card">
      <div class="head">
        <h3>Branches List</h3>
        <div class="tools">
          <input type="text" id="searchGlobal" class="inp" placeholder="Search any field…">
          <input type="text" id="searchCompany" class="inp" placeholder="Search by company…">
        </div>
      </div>

      <div class="body">
        <div class="tablewrap">
          <table id="branchesTable" class="table table-striped table-hover" style="width:100%">
            <thead>
              <tr>
                <th>S/N</th>
                <th>Company</th>
                <th>State</th>
                <th>LGA</th>
                <th>Status</th>
                <th style="width:220px">Action</th>
              </tr>
            </thead>
            <tbody>
              <?php if (!empty($branches)): ?>
                <?php $sn=1; foreach($branches as $b): ?>
                  <?php
                    $st = (string)($b['status'] ?? '0');
                    if ($st === '1') $badge = "<span class='badge b-ok'>Active</span>";
                    elseif ($st === '2') $badge = "<span class='badge b-bad'>Banned</span>";
                    else $badge = "<span class='badge b-warn'>Inactive</span>";
                  ?>
                  <tr>
                    <td><?= $sn++ ?></td>
                    <td><?= htmlspecialchars($b['company_name'] ?? '') ?></td>
                    <td><?= htmlspecialchars($b['state'] ?? '') ?></td>
                    <td><?= htmlspecialchars($b['lga'] ?? '') ?></td>
                    <td><?= $badge ?></td>
                    <td>
                      <button class="btn btn-sm btn-info" type="button"
                              onclick="openBranchModal(<?= (int)$b['id'] ?>)">Edit</button>

                      <?php if ($st !== '2'): ?>
                        <button class="btn btn-sm btn-warning" type="button"
                                onclick="banBranch(<?= (int)$b['id'] ?>)">Ban</button>
                      <?php endif; ?>

                      <?php if ($st !== '1'): ?>
                        <button class="btn btn-sm btn-success" type="button"
                                onclick="activateBranch(<?= (int)$b['id'] ?>)">Activate</button>
                      <?php endif; ?>

                      <button class="btn btn-sm btn-danger" type="button"
                              onclick="deleteBranch(<?= (int)$b['id'] ?>)">Delete</button>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php else: ?>
                <tr><td colspan="6" class="text-center font-weight-bold">No branches yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>


<!-- ===================== ADD BRANCH MODAL ===================== -->
<div class="modal fade" id="modalAddBranch" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <form id="formAddBranch" onsubmit="return false;">
        <div class="modal-header">
          <h3 class="modal-title">Add Branch</h3>
          <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
        </div>

        <div class="modal-body">
          <div class="form-group">
            <label>Company Name</label>
            <input type="text" class="form-control" id="company_name" required>
          </div>

          <div class="form-group">
            <label>State</label>
            <input type="text" class="form-control" id="state" required>
          </div>

          <div class="form-group">
            <label>LGA</label>
            <input type="text" class="form-control" id="lga" required>
          </div>

          <div class="form-group">
            <label>Status</label>
            <select class="form-control" id="status">
              <option value="1" selected>Active</option>
              <option value="0">Inactive</option>
              <option value="2">Banned</option>
            </select>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary" id="btnSubmitAdd">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- ===================== EDIT BRANCH MODAL ===================== -->
<div class="modal fade" id="modalEditBranch" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <form id="formEditBranch" onsubmit="return false;">
        <div class="modal-header">
          <h3 class="modal-title">Edit Branch</h3>
          <button type="button" class="close" data-dismiss="modal"><span>×</span></button>
        </div>

        <div class="modal-body">
          <input type="hidden" id="eb_id">

          <div class="form-group">
            <label>Company Name</label>
            <input type="text" class="form-control" id="eb_company" required>
          </div>

          <div class="form-group">
            <label>State</label>
            <input type="text" class="form-control" id="eb_state" required>
          </div>

          <div class="form-group">
            <label>LGA</label>
            <input type="text" class="form-control" id="eb_lga" required>
          </div>

          <div class="form-group">
            <label>Status</label>
            <select class="form-control" id="eb_status">
              <option value="1">Active</option>
              <option value="0">Inactive</option>
              <option value="2">Banned</option>
            </select>
          </div>
        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- JS libs -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/v/bs4/dt-1.13.8/datatables.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay@2.1.7/dist/loadingoverlay.min.js"></script>

<script>
function showLoad(on){ try{ on ? $.LoadingOverlay("show") : $.LoadingOverlay("hide"); }catch(e){} }
function okResp(res){ return !!res && (res.success === true || String(res.status) === '200'); }

function postAction(action, data, cb){
  data = data || {};
  data.action = action;
  $.ajax({
    type:'POST',
    url:'../assets/branches_action.php',
    data:data,
    dataType:'json',
    beforeSend: ()=>showLoad(true),
    complete: ()=>showLoad(false),
    success: (res)=>cb && cb(res),
    error: (xhr)=>{ console.error(xhr.responseText); swal("Error","Server error.","error"); }
  });
}

$(function(){
  let dt = $('#branchesTable').DataTable({ pageLength: 25 });
  $('#searchGlobal').on('keyup change', function(){ dt.search(this.value).draw(); });
  $('#searchCompany').on('keyup change', function(){ dt.column(1).search(this.value).draw(); });
});

/* ADD */
$('#btnSubmitAdd').on('click', ()=> $('#formAddBranch').trigger('submit'));
$('#formAddBranch').on('submit', function(e){
  e.preventDefault();

  let data = {
    company_name: $('#company_name').val().trim(),
    state: $('#state').val().trim(),
    lga: $('#lga').val().trim(),
    status: $('#status').val()
  };

  if(!data.company_name || !data.state || !data.lga){
    return swal("Incomplete","Please fill all required fields.","error");
  }

  swal({
    title: "Dear <?= htmlspecialchars($admin['username']) ?>",
    text: "Add this branch?",
    icon: "warning",
    buttons: true,
    dangerMode: true
  }).then(function(ok){
    if(!ok) return;
    postAction('create', data, function(res){
      if(okResp(res)){
        swal("Created", "Branch added successfully.", "success").then(()=>location.reload());
      }else{
        swal("Error", res.message || "Failed.", "error");
      }
    });
  });
});

/* OPEN EDIT */
window.openBranchModal = function(id){
  postAction('get', { id:id }, function(res){
    if(!okResp(res) || !res.data) return swal("Error", res.message || "Not found", "error");
    let b = res.data;
    $('#eb_id').val(b.id);
    $('#eb_company').val(b.company_name || '');
    $('#eb_state').val(b.state || '');
    $('#eb_lga').val(b.lga || '');
    $('#eb_status').val(String(b.status));
    $('#modalEditBranch').modal('show');
  });
};

/* SAVE EDIT */
$('#formEditBranch').on('submit', function(e){
  e.preventDefault();

  let data = {
    id: $('#eb_id').val(),
    company_name: $('#eb_company').val().trim(),
    state: $('#eb_state').val().trim(),
    lga: $('#eb_lga').val().trim(),
    status: $('#eb_status').val()
  };

  if(!data.id || !data.company_name || !data.state || !data.lga){
    return swal("Incomplete","Please fill all required fields.","error");
  }

  postAction('update', data, function(res){
    if(okResp(res)){
      swal("Saved","Branch updated.","success").then(()=>location.reload());
    }else{
      swal("Error", res.message || "Update failed.", "error");
    }
  });
});

/* ACTIONS */
function askAction(action, id, label){
  swal({
    title: "Dear <?= htmlspecialchars($admin['username']) ?>",
    text: "Are you sure you want to " + label + " this branch?",
    icon: "warning",
    buttons: true,
    dangerMode: true
  }).then(function(ok){
    if(!ok) return;
    postAction(action, { id:id }, function(res){
      if(okResp(res)){
        swal("Done","Action completed.","success").then(()=>location.reload());
      }else{
        swal("Error", res.message || "Action failed.", "error");
      }
    });
  });
}

window.banBranch      = (id)=> askAction('ban', id, 'ban');
window.activateBranch = (id)=> askAction('activate', id, 'activate');
window.deleteBranch   = (id)=> askAction('delete', id, 'delete');
</script>
