<?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 seedGalleryFromHtmlIfEmpty(mysqli $connection): void
{
    $countResult = $connection->query("SELECT COUNT(*) AS total FROM gallery_items");
    $total = 0;
    if ($countResult) {
        $row = $countResult->fetch_assoc();
        $total = (int)($row['total'] ?? 0);
    }

    if ($total > 0) {
        return;
    }

    $galleryFile = __DIR__ . '/gallery.html';
    if (!file_exists($galleryFile)) {
        return;
    }

    $html = file_get_contents($galleryFile);
    if ($html === false) {
        return;
    }

    $pattern = '/<div class="[^\"]*filter-item\s+([^\"]*)"[^>]*data-gallery-id="(\d+)"[^>]*>.*?<img src="([^"]+)"[^>]*>.*?<h2 class="box-title">([^<]+)<\/h2>/si';
    if (!preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) {
        return;
    }

    $insert = $connection->prepare("INSERT INTO gallery_items (title, category, image, sort_order, is_active) VALUES (?, ?, ?, ?, 1)");
    if (!$insert) {
        return;
    }

    foreach ($matches as $idx => $item) {
        $classes = trim($item[1]);
        $image = trim($item[3]);
        $title = trim(html_entity_decode($item[4], ENT_QUOTES | ENT_HTML5, 'UTF-8'));

        $category = 'Interior';
        if (stripos($classes, 'cat2') !== false) $category = 'Architecture';
        elseif (stripos($classes, 'cat3') !== false) $category = 'Building';
        elseif (stripos($classes, 'cat4') !== false) $category = 'Exterior';
        elseif (stripos($classes, 'cat5') !== false) $category = 'Shape';

        if ($title === '' || $image === '') {
            continue;
        }

        $sortOrder = $idx + 1;
        $insert->bind_param('sssi', $title, $category, $image, $sortOrder);
        $insert->execute();
    }

    $insert->close();
}

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

$title = trim($_POST['title'] ?? '');
$category = trim($_POST['category'] ?? '');
$image = $_FILES['image'] ?? null;

if ($title === '' || $category === '' || !$image || $image['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'All fields are required and image must be provided']);
    exit;
}

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

seedGalleryFromHtmlIfEmpty($connection);

$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$maxSize = 5 * 1024 * 1024;

if (!in_array($image['type'], $allowedTypes, true)) {
    echo json_encode(['success' => false, 'message' => 'Invalid image type. Only JPG, PNG, GIF, and WebP allowed']);
    exit;
}

if ($image['size'] > $maxSize) {
    echo json_encode(['success' => false, 'message' => 'Image size exceeds 5MB limit']);
    exit;
}

$uploadDir = __DIR__ . '/assets/uploads/gallery';
if (!is_dir($uploadDir)) {
    @mkdir($uploadDir, 0755, true);
}

$ext = strtolower(pathinfo($image['name'], PATHINFO_EXTENSION));
$filename = time() . '_' . uniqid() . '.' . $ext;
$uploadPath = $uploadDir . '/' . $filename;
$imageUrl = 'assets/uploads/gallery/' . $filename;

if (!move_uploaded_file($image['tmp_name'], $uploadPath)) {
    echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
    exit;
}

$maxResult = $connection->query("SELECT COALESCE(MAX(sort_order), 0) AS max_order FROM gallery_items");
$maxRow = $maxResult ? $maxResult->fetch_assoc() : ['max_order' => 0];
$nextOrder = ((int)($maxRow['max_order'] ?? 0)) + 1;

$insert = $connection->prepare("INSERT INTO gallery_items (title, category, image, sort_order, is_active) VALUES (?, ?, ?, ?, 1)");
if (!$insert) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare insert']);
    exit;
}

$insert->bind_param('sssi', $title, $category, $imageUrl, $nextOrder);
$ok = $insert->execute();
$newId = $insert->insert_id;
$insert->close();

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