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

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

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

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

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

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

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

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

    if ($_POST['password'] !== $DELETE_PASSWORD) {
        header("Location: hps_products.php?err=pass");
        exit;
    }

    $id = (int)$_POST['delete_id'];

    // Prevent delete if product used
    $used = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT COUNT(*) c FROM hps_sale_items WHERE product_id=$id
    "))['c'];

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

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

/* -----------------------------
   FETCH PRODUCTS
------------------------------*/
$res = mysqli_query($conn,"
    SELECT * FROM hps_products
    ORDER BY id DESC
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Products</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}

/* 3D CARD */
.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);
}

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

/* Zebra rows */
#productTable tbody tr:nth-child(odd){
    background:#f8fbff;
}
#productTable tbody tr:nth-child(even){
    background:#ffffff;
}

/* Hover */
#productTable tbody tr:hover{
    background:#eaf5ea;
    cursor:pointer;
}

/* Buttons */
.btn-success{background:#198754}
</style>
</head>
<body>

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

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

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

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

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

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

<div class="col-md-3">
<label class="small">Price</label>
<input name="price" type="number" step="0.01"
class="form-control form-control-sm" required>
</div>

<div class="col-md-3">
<label class="small">Reorder Level</label>
<input name="reorder_level" type="number"
value="5"
class="form-control form-control-sm" required>
</div>

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

</div>
</div>

<!-- LIVE SEARCH -->
<input id="searchBox"
class="form-control form-control-sm mb-2"
placeholder="Live search product...">

<!-- TABLE -->
<table class="table table-bordered table-sm" id="productTable">
<thead class="table-dark">
<tr>
<th>#</th>
<th>Name</th>
<th class="text-end">Price</th>
<th class="text-center">Reorder</th>
<th width="140">Action</th>
</tr>
</thead>
<tbody>

<?php $i=1; while($r=mysqli_fetch_assoc($res)): ?>
<tr>
<td><?=$i++?></td>
<td><?=esc($r['name'])?></td>
<td class="text-end"><?=number_format($r['price'],2)?></td>
<td class="text-center"><?=$r['reorder_level']?></td>
<td>

<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-price="<?=$r['price']?>"
data-reorder="<?=$r['reorder_level']?>">
Edit
</button>

<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; ?>

<?php if(mysqli_num_rows($res)==0): ?>
<tr>
<td colspan="5" class="text-center text-muted">No products found</td>
</tr>
<?php endif; ?>

</tbody>
</table>

</div>
</div>

<!-- EDIT MODAL -->
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">

<form method="post">
<div class="modal-header">
<h5>Edit Product</h5>
<button class="btn-close" data-bs-dismiss="modal"></button>
</div>

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

<label class="small">Product Name</label>
<input name="name" id="edit_name" class="form-control form-control-sm mb-2" required>

<label class="small">Price</label>
<input name="price" id="edit_price" type="number" step="0.01"
class="form-control form-control-sm mb-2" required>

<label class="small">Reorder Level</label>
<input name="reorder_level" id="edit_reorder" type="number"
class="form-control form-control-sm" required>
</div>

<div class="modal-footer">
<button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
<button name="save_product" class="btn btn-primary btn-sm">Update</button>
</div>
</form>

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

<!-- DELETE MODAL -->
<div class="modal fade" id="deleteModal">
<div class="modal-dialog">
<div class="modal-content">

<form method="post">
<div class="modal-header">
<h5 class="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="delete_id">
<input type="password" name="password"
class="form-control"
placeholder="Enter password" required>
</div>

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

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

<script>
// EDIT MODAL
editModal.addEventListener('show.bs.modal',e=>{
let b=e.relatedTarget;
edit_id.value=b.dataset.id;
edit_name.value=b.dataset.name;
edit_price.value=b.dataset.price;
edit_reorder.value=b.dataset.reorder;
});

// DELETE MODAL
deleteModal.addEventListener('show.bs.modal',e=>{
delete_id.value=e.relatedTarget.dataset.id;
});

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

</body>
</html>
