<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/config/db.php';

function ensureGalleryTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS gallery_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        category VARCHAR(100) NOT NULL,
        image VARCHAR(500) NOT NULL,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    if (!$connection->query($sql)) {
        return false;
    }

    $requiredColumns = [
        'title' => "ALTER TABLE gallery_items ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT ''",
        'category' => "ALTER TABLE gallery_items ADD COLUMN category VARCHAR(100) NOT NULL DEFAULT 'Interior'",
        'image' => "ALTER TABLE gallery_items ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
        'sort_order' => "ALTER TABLE gallery_items ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
        'is_active' => "ALTER TABLE gallery_items ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
        'created_at' => "ALTER TABLE gallery_items ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
        'updated_at' => "ALTER TABLE gallery_items ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
    ];

    $columnsResult = $connection->query("SHOW COLUMNS FROM gallery_items");
    $existingColumns = [];
    if ($columnsResult) {
        while ($column = $columnsResult->fetch_assoc()) {
            $existingColumns[] = $column['Field'];
        }
    }

    foreach ($requiredColumns as $columnName => $alterSql) {
        if (!in_array($columnName, $existingColumns, true) && !$connection->query($alterSql)) {
            return false;
        }
    }

    return true;
}

function normalizeSortOrder(mysqli $connection): void
{
    $result = $connection->query("SELECT id FROM gallery_items ORDER BY sort_order ASC, id ASC");
    if (!$result) {
        return;
    }

    $update = $connection->prepare("UPDATE gallery_items SET sort_order = ? WHERE id = ?");
    if (!$update) {
        return;
    }

    $index = 1;
    while ($row = $result->fetch_assoc()) {
        $id = (int)$row['id'];
        $sortOrder = $index++;
        $update->bind_param('ii', $sortOrder, $id);
        $update->execute();
    }

    $update->close();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$galleryId = (int)($_POST['gallery_id'] ?? 0);
if ($galleryId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Gallery ID is required']);
    exit;
}

if (!ensureGalleryTable($connection)) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare gallery table']);
    exit;
}

$stmt = $connection->prepare("DELETE FROM gallery_items WHERE id = ?");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare delete']);
    exit;
}

$stmt->bind_param('i', $galleryId);
$ok = $stmt->execute();
$stmt->close();

if ($ok) {
    normalizeSortOrder($connection);
}

echo json_encode([
    'success' => (bool)$ok,
    'message' => $ok ? 'Gallery item deleted successfully' : 'Failed to delete gallery item'
]);
?>
