<?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 FAQ ID
 */
if (empty($_POST['faq_id']) || !filter_var($_POST['faq_id'], FILTER_VALIDATE_INT)) {
    Response::error('Valid faq_id is required', 422);
}

$faqId = (int)$_POST['faq_id'];

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

if (!$stmt->fetch()) {
    Response::error('FAQ 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 are allowed', 422);
}

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

/**
 * Resolve upload path (STANDARDIZED)
 * /nwx/uploads/faqs/{faq_id}/featured/
 */
$adminRoot = dirname(__DIR__, 3); // /nwx/admin
$uploadDir = $adminRoot . "/uploads/faqs/$faqId/featured/";

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

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

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

/**
 * Optional metadata
 */
$altText = isset($_POST['alt_text']) ? trim($_POST['alt_text']) : null;
$caption = isset($_POST['caption']) ? trim($_POST['caption']) : null;

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

try {

    /**
     * Deactivate previous images
     */
    $stmt = $db->prepare("
        UPDATE faq_images
        SET status = 'InActive'
        WHERE faq_id = :faq_id
    ");
    $stmt->execute(['faq_id' => $faqId]);

    /**
     * Insert new featured image
     */
    $stmt = $db->prepare("
        INSERT INTO faq_images (
            faq_id,
            image_path,
            alt_text,
            caption,
            is_primary,
            status,
            created_at
        ) VALUES (
            :faq_id,
            :image_path,
            :alt_text,
            :caption,
            1,
            'Active',
            NOW()
        )
    ");

    $stmt->execute([
        'faq_id'     => $faqId,
        'image_path' => "/uploads/faqs/$faqId/featured/$fileName",
        'alt_text'   => $altText,
        'caption'    => $caption
    ]);

    $db->commit();

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

Response::success('FAQ featured image uploaded successfully', [
    'image' => "/uploads/faqs/$faqId/featured/$fileName"
]);
