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

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

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

/* -----------------------------
   ADD / UPDATE CUSTOMER
------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_customer'])) {

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

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

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

/* -----------------------------
   DELETE WITH PASSWORD
------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_customer'])) {

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

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

    // Check if customer used in sales
    $chk = mysqli_query($conn,"
        SELECT COUNT(*) AS total
        FROM hps_sales
        WHERE customer_id = $id
    ");

    $row  = mysqli_fetch_assoc($chk);
    $used = (int)($row['total'] ?? 0);

    if ($used > 0) {
        header("Location: hps_customers.php?err=used");
        exit;
    }

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

    header("Location: hps_customers.php?success=deleted");
    exit;
}



/* -----------------------------
   FETCH CUSTOMERS
------------------------------*/
$res = mysqli_query($conn,"
    SELECT * FROM hps_customers
    ORDER BY id DESC
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Customers</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{
    background: rgba(200,200,200,.70);
    border-radius:30px;
    padding:24px;
    margin:30px auto;
    max-width:1200px;
    box-shadow:0 10px 25px rgba(0,0,0,.08),0 2px 6px rgba(0,0,0,.06);
}

#customerTable tbody tr:hover{
    background:#eaf5ea;
    transition:.15s;
}

input.form-control{
    border:1.5px solid #6c757d;
}
input.form-control:focus{
    border-color:#198754;
    box-shadow:0 0 0 .15rem rgba(25,135,84,.25);
}
</style>
</head>
<body>

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

<h4 class="mb-3">Customers</h4>

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

<?php if(isset($_GET['err']) && $_GET['err']=='used'): ?>
<div class="alert alert-warning py-2">
⚠ Customer cannot be deleted. It is used in sales.
</div>
<?php endif; ?>

<?php if(isset($_GET['success']) && $_GET['success']=='deleted'): ?>
<div class="alert alert-success py-2">
✅ Customer deleted successfully.
</div>
<?php endif; ?>



<!-- ADD CUSTOMER -->
<div class="card mb-3">
<div class="card-header fw-bold">Add Customer</div>
<div class="card-body">

<form method="post" class="row g-2">
<input type="hidden" name="id" value="0">

<div class="col-md-4">
<label class="small">Customer Name</label>
<input name="name" class="form-control form-control-sm" required>
</div>

<div class="col-md-3">
<label class="small">Mobile</label>
<input name="mobile" class="form-control form-control-sm" required>
</div>

<div class="col-md-3">
<label class="small">CNIC</label>
<input name="cnic" class="form-control form-control-sm">
</div>

<div class="col-md-10">
<label class="small">Address</label>
<input name="address" class="form-control form-control-sm">
</div>

<div class="col-md-2 d-flex align-items-end">
<button name="save_customer" class="btn btn-primary btn-sm w-100">Add</button>
</div>
</form>

</div>
</div>

<!-- 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 customer...">
</div>
</div>

<!-- TABLE -->
<table class="table table-bordered table-sm" id="customerTable">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Name</th>
<th>Mobile</th>
<th>CNIC</th>
<th>Address</th>
<th width="130">Action</th>
</tr>
</thead>
<tbody>

<?php $i=1; while($r=mysqli_fetch_assoc($res)): ?>
<tr>
<td><?=$i++?></td>
<td><?=esc($r['name'])?></td>
<td><?=esc($r['mobile'])?></td>
<td><?=esc($r['cnic'])?></td>
<td><?=esc($r['address'])?></td>
<td>

<button type="button" class="btn btn-sm btn-success"
data-bs-toggle="modal"
data-bs-target="#editModal"
data-id="<?=$r['id']?>"
data-name="<?=esc($r['name'])?>"
data-mobile="<?=esc($r['mobile'])?>"
data-cnic="<?=esc($r['cnic'])?>"
data-address="<?=esc($r['address'])?>">
Edit
</button>

<button type="button" class="btn btn-sm btn-danger"
data-bs-toggle="modal"
data-bs-target="#deleteModal"
data-id="<?=$r['id']?>">
Delete
</button>

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

</tbody>
</table>

</div>
</div>

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

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

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

<div class="mb-2">
<label class="small">Customer Name</label>
<input name="name" id="e_name" class="form-control form-control-sm" required>
</div>

<div class="mb-2">
<label class="small">Mobile</label>
<input name="mobile" id="e_mobile" class="form-control form-control-sm" required>
</div>

<div class="mb-2">
<label class="small">CNIC</label>
<input name="cnic" id="e_cnic" class="form-control form-control-sm">
</div>

<div class="mb-2">
<label class="small">Address</label>
<input name="address" id="e_address" class="form-control form-control-sm">
</div>
</div>

<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
<button name="save_customer" class="btn btn-primary 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 type="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_customer" class="btn btn-danger btn-sm">Delete</button>
</div>

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

<script>
// LIVE SEARCH (works now)
document.getElementById('searchBox').addEventListener('keyup', function(){
    let v=this.value.toLowerCase();
    document.querySelectorAll('#customerTable tbody tr').forEach(tr=>{
        tr.style.display = tr.innerText.toLowerCase().includes(v) ? '' : 'none';
    });
});

// EDIT MODAL (no errors now)
document.getElementById('editModal').addEventListener('show.bs.modal', function(e){
    let b = e.relatedTarget;
    document.getElementById('e_id').value      = b.dataset.id;
    document.getElementById('e_name').value    = b.dataset.name;
    document.getElementById('e_mobile').value  = b.dataset.mobile;
    document.getElementById('e_cnic').value    = b.dataset.cnic;
    document.getElementById('e_address').value = b.dataset.address;
});

// DELETE MODAL
document.getElementById('deleteModal').addEventListener('show.bs.modal', function(e){
    document.getElementById('d_id').value = e.relatedTarget.dataset.id;
});
</script>

</body>
</html>
