prepare("SELECT image_path FROM gallery WHERE id = :id"); $stmt_path->execute(['id' => $delete_id]); $img = $stmt_path->fetch(); if ($img) { if (file_exists(__DIR__ . '/../' . $img['image_path'])) { @unlink(__DIR__ . '/../' . $img['image_path']); } $stmt = $pdo->prepare("DELETE FROM gallery WHERE id = :id"); $stmt->execute(['id' => $delete_id]); } header("Location: " . BASE_URL . "admin/gallery.php?success=deleted"); exit(); } catch (PDOException $e) { $error_msg = "Failed to delete image: " . $e->getMessage(); } } // Upload new gallery image if (isset($_POST['submit_gallery'])) { $title = trim($_POST['title']); $category = trim($_POST['category']); if (empty($title) || empty($category) || !isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) { $error_msg = "All fields and a valid image file are required."; } else { $allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg']; if (!in_array($_FILES['image']['type'], $allowed)) { $error_msg = "Only JPG, PNG and WebP files are allowed."; } else { try { $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION); $filename = 'gal_' . bin2hex(random_bytes(8)) . '.' . $ext; $destination = PROJECT_UPLOAD_DIR . $filename; if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) { $db_path = 'uploads/projects/' . $filename; $stmt = $pdo->prepare("INSERT INTO gallery (title, category, image_path) VALUES (:title, :category, :image_path)"); $stmt->execute([ 'title' => $title, 'category' => $category, 'image_path' => $db_path ]); header("Location: " . BASE_URL . "admin/gallery.php?success=added"); exit(); } else { $error_msg = "Failed to save file to uploads folder."; } } catch (PDOException $e) { $error_msg = "Database error: " . $e->getMessage(); } } } } // Fetch all gallery items $items = []; try { $stmt = $pdo->query("SELECT * FROM gallery ORDER BY id DESC"); $items = $stmt->fetchAll(); } catch (PDOException $e) { // offline } require_once __DIR__ . '/header.php'; require_once __DIR__ . '/navbar.php'; ?>