<?php
include("connection.php");
include("header.php");

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Get item ID
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid gallery item");

// Fetch item
$item = mysqli_fetch_assoc(
    mysqli_query($con, "SELECT * FROM gallery_items WHERE id=$id")
);
if (!$item) die("Gallery item not found");

// Fetch 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 = $item['file']; // keep existing by default

        /* ---------- IMAGE ---------- */
        if ($type === 'image') {

            if (!empty($_FILES['file']['name'])) {
                $dir = "./assets/images/gallery/";
                if (!is_dir($dir)) mkdir($dir, 0777, true);

                // remove old file
                if ($item['file'] && file_exists($dir . $item['file'])) {
                    unlink($dir . $item['file']);
                }

                $ext  = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
                $file = time() . '_' . uniqid('gal_') . '.' . $ext;
                move_uploaded_file($_FILES['file']['tmp_name'], $dir . $file);
            }

            $video_url = NULL;
        }

        /* ---------- VIDEO ---------- */
        if ($type === 'video') {

            $hasUploadedVideo = (
                isset($_FILES['video_file']) &&
                $_FILES['video_file']['error'] === UPLOAD_ERR_OK
            );

            $hasVideoUrl      = trim($video_url) !== '';
            $hasExistingVideo = !empty($item['file']) || !empty($item['video_url']);

            // CASE 1: Uploaded new video file
            if ($hasUploadedVideo) {

                $dir = "./assets/videos/gallery/";
                if (!is_dir($dir)) mkdir($dir, 0777, true);

                // delete old uploaded video
                if ($item['file'] && file_exists($dir . $item['file'])) {
                    unlink($dir . $item['file']);
                }

                $ext  = pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION);
                $file = time() . '_' . uniqid('vid_') . '.' . $ext;
                move_uploaded_file($_FILES['video_file']['tmp_name'], $dir . $file);

                // clear URL when file is uploaded
                $video_url = NULL;
            }

            // CASE 2: New video URL entered
            elseif ($hasVideoUrl) {

                // delete old uploaded file if any
                if ($item['file']) {
                    @unlink("./assets/videos/gallery/" . $item['file']);
                }

                $file = NULL;
            }

            // CASE 3: Keep existing video (NO CHANGE)
            elseif ($hasExistingVideo) {
                // do nothing — keep existing file or URL
            }

            // CASE 4: Nothing exists at all
            else {
                $error = "Please provide video URL or upload video file.";
            }
        }


        if ($error === '') {

            $title     = mysqli_real_escape_string($con, $title);
            $videoSql  = $video_url ? "'" . mysqli_real_escape_string($con, $video_url) . "'" : "NULL";
            $fileSql   = $file ? "'" . mysqli_real_escape_string($con, $file) . "'" : "NULL";

            mysqli_query($con,
                "UPDATE gallery_items SET
                 category_id=$category_id,
                 type='$type',
                 title='$title',
                 file=$fileSql,
                 video_url=$videoSql
                 WHERE id=$id"
            );

            header("Location: gallery_items.php?cat=$category_id");
            exit;
        }
    }
}
?>

<div class="main-content">
<div class="page-content">
<div class="container-fluid">

<h4>Edit 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 -->
<div class="mb-3">
<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 if ($cat['id'] == $item['category_id']) echo 'selected'; ?>>
            <?php echo htmlspecialchars($cat['title']); ?>
        </option>
    <?php endwhile; ?>
</select>
</div>

<!-- Title -->
<div class="mb-3">
<label>Title</label>
<input type="text" name="title" class="form-control"
       value="<?php echo htmlspecialchars($item['title']); ?>">
</div>

<!-- Type -->
<div class="mb-3">
<label>Item Type</label>
<select name="type" class="form-control" onchange="toggleType(this.value)" required>
    <option value="">-- Select Type --</option>
    <option value="image" <?php if ($item['type']=='image') echo 'selected'; ?>>Image</option>
    <option value="video" <?php if ($item['type']=='video') echo 'selected'; ?>>Video</option>
</select>
</div>

<!-- Image -->
<div class="mb-3" id="imageField" style="display:none;">
<label>Replace Image</label>
<input type="file" name="file" class="form-control" accept="image/*">

<?php if ($item['type']=='image' && $item['file']): ?>
<img src="assets/images/gallery/<?php echo $item['file']; ?>"
     style="height:80px;margin-top:10px;border-radius:6px;">
<?php endif; ?>
</div>

<!-- Video -->
<div class="mb-3" id="videoField" style="display:none;">

<label>Video URL</label>
<input type="text" name="video_url" class="form-control"
       value="<?php echo $item['video_url']; ?>">

<label class="mt-2">OR Upload Video (MP4)</label>
<input type="file" name="video_file" class="form-control" accept="video/mp4">

<?php if ($item['type']=='video'): ?>
    <?php if ($item['video_url']): ?>
        <p class="mt-2">
            <a href="<?php echo $item['video_url']; ?>" target="_blank">
                View Current Video
            </a>
        </p>
    <?php elseif ($item['file']): ?>
        <video width="200" controls class="mt-2">
            <source src="assets/videos/gallery/<?php echo $item['file']; ?>">
        </video>
    <?php endif; ?>
<?php endif; ?>

</div>

<button name="submit" class="btn btn-primary">Update 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';
}
toggleType('<?php echo $item['type']; ?>');
</script>
