<?php
include("connection.php");

// Validate and sanitize ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: viewgallery.php");
    exit;
}

$id = intval($_GET['id']);

// Step 1: Fetch the existing photo or video filename or URL
$stmt = $con->prepare("SELECT photo FROM media WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header("Location: viewgallery.php");
    exit;
}

$row = $result->fetch_assoc();
$mediaPath = $row['photo'];

// Step 2: Delete the file if it's a local file
if (!empty($mediaPath)) {
    // Check if it's not a YouTube or external URL
    if (
        !preg_match("/^(http|https):\/\//i", $mediaPath) && // Not a full URL
        strpos($mediaPath, 'youtube.com') === false &&
        strpos($mediaPath, 'youtu.be') === false &&
        strpos($mediaPath, 'embed') === false
    ) {
        $filePath = "assets/images/gallery/" . $mediaPath;
        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }
}

// Step 3: Delete the database record
$stmtDel = $con->prepare("DELETE FROM media WHERE id = ?");
$stmtDel->bind_param("i", $id);
$stmtDel->execute();

// Step 4: Redirect back
header("Location: viewgallery.php");
exit;
?>

