<?php
/**
 * gallery_upload.php  —  Admin: handle image file uploads for Gallery Manager
 * Place this file in:  /admin/gallery_upload.php
 *
 * Zero-input mode: no title/category/caption required from the client.
 * - Title auto-derived from filename (strip extension, replace - and _ with spaces, title-case)
 * - Category defaults to 'expo'
 * - sort_order auto-increments from current max in gallery data
 * - Supports batches of files in one request (input name="image_file[]")
 * - URL mode still supported as a fallback (single image, title derived from URL)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/auth.php';

header('Content-Type: application/json');

// ── helpers ─────────────────────────────────────────────────────────────────
function jsonError(string $msg, int $code = 400): void {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

function jsonOK(array $payload): void {
    echo json_encode(array_merge(['success' => true], $payload));
    exit;
}

/**
 * Normalizes $_FILES['image_file'] into a flat list of individual file arrays,
 * regardless of whether the form sent one file or many (array syntax).
 */
function normalizeFilesInput(array $filesField): array {
    if (is_array($filesField['name'])) {
        $count = count($filesField['name']);
        $out = [];
        for ($i = 0; $i < $count; $i++) {
            if (empty($filesField['name'][$i])) continue;
            $out[] = [
                'name'     => $filesField['name'][$i],
                'type'     => $filesField['type'][$i],
                'tmp_name' => $filesField['tmp_name'][$i],
                'error'    => $filesField['error'][$i],
                'size'     => $filesField['size'][$i],
            ];
        }
        return $out;
    }
    if (!empty($filesField['name'])) {
        return [$filesField];
    }
    return [];
}

/**
 * Converts a filename (or URL) into a clean, human-readable title.
 * "expo-hall_3_final.jpg" -> "Expo Hall 3 Final"
 */
function titleFromFilename(string $filename): string {
    $name = pathinfo($filename, PATHINFO_FILENAME); // strip extension
    $name = preg_replace('/[_\-]+/', ' ', $name);    // dashes/underscores -> spaces
    $name = preg_replace('/\s+/', ' ', $name);       // collapse whitespace
    $name = trim($name);

    // Guard against filenames that are purely numeric (e.g. "25.jpg",
    // "IMG_004.jpg" after digit-stripping) — a bare number as a title
    // reads as a stray badge/number wherever titles are displayed.
    if ($name === '' || preg_match('/^\d+$/', $name)) {
        $name = 'Gallery Photo ' . date('M j, Y g:ia');
    }
    return mb_convert_case($name, MB_CASE_TITLE, 'UTF-8');
}

// ── only accept POST ─────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

// ── CSRF ─────────────────────────────────────────────────────────────────────
// (Skip if your main.js sends CSRF differently — adjust to match your pattern)
// if (!validateCSRF($_POST['csrf_token'] ?? '')) jsonError('Invalid CSRF token', 403);

$category = 'expo'; // fixed default — no category input in the simplified UI

$allowed  = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
$maxBytes = 5 * 1024 * 1024; // 5 MB per file

// ── read existing gallery once, compute starting sort_order ─────────────────
$gallery = readJSON(GALLERY_FILE);
$maxSort = 0;
foreach ($gallery as $g) {
    $maxSort = max($maxSort, (int)($g['sort_order'] ?? 0));
}
$nextSort = $maxSort + 1;

$newEntries = [];

// ── mode: file upload(s) ─────────────────────────────────────────────────────
if (!empty($_FILES['image_file']['name'])) {

    $files = normalizeFilesInput($_FILES['image_file']);

    if (empty($files)) {
        jsonError('No valid files received.');
    }

    $uploadDir = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/uploads/gallery/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            jsonError('Could not create upload directory.', 500);
        }
    }

    foreach ($files as $file) {

        if ($file['error'] !== UPLOAD_ERR_OK) {
            jsonError('Upload error on "' . $file['name'] . '" (code: ' . $file['error'] . ')');
        }
        if ($file['size'] > $maxBytes) {
            jsonError('"' . $file['name'] . '" is too large. Max 5MB per image.');
        }

        $finfo    = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($file['tmp_name']);
        if (!in_array($mimeType, $allowed, true)) {
            jsonError('"' . $file['name'] . '" has an invalid file type. Only JPG, PNG, WEBP, GIF allowed.');
        }

        $ext = match($mimeType) {
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            'image/gif'  => 'gif',
            default      => 'jpg',
        };
        $filename = uniqid('gallery_', true) . '.' . $ext;
        $destPath = $uploadDir . $filename;

        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            jsonError('Failed to save "' . $file['name'] . '".', 500);
        }

        $imageUrl = '/uploads/gallery/' . $filename;
        $title    = titleFromFilename($file['name']);

        $newEntries[] = [
            'id'         => 'img_' . uniqid(),
            'url'        => $imageUrl,
            'title'      => $title,
            'category'   => $category,
            'caption'    => '',
            'alt'        => $title,
            'featured'   => false,
            'sort_order' => $nextSort,
            'added_at'   => date('Y-m-d H:i:s'),
        ];
        $nextSort++;
    }

} else {
    // ── URL mode (single image, fallback path) ──────────────────────────────
    $imageUrl = trim($_POST['url'] ?? '');
    if (empty($imageUrl) || !filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        jsonError('Please provide a valid image URL.');
    }

    $urlPath = parse_url($imageUrl, PHP_URL_PATH) ?: $imageUrl;
    $title   = titleFromFilename(basename($urlPath));

    $newEntries[] = [
        'id'         => 'img_' . uniqid(),
        'url'        => $imageUrl,
        'title'      => $title,
        'category'   => $category,
        'caption'    => '',
        'alt'        => $title,
        'featured'   => false,
        'sort_order' => $nextSort,
        'added_at'   => date('Y-m-d H:i:s'),
    ];
    $nextSort++;
}

// ── persist: single write for the whole batch ────────────────────────────────
foreach ($newEntries as $entry) {
    $gallery[] = $entry;
}

usort($gallery, fn($a, $b) => ($a['sort_order'] ?? 0) <=> ($b['sort_order'] ?? 0));

writeJSON(GALLERY_FILE, $gallery);

jsonOK([
    'images'  => $newEntries,
    'count'   => count($newEntries),
    'message' => count($newEntries) > 1
        ? count($newEntries) . ' images added successfully.'
        : 'Image added successfully.',
]);