<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET    /api/admin/gallery — list all gallery items
// POST   /api/admin/gallery — add item
// PATCH  /api/admin/gallery — update item
// DELETE /api/admin/gallery — delete item
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

requireAdmin();
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $items = $db->query('SELECT * FROM gallery ORDER BY created_at DESC')->fetchAll();
    jsonResponse($items);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body        = getBody();
    $title       = trim($body['title']       ?? '');
    $description = trim($body['description'] ?? '');
    $imageUrl    = trim($body['imageUrl']     ?? '');
    $category    = trim($body['category']    ?? 'General');
    $isActive    = isset($body['isActive'])  ? (int)(bool)$body['isActive'] : 1;

    if (!$title || !$imageUrl) jsonError('title and imageUrl are required');

    $id = generateId();
    $db->prepare(
        'INSERT INTO gallery (id, title, description, image_url, category, is_active)
         VALUES (?, ?, ?, ?, ?, ?)'
    )->execute([$id, $title, $description ?: null, $imageUrl, $category, $isActive]);

    $stmt = $db->prepare('SELECT * FROM gallery WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch(), 201);
}

if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $body = getBody();
    $id   = $body['id'] ?? '';
    if (!$id) jsonError('id is required');

    $fields = [];
    $params = [];
    if (isset($body['title']))       { $fields[] = 'title = ?';       $params[] = trim($body['title']); }
    if (isset($body['description'])) { $fields[] = 'description = ?'; $params[] = trim($body['description']); }
    if (isset($body['imageUrl']))    { $fields[] = 'image_url = ?';   $params[] = trim($body['imageUrl']); }
    if (isset($body['category']))    { $fields[] = 'category = ?';    $params[] = trim($body['category']); }
    if (isset($body['isActive']))    { $fields[] = 'is_active = ?';   $params[] = (int)(bool)$body['isActive']; }

    if (empty($fields)) jsonError('Nothing to update');
    $params[] = $id;
    $db->prepare('UPDATE gallery SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);

    $stmt = $db->prepare('SELECT * FROM gallery WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $body = getBody();
    $id   = $body['id'] ?? '';
    if (!$id) jsonError('id is required');
    $db->prepare('DELETE FROM gallery WHERE id = ?')->execute([$id]);
    jsonResponse(['success' => true]);
}

jsonError('Method not allowed', 405);
