<?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;
}

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

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

if ($galleryId <= 0 || $title === '' || $category === '') {
    echo json_encode(['success' => false, 'message' => 'Gallery ID, title, and category are required']);
    exit;
}

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

$currentImage = null;
$currentStmt = $connection->prepare("SELECT image FROM gallery_items WHERE id = ?");
if (!$currentStmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare current gallery lookup']);
    exit;
}
$currentStmt->bind_param('i', $galleryId);
$currentStmt->execute();
$currentResult = $currentStmt->get_result();
if ($currentResult && $currentResult->num_rows > 0) {
    $currentRow = $currentResult->fetch_assoc();
    $currentImage = (string)($currentRow['image'] ?? '');
}
$currentStmt->close();

if ($currentImage === null) {
    echo json_encode(['success' => false, 'message' => 'Gallery item not found']);
    exit;
}

$imageUrl = $currentImage;
if ($image && $image['error'] === UPLOAD_ERR_OK) {
    $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;
    }
}

$stmt = $connection->prepare("UPDATE gallery_items SET title = ?, category = ?, image = ? WHERE id = ?");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Failed to prepare update']);
    exit;
}

$stmt->bind_param('sssi', $title, $category, $imageUrl, $galleryId);
$ok = $stmt->execute();
$stmt->close();

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