<?php
include 'auth.php';
include 'db.php';
include 'adminhead.php';
include 'sidebar.php';

$success = '';
$error = '';

/* -------------------------
   DELETE PRODUCT
---------------------------*/
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);

    // Delete image
    $img = $conn->query("SELECT image FROM products WHERE id=$id")->fetch_assoc()['image'];
    if ($img && file_exists("asset/images/" . $img)) {
        unlink("asset/images/" . $img);
    }

    $stmt = $conn->prepare("DELETE FROM products WHERE id=?");
    $stmt->bind_param("i", $id);
    $success = $stmt->execute() ? "Product deleted successfully!" : "Failed to delete product: " . $stmt->error;
}

/* -------------------------
   ADD PRODUCT
---------------------------*/
if (isset($_POST['add_product'])) {
    $subcategory_id = $_POST['subcategory_id'];
    $brand = $_POST['brand'];
    $model_no = $_POST['model_no'];

    $image = "";
    if (!empty($_FILES['image']['name'])) {
        $image = time() . "_" . $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], "asset/images/" . $image);
    }

    $stmt = $conn->prepare("INSERT INTO products (subcategory_id, brand, model_no, image) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isss", $subcategory_id, $brand, $model_no, $image);
    $success = $stmt->execute() ? "Product added successfully!" : "Failed to add product: " . $stmt->error;
}

/* -------------------------
   UPDATE PRODUCT
---------------------------*/
if (isset($_POST['update_product'])) {
    $id = $_POST['id'];
    $subcategory_id = $_POST['subcategory_id'];
    $brand = $_POST['brand'];
    $model_no = $_POST['model_no'];

    $old_image = $_POST['old_image'];
    $new_image = $old_image;

    if (!empty($_FILES['image']['name'])) {
        $new_image = time() . "_" . $_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], "asset/images/" . $new_image);

        if ($old_image && file_exists("asset/images/" . $old_image)) {
            unlink("asset/images/" . $old_image);
        }
    }

    $stmt = $conn->prepare("UPDATE products SET subcategory_id=?, brand=?, model_no=?, image=? WHERE id=?");
    $stmt->bind_param("isssi", $subcategory_id, $brand, $model_no, $new_image, $id);
    $success = $stmt->execute() ? "Product updated successfully!" : "Failed to update product: " . $stmt->error;
}

/* -------------------------
   FETCH SUBCATEGORIES
---------------------------*/
$subcats = $conn->query("
    SELECT subcategories.*, categories.title AS category_title
    FROM subcategories
    JOIN categories ON categories.id=subcategories.category_id
    ORDER BY categories.title ASC, subcategories.title ASC
");

/* -------------------------
   FETCH PRODUCTS
---------------------------*/
$data = $conn->query("
    SELECT products.*, subcategories.title AS subcat_title 
    FROM products 
    JOIN subcategories ON subcategories.id = products.subcategory_id
    ORDER BY products.id DESC
");
?>

<div class="page-wrapper">
    <div class="container-fluid">

        <h3 class="mb-4 fw-bold">Manage Products</h3>

        <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
        <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

        <!-- ADD PRODUCT FORM -->
        <div class="card mb-4">
            <div class="card-header">Add New Product</div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" class="row">

                    <div class="col-md-4 mb-3">
                        <label>Subcategory</label>
                        <select name="subcategory_id" class="form-control" required>
                            <option value="">Select</option>
                            <?php while ($s = $subcats->fetch_assoc()): ?>
                                <option value="<?= $s['id'] ?>"><?= $s['category_title'] ?> → <?= $s['title'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Brand</label>
                        <input type="text" name="brand" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Model No</label>
                        <input type="text" name="model_no" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Image</label>
                        <input type="file" name="image" class="form-control" required>
                    </div>

                    <div class="col-12">
                        <button type="submit" name="add_product" class="btn btn-primary">Add Product</button>
                    </div>

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

        <!-- PRODUCT TABLE -->
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="thead-dark">
                    <tr>
                        <th>#</th>
                        <th>Image</th>
                        <th>Brand</th>
                        <th>Model No</th>
                        <th>Subcategory</th>
                        <th width="160px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i=1; while($row = $data->fetch_assoc()): ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td><img src="asset/images/<?= $row['image'] ?>" width="70" height="70"></td>
                        <td><?= htmlspecialchars($row['brand']) ?></td>
                        <td><?= htmlspecialchars($row['model_no']) ?></td>
                        <td><?= htmlspecialchars($row['subcat_title']) ?></td>
                        <td>
                            <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#edit<?= $row['id'] ?>">Edit</button>
                            <a href="?delete_id=<?= $row['id'] ?>" onclick="return confirm('Delete this product?')" class="btn btn-danger btn-sm">Delete</a>
                        </td>
                    </tr>

                    <!-- EDIT MODAL -->
                    <div class="modal fade" id="edit<?= $row['id'] ?>" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <form method="POST" enctype="multipart/form-data">
                                    <div class="modal-header">
                                        <h5>Edit Product #<?= $row['id'] ?></h5>
                                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    </div>
                                    <div class="modal-body">

                                        <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                        <input type="hidden" name="old_image" value="<?= $row['image'] ?>">

                                        <label>Subcategory</label>
                                        <select name="subcategory_id" class="form-control mb-2" required>
                                            <?php 
                                            $sdata = $conn->query("
                                                SELECT subcategories.*, categories.title AS category_title
                                                FROM subcategories
                                                JOIN categories ON categories.id=subcategories.category_id
                                                ORDER BY categories.title ASC
                                            ");
                                            while ($s = $sdata->fetch_assoc()):
                                            ?>
                                                <option value="<?= $s['id'] ?>" <?= ($s['id']==$row['subcategory_id'])?'selected':'' ?>>
                                                    <?= $s['category_title'] ?> → <?= $s['title'] ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>

                                        <label>Brand</label>
                                        <input type="text" name="brand" class="form-control mb-2" value="<?= htmlspecialchars($row['brand']) ?>" required>

                                        <label>Model No</label>
                                        <input type="text" name="model_no" class="form-control mb-2" value="<?= htmlspecialchars($row['model_no']) ?>" required>

                                        <label>Image</label>
                                        <input type="file" name="image" class="form-control mb-2">
                                        <img src="asset/images/<?= $row['image'] ?>" width="100" class="mt-2">

                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="update_product" class="btn btn-success">Save Changes</button>
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>

<?php include 'adminfoot.php'; ?>
