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

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

$uploadDir = 'assets/images/'; // Make sure this folder exists and is writable

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

    // Get the image filename to delete
    $res = $conn->query("SELECT image FROM brands WHERE id=$id");
    if ($res->num_rows) {
        $row = $res->fetch_assoc();
        if (file_exists($uploadDir . $row['image'])) {
            unlink($uploadDir . $row['image']);
        }
    }

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

/* -------------------------
   ADD BRAND
---------------------------*/
if (isset($_POST['add_brand'])) {
    $title = $_POST['title'];

    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $filename = time() . '_' . basename($_FILES['image']['name']);
        $targetFile = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            $stmt = $conn->prepare("INSERT INTO brands (title, image) VALUES (?, ?)");
            $stmt->bind_param("ss", $title, $filename);
            $success = $stmt->execute() ? "Brand added successfully!" : "Failed to add brand: " . $stmt->error;
        } else {
            $error = "Failed to upload image.";
        }
    } else {
        $error = "Please select an image.";
    }
}

/* -------------------------
   UPDATE BRAND
---------------------------*/
if (isset($_POST['update_brand'])) {
    $id = intval($_POST['id']);
    $title = $_POST['title'];
    $filename = $_POST['old_image']; // Default old image

    // Check if a new image is uploaded
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $filename = time() . '_' . basename($_FILES['image']['name']);
        $targetFile = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
            // Delete old image
            if (file_exists($uploadDir . $_POST['old_image'])) {
                unlink($uploadDir . $_POST['old_image']);
            }
        } else {
            $error = "Failed to upload new image.";
        }
    }

    $stmt = $conn->prepare("UPDATE brands SET title=?, image=? WHERE id=?");
    $stmt->bind_param("ssi", $title, $filename, $id);
    $success = $stmt->execute() ? "Brand updated successfully!" : "Failed to update brand: " . $stmt->error;
}

/* -------------------------
   FETCH ALL BRANDS
---------------------------*/
$data = $conn->query("SELECT * FROM brands ORDER BY id DESC");
?>

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

        <h3 class="mb-4 fw-bold">Manage Brands</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 BRAND FORM -->
        <div class="card mb-4">
            <div class="card-header">Add New Brand</div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label>Brand Title</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Brand Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*" required>
                    </div>
                    <button type="submit" name="add_brand" class="btn btn-primary">Add Brand</button>
                </form>
            </div>
        </div>

        <!-- BRAND TABLE -->
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="thead-dark">
                    <tr>
                        <th>#</th>
                        <th>Title</th>
                        <th>Image</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $i=1; while($row = $data->fetch_assoc()): ?>
                    <tr>
                        <td><?= $i++ ?></td>
                        <td><?= htmlspecialchars($row['title']) ?></td>
                        <td><img src="<?= $uploadDir . $row['image'] ?>" alt="" width="80"></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 brand?')" 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 Brand #<?= $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'] ?>">
                                        <div class="form-group">
                                            <label>Brand Title</label>
                                            <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($row['title']) ?>" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Brand Image</label>
                                            <input type="file" name="image" class="form-control" accept="image/*">
                                            <img src="<?= $uploadDir . $row['image'] ?>" width="80" class="mt-2">
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" name="update_brand" 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'; ?>
