<?php
// hps_expense_add.php
require "db.php";

$DELETE_PASSWORD = "1234";

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

/* =========================
   ADD EXPENSE
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_expense'])) {

    $head_id     = (int)($_POST['head_id'] ?? 0);
    $sub_head_id = (int)($_POST['sub_head_id'] ?? 0);
    $amount      = (float)($_POST['amount'] ?? 0);
    $mode        = mysqli_real_escape_string($conn, $_POST['mode'] ?? 'Cash');
    $details     = mysqli_real_escape_string($conn, $_POST['details'] ?? '');

    if ($head_id>0 && $sub_head_id>0 && $amount>0) {

        /* ===== INSERT EXPENSE (UNCHANGED) ===== */
        mysqli_query($conn,"
            INSERT INTO hps_expenses
            (head_id, sub_head_id, amount, pay_mode, details, exp_date)
            VALUES
            ($head_id, $sub_head_id, $amount, '$mode', '$details', CURDATE())
        ");

        /* =====================================================
           PETTY CASH INTEGRATION (EXPENSE – CASH ONLY)
           -----------------------------------------------------
           Description: Main Head (Sub Head)
        ====================================================== */
        if ($mode === 'Cash') {

            /* get petty cash (staff) account */
            $staffAcc = mysqli_fetch_assoc(mysqli_query($conn,"
                SELECT id
                FROM hps_cash_accounts
                WHERE account_type='STAFF'
                ORDER BY id
                LIMIT 1
            "));

            if ($staffAcc) {
                $staff_id = (int)$staffAcc['id'];

                /* get head & sub-head names */
                $h = mysqli_fetch_assoc(mysqli_query($conn,"
                    SELECT h.name head_name, s.name sub_name
                    FROM hps_expense_heads h
                    JOIN hps_expense_sub_heads s ON s.id = $sub_head_id
                    WHERE h.id = $head_id
                    LIMIT 1
                "));

                $desc = 'EXPENSE';
                if ($h) {
                    $desc = mysqli_real_escape_string(
                        $conn,
                        $h['head_name'].' ('.$h['sub_name'].')'
                    );
                }

                mysqli_query($conn,"
                    INSERT INTO hps_cashbook
                    (trans_date, description, from_account, to_account, amount, ref_type)
                    VALUES
                    (
                        CURDATE(),
                        '$desc',
                        $staff_id,
                        NULL,
                        $amount,
                        'PETTY_EXPENSE'
                    )
                ");
            }
        }
        /* ================= END PETTY CASH =================== */
    }

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

/* =========================
   UPDATE / DELETE / UI
   (100% UNCHANGED)
========================= */


/* =========================
   UPDATE EXPENSE
   (UNCHANGED – as requested)
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_expense'])) {

    $id          = (int)($_POST['id'] ?? 0);
    $head_id     = (int)($_POST['head_id'] ?? 0);
    $sub_head_id = (int)($_POST['sub_head_id'] ?? 0);
    $amount      = (float)($_POST['amount'] ?? 0);
    $mode        = mysqli_real_escape_string($conn, $_POST['mode'] ?? 'Cash');
    $details     = mysqli_real_escape_string($conn, $_POST['details'] ?? '');

    if ($id>0 && $head_id>0 && $sub_head_id>0 && $amount>0) {
        mysqli_query($conn,"
            UPDATE hps_expenses SET
                head_id=$head_id,
                sub_head_id=$sub_head_id,
                amount=$amount,
                pay_mode='$mode',
                details='$details'
            WHERE id=$id
        ");
    }

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

/* =========================
   DELETE EXPENSE (UNCHANGED)
========================= */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_expense'])) {

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

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

    if ($id>0) {
        mysqli_query($conn,"DELETE FROM hps_expenses WHERE id=$id");
    }

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

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

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

<!-- ===== UI / JS / HTML BELOW IS 100% UNCHANGED ===== -->
<!-- (intentionally not repeated here for brevity in explanation;
     your pasted version already includes it and remains the same) -->
<style>
body{background:#f1f3f5}

/* 3D card */
.main-card{
    background: rgba(200,200,200,.70);
    border-radius: 30px;
    padding: 22px;
    margin: 28px auto;
    max-width: 1200px;
    box-shadow: 0 10px 25px rgba(0,0,0,.08), 0 2px 6px rgba(0,0,0,.06);
}

/* inputs */
.form-control,.form-select{
    border:1.5px solid #6c757d;
}
.form-control:focus,.form-select:focus{
    border-color:#198754;
    box-shadow:0 0 0 .15rem rgba(25,135,84,.25);
}

/* zebra + hover */
#expTable tbody tr:nth-child(odd){ background:#f4f7fb; }
#expTable tbody tr:nth-child(even){ background:#ffffff; }
#expTable tbody tr:hover{
    background:#eaf5ea !important;
    cursor:pointer;
    transition:.12s;
}
</style>
</head>
<body>

<div class="main-card">

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

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

<!-- FORM (single row aligned) -->
<form method="post" class="card p-3 mb-3">
<div class="row g-2 align-items-end">

  <div class="col-md-3">
    <label class="small">Main Head</label>
    <select name="head_id" id="head" class="form-select form-select-sm" required>
      <option value="">Select</option>
      <?php while($h=mysqli_fetch_assoc($heads)): ?>
        <option value="<?=$h['id']?>"><?=esc($h['name'])?></option>
      <?php endwhile; ?>
    </select>
  </div>

  <div class="col-md-3">
    <label class="small">Sub Head</label>
    <select name="sub_head_id" id="sub" class="form-select form-select-sm" required>
      <option value="">Select</option>
    </select>
  </div>

  <div class="col-md-2">
    <label class="small">Amount</label>
    <input name="amount" type="number" step="0.01" class="form-control form-control-sm" required>
  </div>

  <div class="col-md-2">
    <label class="small">Payment Mode</label>
    <select name="mode" class="form-select form-select-sm">
      <option>Cash</option>
      <option>Bank</option>
      <option>Online</option>
    </select>
  </div>

  <div class="col-md-2">
    <button name="add_expense" class="btn btn-success btn-sm w-100">
      <i class="bi bi-plus-circle"></i> Save
    </button>
  </div>

  <div class="col-md-12">
    <label class="small">Details</label>
    <input name="details" class="form-control form-control-sm" placeholder="Optional details...">
  </div>

</div>
</form>

<!-- LIVE SEARCH -->
<div class="row g-2 mb-2">
  <div class="col-md-4">
    <input id="searchBox" class="form-control form-control-sm" placeholder="Live search expense...">
  </div>
</div>

<!-- EXPENSE LIST -->
<table class="table table-bordered table-sm" id="expTable">
<thead class="table-dark">
<tr>
  <th width="60">#</th>
  <th>Main Head</th>
  <th>Sub Head</th>
  <th width="120" class="text-end">Amount</th>
  <th width="110">Mode</th>
  <th>Details</th>
  <th width="110">Action</th>
</tr>
</thead>
<tbody>
<?php $i=1; while($r=mysqli_fetch_assoc($res)): ?>
<tr>
  <td><?=$i++?></td>
  <td><?=esc($r['head_name'])?></td>
  <td><?=esc($r['sub_name'])?></td>
  <td class="text-end"><?=number_format((float)$r['amount'],2)?></td>
  <td><?=esc($r['pay_mode'])?></td>
  <td><?=esc($r['details'])?></td>
  <td class="text-center">

    <!-- EDIT ICON -->
    <button class="btn btn-sm btn-success"
      data-bs-toggle="modal"
      data-bs-target="#editModal"
      data-id="<?=$r['id']?>"
      data-head="<?=$r['head_id']?>"
      data-sub="<?=$r['sub_head_id']?>"
      data-amount="<?=$r['amount']?>"
      data-mode="<?=esc($r['pay_mode'])?>"
      data-details="<?=esc($r['details'])?>">
      <i class="bi bi-pencil"></i>
    </button>

    <!-- DELETE ICON -->
    <button class="btn btn-sm btn-danger"
      data-bs-toggle="modal"
      data-bs-target="#deleteModal"
      data-id="<?=$r['id']?>">
      <i class="bi bi-trash"></i>
    </button>

  </td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

<!-- ================= EDIT MODAL (NOW INCLUDED ✅) ================= -->
<div class="modal fade" id="editModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form method="post">

<div class="modal-header">
  <h5 class="modal-title">Edit Expense</h5>
  <button class="btn-close" data-bs-dismiss="modal"></button>
</div>

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

<div class="row g-2 align-items-end">

  <div class="col-md-3">
    <label class="small">Main Head</label>
    <select name="head_id" id="e_head" class="form-select form-select-sm" required>
      <?php
      $h3 = mysqli_query($conn,"SELECT * FROM hps_expense_heads ORDER BY name");
      while($h=mysqli_fetch_assoc($h3)):
      ?>
        <option value="<?=$h['id']?>"><?=esc($h['name'])?></option>
      <?php endwhile; ?>
    </select>
  </div>

  <div class="col-md-3">
    <label class="small">Sub Head</label>
    <select name="sub_head_id" id="e_sub" class="form-select form-select-sm" required></select>
  </div>

  <div class="col-md-2">
    <label class="small">Amount</label>
    <input name="amount" id="e_amount" type="number" step="0.01" class="form-control form-control-sm" required>
  </div>

  <div class="col-md-2">
    <label class="small">Mode</label>
    <select name="mode" id="e_mode" class="form-select form-select-sm">
      <option>Cash</option>
      <option>Bank</option>
      <option>Online</option>
    </select>
  </div>

  <div class="col-md-12">
    <label class="small">Details</label>
    <input name="details" id="e_details" class="form-control form-control-sm">
  </div>

</div>
</div>

<div class="modal-footer">
  <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
  <button name="update_expense" class="btn btn-success btn-sm">Update</button>
</div>

</form>
</div>
</div>
</div>

<!-- ================= DELETE MODAL ================= -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="post">

<div class="modal-header">
  <h5 class="modal-title text-danger">Confirm Delete</h5>
  <button class="btn-close" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">
  <input type="hidden" name="delete_id" id="d_id">
  <label class="small mb-1">Enter delete password</label>
  <input type="password" name="password" class="form-control" required>
</div>

<div class="modal-footer">
  <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
  <button name="delete_expense" class="btn btn-danger btn-sm">Delete</button>
</div>

</form>
</div>
</div>
</div>

<script>
// load subheads for add form
document.getElementById('head').addEventListener('change', function(){
  fetch('hps_get_subheads.php?head_id='+this.value)
    .then(r=>r.text())
    .then(d=>{ document.getElementById('sub').innerHTML = d; });
});

// edit modal: fill fields + load subheads with selected
document.getElementById('editModal').addEventListener('show.bs.modal', function(e){
  let b = e.relatedTarget;

  e_id.value      = b.dataset.id;
  e_head.value    = b.dataset.head;
  e_amount.value  = b.dataset.amount;
  e_mode.value    = b.dataset.mode;
  e_details.value = b.dataset.details;

  fetch('hps_get_subheads.php?head_id='+b.dataset.head+'&selected='+b.dataset.sub)
    .then(r=>r.text())
    .then(d=>{ e_sub.innerHTML = d; });
});

// if user changes head in edit modal -> reload subs
document.getElementById('e_head').addEventListener('change', function(){
  fetch('hps_get_subheads.php?head_id='+this.value)
    .then(r=>r.text())
    .then(d=>{ e_sub.innerHTML = d; });
});

// delete modal set id
document.getElementById('deleteModal').addEventListener('show.bs.modal', function(e){
  d_id.value = e.relatedTarget.dataset.id;
});

// live search in table
document.getElementById('searchBox').addEventListener('keyup', function(){
  let v = this.value.toLowerCase();
  document.querySelectorAll('#expTable tbody tr').forEach(tr=>{
    tr.style.display = tr.innerText.toLowerCase().includes(v) ? '' : 'none';
  });
});
</script>

</body>
</html>
