<?php
session_start();
include 'db.php';

/* ================= ADD ================= */
if (isset($_POST['action']) && $_POST['action'] == 'add') {

    $name   = mysqli_real_escape_string($con, $_POST['product_name']);
    $hsn    = mysqli_real_escape_string($con, $_POST['hsn']);
    $weight = mysqli_real_escape_string($con, $_POST['weight']);

    mysqli_query($con, "INSERT INTO products (product_name, hsn, weight)
                        VALUES ('$name','$hsn','$weight')");

    $_SESSION['message'] = "Product Added Successfully";
    header("Location: products.php");
    exit;
}

/* ================= UPDATE ================= */
if (isset($_POST['action']) && $_POST['action'] == 'edit') {

    $id     = intval($_POST['id']);
    $name   = mysqli_real_escape_string($con, $_POST['product_name']);
    $hsn    = mysqli_real_escape_string($con, $_POST['hsn']);
    $weight = mysqli_real_escape_string($con, $_POST['weight']);

    mysqli_query($con, "UPDATE products
                        SET product_name='$name',
                            hsn='$hsn',
                            weight='$weight'
                        WHERE id=$id");

    $_SESSION['message'] = "Product Updated Successfully";
    header("Location: products.php");
    exit;
}

/* ================= DELETE ================= */
if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);
    mysqli_query($con, "DELETE FROM products WHERE id=$id");

    $_SESSION['message'] = "Product Deleted Successfully";
    header("Location: products.php");
    exit;
}

/* ================= FETCH PRODUCTS ================= */
$products = [];
$res = mysqli_query($con, "SELECT * FROM products ORDER BY id DESC");
while ($row = mysqli_fetch_assoc($res)) {
    $products[] = $row;
}

/* ================= EDIT DATA ================= */
$editData = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $r = mysqli_query($con, "SELECT * FROM products WHERE id=$id");
    $editData = mysqli_fetch_assoc($r);
}
?>
<?php 
$title = "Products";
include 'include/header.php';?>

<div id="page-wrapper">
<div id="page-inner">
<div class="row g-4">

<!-- ================= FORM ================= -->
<div class="col-md-8">


<?php if (!empty($_SESSION['message'])): ?>
<div id="customAlert" class="custom-alert">
    <?= $_SESSION['message']; unset($_SESSION['message']); ?>
    <span class="close-btn" onclick="closeAlert()">×</span>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <?= $editData ? 'Edit Product' : 'Add Product' ?>
    </div>

    <div class="card-body">
        <form method="post" id="productsForm">
            <input type="hidden" name="id" value="<?= $editData['id'] ?? '' ?>">
            <input type="hidden" name="action"
                   value="<?= $editData ? 'edit' : 'add' ?>">

            <div class="mb-3">
                <input type="text" name="product_name" class="form-control"
                       placeholder="Product Name"
                       value="<?= $editData['product_name'] ?? '' ?>" required>
            </div>

            <div class="mb-3">
                <input type="text" name="hsn" class="form-control"
                       placeholder="HUID"
                       value="<?= $editData['hsn'] ?? '' ?>" required>
            </div>
            <div class="mb-3">
                <input type="text" name="weight" class="form-control"
                    placeholder="Weight"
                    value="<?= $editData['weight'] ?? '' ?>" required>
            </div>
            <button class="btn btn-primary w-100">
                <?= $editData ? 'Update Product' : 'Add Product' ?>
            </button>
        </form>
    </div>
</div>
</div>

<!-- ================= LIST ================= -->
<div class="col-md-4">
<div class="card">
    <div class="card-header">Product List</div>
    <div class="card-body">
        <table class="table table-bordered table-striped">
            <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Product</th>
                <th>HSN</th>
                <th>Weight</th>
                <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($products as $i => $p): ?>
            <tr>
                <td><?= $i+1 ?></td>
                <td><?= $p['product_name'] ?></td>
                <td><?= $p['hsn'] ?></td>
                <td><?= $p['weight'] ?></td>
                <td>
                    <a href="?edit=<?= $p['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                    <a href="?delete=<?= $p['id'] ?>"
                       onclick="return confirm('Delete this product?')"
                       class="btn btn-sm btn-danger">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</div>

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

<!-- ================= ENTER KEY JS ================= -->
<script>
$('#productsForm').on('keydown', 'input', function (e) {
    if (e.key === 'Enter') {
        e.preventDefault();

        let inputs = $('#productsForm input:visible');
        let index = inputs.index(this);

        if (index + 1 < inputs.length) {
            inputs.eq(index + 1).focus();
        } else {
            $('#productsForm')[0].submit(); // last input
        }
    }
});
</script>

<?php include 'include/footer.php'; ?>
