<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/**
 * Validate page_id
 */
if (empty($_POST['page_id']) || !filter_var($_POST['page_id'], FILTER_VALIDATE_INT)) {
    Response::error('Valid page_id is required', 422);
}

$pageId = (int)$_POST['page_id'];

/**
 * Image type: featured | inline
 */
$imageType = $_POST['image_type'] ?? 'featured';
if (!in_array($imageType, ['featured', 'inline'], true)) {
    Response::error('Invalid image_type', 422);
}

/**
 * Check page exists
 */
$stmt = $db->prepare("SELECT id FROM pages WHERE id = :id");
$stmt->execute(['id' => $pageId]);

if (!$stmt->fetch()) {
    Response::error('Page not found', 404);
}

/**
 * Validate image
 */
if (empty($_FILES['image'])) {
    Response::error('Image file is required', 422);
}

$file = $_FILES['image'];

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

if (!in_array($file['type'], $allowedTypes, true)) {
    Response::error('Only JPG, PNG, WEBP images allowed', 422);
}

if ($file['size'] > $maxSize) {
    Response::error('Image size must not exceed 2MB', 422);
}

/**
 * Resolve upload path
 * /nwx/uploads/pages/{page_id}/{type}/
 */
$adminRoot = dirname(__DIR__, 3); // /nwx/admin
$uploadDir = $adminRoot . "/uploads/pages/$pageId/$imageType/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

/**
 * Generate filename
 */
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$fileName  = "page_{$pageId}_" . time() . '.' . $extension;
$fullPath  = $uploadDir . $fileName;

/**
 * Move file
 */
if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
    Response::error('Failed to upload image', 500);
}

/**
 * Metadata
 */
$altText   = $_POST['alt_text'] ?? null;
$caption   = $_POST['caption'] ?? null;
$sortOrder = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 1;

/**
 * DB transaction
 */
$db->beginTransaction();

try {

    /**
     * If featured → deactivate previous
     */
    if ($imageType === 'featured') {
        $stmt = $db->prepare("
            UPDATE page_images
            SET status = 'InActive'
            WHERE page_id = :page_id AND is_primary = 1
        ");
        $stmt->execute(['page_id' => $pageId]);
    }

    /**
     * Insert image record
     */
    $stmt = $db->prepare("
        INSERT INTO page_images (
            page_id,
            image_path,
            alt_text,
            caption,
            is_primary,
            sort_order,
            status,
            created_at
        ) VALUES (
            :page_id,
            :image_path,
            :alt_text,
            :caption,
            :is_primary,
            :sort_order,
            'Active',
            NOW()
        )
    ");

    $stmt->execute([
        'page_id'    => $pageId,
        'image_path' => "/uploads/pages/$pageId/$imageType/$fileName",
        'alt_text'   => $altText,
        'caption'    => $caption,
        'is_primary' => $imageType === 'featured' ? 1 : 0,
        'sort_order' => $sortOrder
    ]);

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to save image', 500);
}

Response::success('Page image uploaded successfully', [
    'image' => "/uploads/pages/$pageId/$imageType/$fileName",
    'type'  => $imageType
]);
