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

$success = "";
$error = "";

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

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

    $stmt = $conn->prepare("DELETE FROM subcategories WHERE id=?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) $success = "Subcategory deleted successfully!";
    else $error = "Failed to delete: " . $stmt->error;
}

/* -------------------------
   ADD SUBCATEGORY
---------------------------*/
if (isset($_POST['add_subcat'])) {
    $cat = $_POST['category_id'];
    $title = $_POST['title'];
    $desc = $_POST['description'];

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

    $stmt = $conn->prepare("INSERT INTO subcategories (category_id, title, image, description) VALUES (?,?,?,?)");
    $stmt->bind_param("isss", $cat, $title, $filename, $desc);

    if ($stmt->execute()) $success = "Subcategory added successfully!";
    else $error = "Failed to add: " . $stmt->error;
}

/* -------------------------
   UPDATE SUBCATEGORY
---------------------------*/
if (isset($_POST['update_subcat'])) {
    $id = intval($_POST['update_id']);
    $cat = $_POST['category_id'];
    $title = $_POST['title'];
    $desc = $_POST['description'];

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

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

        $stmt = $conn->prepare("UPDATE subcategories SET category_id=?, title=?, image=?, description=? WHERE id=?");
        $stmt->bind_param("isssi", $cat, $title, $filename, $desc, $id);
    } else {
        $stmt = $conn->prepare("UPDATE subcategories SET category_id=?, title=?, description=? WHERE id=?");
        $stmt->bind_param("issi", $cat, $title, $desc, $id);
    }

    if ($stmt->execute()) $success = "Subcategory updated successfully!";
    else $error = "Failed to update: " . $stmt->error;
}

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

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

    <h3 class="mb-4 fw-bold">Manage Subcategories</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 FORM -->
    <div class="card mb-4">
        <div class="card-header">Add Subcategory</div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">
                <div class="mb-3">
                    <label>Category</label>
                    <select name="category_id" class="form-control" required>
                        <option value="">Select Category</option>
                        <?php while($c = $cats->fetch_assoc()): ?>
                            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label>Title</label>
                    <input type="text" name="title" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label>Description</label>
                    <textarea name="description" class="form-control" rows="3" required></textarea>
                </div>
                <div class="mb-3">
                    <label>Image</label>
                    <input type="file" name="image" class="form-control" required>
                </div>
                <button type="submit" name="add_subcat" class="btn btn-primary">Add Subcategory</button>
            </form>
        </div>
    </div>

    <!-- TABLE -->
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>#</th>
                <th>Image</th>
                <th>Title</th>
                <th>Category</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php $i=1; while($row = $subcats->fetch_assoc()): ?>
            <tr>
                <td><?= $i++ ?></td>
                <td><img src="asset/images/<?= $row['image'] ?>" height="50"></td>
                <td><?= htmlspecialchars($row['title']) ?></td>
                <td><?= htmlspecialchars($row['cat_title']) ?></td>
                <td><?= htmlspecialchars(substr($row['description'],0,50)) ?>...</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 subcategory?')" 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">
                    <div class="modal-content">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="modal-header">
                                <h5>Edit Subcategory #<?= $row['id'] ?></h5>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="update_id" value="<?= $row['id'] ?>">

                                <div class="mb-2">
                                    <label>Category</label>
                                    <select name="category_id" class="form-control" required>
                                        <?php 
                                        $catreset = $conn->query("SELECT * FROM categories ORDER BY title ASC");
                                        while($ct = $catreset->fetch_assoc()):
                                        ?>
                                            <option value="<?= $ct['id'] ?>" <?= $ct['id']==$row['category_id']?"selected":"" ?>>
                                                <?= htmlspecialchars($ct['title']) ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>

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

                                <div class="mb-2">
                                    <label>Description</label>
                                    <textarea name="description" class="form-control" rows="3" required><?= htmlspecialchars($row['description']) ?></textarea>
                                </div>

                                <div class="mb-2">
                                    <label>Image</label>
                                    <input type="file" name="image" class="form-control">
                                    <img src="asset/images/<?= $row['image'] ?>" height="70" class="mt-2">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" name="update_subcat" 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>

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