<?php
require "db.php";

/* =========================
   CONFIG
========================= */
$DELETE_PASSWORD = "1234";

function esc($v){
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

/* =========================
   ADD / UPDATE MAIN HEAD
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_head'])) {

    $id   = (int)($_POST['id'] ?? 0);
    $name = mysqli_real_escape_string($conn, $_POST['name'] ?? '');

    if ($id > 0) {
        mysqli_query($conn,"UPDATE hps_expense_heads SET name='$name' WHERE id=$id");
    } else {
        mysqli_query($conn,"INSERT INTO hps_expense_heads(name) VALUES('$name')");
    }

    header("Location: hps_expense_heads.php");
    exit;
}

/* =========================
   DELETE MAIN HEAD (PASSWORD)
   - block delete if has subheads
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_head'])) {

    $pass = $_POST['password'] ?? '';
    $id   = (int)($_POST['delete_id'] ?? 0);

    if ($pass !== $DELETE_PASSWORD) {
        header("Location: hps_expense_heads.php?err=pass");
        exit;
    }

    $cnt = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT COUNT(*) c FROM hps_expense_sub_heads WHERE head_id=$id
    "))['c'] ?? 0;

    if ((int)$cnt === 0) {
        mysqli_query($conn,"DELETE FROM hps_expense_heads WHERE id=$id");
    } else {
        header("Location: hps_expense_heads.php?err=has_sub");
        exit;
    }

    header("Location: hps_expense_heads.php");
    exit;
}

/* =========================
   ADD / UPDATE SUB HEAD
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_sub'])) {

    $id      = (int)($_POST['id'] ?? 0);
    $head_id = (int)($_POST['head_id'] ?? 0);
    $name    = mysqli_real_escape_string($conn, $_POST['name'] ?? '');

    if ($id > 0) {
        mysqli_query($conn,"
            UPDATE hps_expense_sub_heads
            SET head_id=$head_id, name='$name'
            WHERE id=$id
        ");
    } else {
        mysqli_query($conn,"
            INSERT INTO hps_expense_sub_heads(head_id,name)
            VALUES($head_id,'$name')
        ");
    }

    header("Location: hps_expense_heads.php");
    exit;
}

/* =========================
   DELETE SUB HEAD (PASSWORD)
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_sub'])) {

    $pass = $_POST['password'] ?? '';
    $id   = (int)($_POST['delete_id'] ?? 0);

    if ($pass !== $DELETE_PASSWORD) {
        header("Location: hps_expense_heads.php?err=pass");
        exit;
    }

    mysqli_query($conn,"DELETE FROM hps_expense_sub_heads WHERE id=$id");

    header("Location: hps_expense_heads.php");
    exit;
}

/* =========================
   FETCH DATA
========================= */
$heads = mysqli_query($conn,"SELECT * FROM hps_expense_heads ORDER BY name");
$heads_for_select = mysqli_query($conn,"SELECT * FROM hps_expense_heads ORDER BY name");

$subs = mysqli_query($conn,"
    SELECT s.*, h.name AS head_name
    FROM hps_expense_sub_heads s
    JOIN hps_expense_heads h ON h.id = s.head_id
    ORDER BY h.name, s.name
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Expense Heads</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<style>
body{background:#f1f3f5}
.main-card{
    max-width:1100px;
    margin:30px auto;
    padding:22px;
    background:#e0e0e0;
    border-radius:22px;
    box-shadow:0 10px 25px rgba(0,0,0,.08);
}
tbody tr:hover{background:#eaf5ea}
.search-box{max-width:420px}
</style>
</head>
<body>

<div class="container-fluid">
<div class="main-card">

<h4 class="mb-3">Expense Heads</h4>

<?php if(isset($_GET['err']) && $_GET['err']=='pass'): ?>
<div class="alert alert-danger py-2">❌ Wrong delete password</div>
<?php endif; ?>

<?php if(isset($_GET['err']) && $_GET['err']=='has_sub'): ?>
<div class="alert alert-warning py-2">⚠ Cannot delete this Main Head because it has Sub Heads.</div>
<?php endif; ?>

<div class="row g-3">

  <!-- ADD MAIN HEAD -->
  <div class="col-md-4">
    <form method="post" class="card p-3">
      <h6 class="mb-2">Add Main Head</h6>
      <input name="name" class="form-control mb-2" placeholder="Head name" required>
      <button name="save_head" class="btn btn-primary btn-sm">Add</button>
    </form>
  </div>

  <!-- ADD SUB HEAD -->
  <div class="col-md-8">
    <form method="post" class="card p-3">
      <h6 class="mb-2">Add Sub Head</h6>
      <select name="head_id" class="form-select mb-2" required>
        <option value="">Select Main Head</option>
        <?php while($h=mysqli_fetch_assoc($heads_for_select)): ?>
          <option value="<?=$h['id']?>"><?=esc($h['name'])?></option>
        <?php endwhile; ?>
      </select>
      <input name="name" class="form-control mb-2" placeholder="Sub head name" required>
      <button name="save_sub" class="btn btn-success btn-sm">Add</button>
    </form>
  </div>

</div>

<hr class="my-3">

<!-- LIVE SEARCH -->
<input id="searchBox" class="form-control form-control-sm mb-2 search-box"
placeholder="Live search main head or sub head...">

<!-- MAIN HEADS -->
<div class="card mb-3">
  <div class="card-header fw-bold">Main Heads</div>
  <div class="card-body p-0">
    <table class="table table-sm table-bordered mb-0" id="headTable">
      <thead class="table-dark">
        <tr>
          <th width="60">#</th>
          <th>Main Head</th>
          <th width="150">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php
      $hres = mysqli_query($conn,"SELECT * FROM hps_expense_heads ORDER BY name");
      $i=1; while($h=mysqli_fetch_assoc($hres)):
      ?>
        <tr>
          <td><?=$i++?></td>
          <td><?=esc($h['name'])?></td>
          <td>
            <button class="btn btn-sm btn-success"
              data-bs-toggle="modal"
              data-bs-target="#editHeadModal"
              data-id="<?=$h['id']?>"
              data-name="<?=esc($h['name'])?>">Edit</button>

            <button class="btn btn-sm btn-danger"
              data-bs-toggle="modal"
              data-bs-target="#deleteHeadModal"
              data-id="<?=$h['id']?>"
              data-name="<?=esc($h['name'])?>">Delete</button>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- SUB HEADS -->
<div class="card">
  <div class="card-header fw-bold">Sub Heads</div>
  <div class="card-body p-0">
    <table class="table table-sm table-bordered mb-0" id="subTable">
      <thead class="table-dark">
        <tr>
          <th width="60">#</th>
          <th>Main Head</th>
          <th>Sub Head</th>
          <th width="150">Action</th>
        </tr>
      </thead>
      <tbody>
      <?php $j=1; while($s=mysqli_fetch_assoc($subs)): ?>
        <tr>
          <td><?=$j++?></td>
          <td><?=esc($s['head_name'])?></td>
          <td><?=esc($s['name'])?></td>
          <td>
            <button class="btn btn-sm btn-success"
              data-bs-toggle="modal"
              data-bs-target="#editSubModal"
              data-id="<?=$s['id']?>"
              data-name="<?=esc($s['name'])?>"
              data-head="<?=$s['head_id']?>">Edit</button>

            <button class="btn btn-sm btn-danger"
              data-bs-toggle="modal"
              data-bs-target="#deleteSubModal"
              data-id="<?=$s['id']?>"
              data-name="<?=esc($s['name'])?>">Delete</button>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

</div>
</div>

<!-- ================= EDIT HEAD MODAL ================= -->
<div class="modal fade" id="editHeadModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Main Head</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="eh_id">
        <label class="small">Head Name</label>
        <input name="name" id="eh_name" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button name="save_head" class="btn btn-primary btn-sm">Update</button>
      </div>
    </form>
  </div>
</div>

<!-- ================= DELETE HEAD MODAL ================= -->
<div class="modal fade" id="deleteHeadModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title text-danger">Delete Main Head</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="delete_id" id="dh_id">
        <div class="mb-2">Enter password to delete: <b id="dh_name"></b></div>
        <input type="password" name="password" class="form-control" required>
        <div class="text-muted small mt-2">Note: Main head cannot be deleted if it has sub-heads.</div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button name="delete_head" class="btn btn-danger btn-sm">Delete</button>
      </div>
    </form>
  </div>
</div>

<!-- ================= EDIT SUB MODAL ================= -->
<div class="modal fade" id="editSubModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Edit Sub Head</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="es_id">

        <label class="small">Main Head</label>
        <select name="head_id" id="es_head" class="form-select mb-2" required>
          <?php
          $heads4 = mysqli_query($conn,"SELECT * FROM hps_expense_heads ORDER BY name");
          while($h=mysqli_fetch_assoc($heads4)):
          ?>
            <option value="<?=$h['id']?>"><?=esc($h['name'])?></option>
          <?php endwhile; ?>
        </select>

        <label class="small">Sub Head Name</label>
        <input name="name" id="es_name" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button name="save_sub" class="btn btn-primary btn-sm">Update</button>
      </div>
    </form>
  </div>
</div>

<!-- ================= DELETE SUB MODAL ================= -->
<div class="modal fade" id="deleteSubModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title text-danger">Delete Sub Head</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="delete_id" id="ds_id">
        <div class="mb-2">Enter password to delete: <b id="ds_name"></b></div>
        <input type="password" name="password" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
        <button name="delete_sub" class="btn btn-danger btn-sm">Delete</button>
      </div>
    </form>
  </div>
</div>

<script>
// LIVE SEARCH (both tables)
document.getElementById('searchBox').addEventListener('keyup', function(){
  let v = this.value.toLowerCase();

  document.querySelectorAll('#headTable tbody tr').forEach(tr=>{
    tr.style.display = tr.innerText.toLowerCase().includes(v) ? '' : 'none';
  });

  document.querySelectorAll('#subTable tbody tr').forEach(tr=>{
    tr.style.display = tr.innerText.toLowerCase().includes(v) ? '' : 'none';
  });
});

// EDIT HEAD
document.getElementById('editHeadModal').addEventListener('show.bs.modal', function(e){
  let b = e.relatedTarget;
  document.getElementById('eh_id').value = b.dataset.id;
  document.getElementById('eh_name').value = b.dataset.name;
});

// DELETE HEAD
document.getElementById('deleteHeadModal').addEventListener('show.bs.modal', function(e){
  let b = e.relatedTarget;
  document.getElementById('dh_id').value = b.dataset.id;
  document.getElementById('dh_name').innerText = b.dataset.name;
});

// EDIT SUB
document.getElementById('editSubModal').addEventListener('show.bs.modal', function(e){
  let b = e.relatedTarget;
  document.getElementById('es_id').value = b.dataset.id;
  document.getElementById('es_name').value = b.dataset.name;
  document.getElementById('es_head').value = b.dataset.head;
});

// DELETE SUB
document.getElementById('deleteSubModal').addEventListener('show.bs.modal', function(e){
  let b = e.relatedTarget;
  document.getElementById('ds_id').value = b.dataset.id;
  document.getElementById('ds_name').innerText = b.dataset.name;
});
</script>

</body>
</html>
