<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Fetch all gallery categories
$categories = mysqli_query(
    $con,
    "SELECT id, title FROM gallery_categories ORDER BY title ASC"
);

$error = '';

if (isset($_POST['submit'])) {

    $category_id = (int)($_POST['category_id'] ?? 0);
    $type        = $_POST['type'] ?? '';
    $title       = trim($_POST['title'] ?? '');
    $video_url   = trim($_POST['video_url'] ?? '');

    if ($category_id <= 0) {
        $error = "Please select a category.";
    } elseif ($type === '') {
        $error = "Please select item type.";
    } else {

        $file = null;

        // Image upload
        if ($type === 'image') {
            if (!empty($_FILES['file']['name'])) {
                $dir = "./assets/images/gallery/";
                if (!is_dir($dir)) {
                    mkdir($dir, 0777, true);
                }

                $ext  = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
                $file = time() . '_' . uniqid('gal_') . '.' . $ext;
                move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file);
            } else {
                $error = "Please upload an image.";
            }
        }

        // Video
        if ($type === 'video' && $video_url === '') {
            $error = "Please enter video URL.";
        }

        if ($error === '') {

            $title     = mysqli_real_escape_string($con, $title);
            $video_url = mysqli_real_escape_string($con, $video_url);
            $fileSql   = $file ? "'" . mysqli_real_escape_string($con, $file) . "'" : "NULL";
            $videoSql  = $type === 'video' ? "'$video_url'" : "NULL";

            mysqli_query($con,
                "INSERT INTO gallery_items
                 (category_id, type, file, video_url, title)
                 VALUES
                 ($category_id, '$type', $fileSql, $videoSql, '$title')"
            );

            header("Location: gallery_items.php?cat=$category_id");
            exit;
        }
    }
}
?>

<div class="main-content">
<div class="page-content">
<div class="container-fluid">

<h4>Add Gallery Item</h4>

<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">

<!-- Category Select -->
<div class="mb-3">
    <label class="form-label">Gallery Category</label>
    <select name="category_id" class="form-control" required>
        <option value="">-- Select Category --</option>
        <?php while ($cat = mysqli_fetch_assoc($categories)): ?>
            <option value="<?php echo $cat['id']; ?>">
                <?php echo htmlspecialchars($cat['title']); ?>
            </option>
        <?php endwhile; ?>
    </select>
</div>

<!-- Title -->
<div class="mb-3">
    <label class="form-label">Title (optional)</label>
    <input type="text" name="title" class="form-control">
</div>

<!-- Type -->
<div class="mb-3">
    <label class="form-label">Item Type</label>
    <select name="type" class="form-control" onchange="toggleType(this.value)" required>
        <option value="">-- Select Type --</option>
        <option value="image">Image</option>
        <option value="video">Video</option>
    </select>
</div>

<!-- Image -->
<div class="mb-3" id="imageField" style="display:none;">
    <label class="form-label">Image</label>
    <input type="file" name="file" class="form-control" accept="image/*">
</div>

<!-- Video -->
<div class="mb-3" id="videoField" style="display:none;">
    <label class="form-label">Video URL (YouTube / Vimeo)</label>
    <input type="text" name="video_url" class="form-control">
</div>

<button name="submit" class="btn btn-primary">Save Item</button>
<a href="gallery_items.php" class="btn btn-secondary">Back</a>

</form>

</div>
</div>
</div>

<?php include("footer.php"); ?>

<script>
function toggleType(val) {
    document.getElementById('imageField').style.display = val === 'image' ? 'block' : 'none';
    document.getElementById('videoField').style.display = val === 'video' ? 'block' : 'none';
}
</script>
