<?php
declare(strict_types=1);

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

$db = Database::getInstance();

/**
 * Validate blog_id
 */
if (empty($_POST['blog_id'])) {
    Response::error('blog_id is required', 422);
}

$blogId = (int)$_POST['blog_id'];

/**
 * Role check
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetch();

if (!$role || !in_array($role['name'], ['Super Admin', 'Admin', 'SEO Manager'], true)) {
    Response::error('You are not authorized to upload blog images', 403);
}

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

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

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

$file = $_FILES['image'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    Response::error('File upload failed', 400);
}

/**
 * Allowed image types
 */
$allowedTypes = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/webp' => 'webp'
];

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!isset($allowedTypes[$mime])) {
    Response::error('Invalid image type', 422);
}

/**
 * File size limit: 2MB
 */
if ($file['size'] > 2 * 1024 * 1024) {
    Response::error('Image exceeds 2MB size limit', 422);
}

/**
 * Prepare directory
 */
$baseDir = __DIR__ . '/../../../uploads/blogs/' . $blogId . '/featured';

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

/**
 * Remove existing featured image (DB + FS)
 */
$stmt = $db->prepare("
    SELECT image_path
    FROM blog_images
    WHERE blog_id = :id AND is_primary = 1
");
$stmt->execute(['id' => $blogId]);
$old = $stmt->fetch();

if ($old) {
    $oldPath = __DIR__ . '/../../../' . ltrim($old['image_path'], '/');
    if (is_file($oldPath)) {
        unlink($oldPath);
    }

    $db->prepare("
        DELETE FROM blog_images
        WHERE blog_id = :id AND is_primary = 1
    ")->execute(['id' => $blogId]);
}

/**
 * Generate filename
 */
$extension = $allowedTypes[$mime];
$filename  = 'featured_' . uniqid() . '.' . $extension;
$filepath  = $baseDir . '/' . $filename;

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

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

$stmt->execute([
    'blog_id'    => $blogId,
    'image_path'=> '/uploads/blogs/' . $blogId . '/featured/' . $filename,
    'alt_text'  => $_POST['alt_text'] ?? null,
    'caption'   => $_POST['caption'] ?? null
]);

Logger::auth('Blog featured image uploaded', [
    'blog_id' => $blogId,
    'by'      => $_SESSION['employee_id']
]);

Response::success('Blog featured image uploaded successfully');
