<?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/Validator.php';
require_once __DIR__ . '/../../core/Logger.php';

$db   = Database::getInstance();
$data = json_decode(file_get_contents('php://input'), true);

Validator::required($data, ['blog_id']);

$blogId = (int)$data['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 update blog SEO', 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);
}

/**
 * Prepare SEO values (NULL-safe)
 */
$params = [
    'blog_id'          => $blogId,
    'meta_title'       => $data['meta_title'] ?? null,
    'meta_keywords'    => $data['meta_keywords'] ?? null,
    'meta_description' => $data['meta_description'] ?? null,
    'seo_schema'       => $data['seo_schema'] ?? null,
    'ai_seo_content'   => $data['ai_seo_content'] ?? null
];

/**
 * Ensure at least one SEO field is provided
 */
$hasSeo = false;
foreach ($params as $key => $value) {
    if ($key !== 'blog_id' && $value !== null) {
        $hasSeo = true;
        break;
    }
}

if (!$hasSeo) {
    Response::error('No SEO fields provided for update', 422);
}

/**
 * UPSERT BLOG SEO (SAFE)
 */
$sql = "
INSERT INTO blog_seo (
    blog_id,
    meta_title,
    meta_keywords,
    meta_description,
    seo_schema,
    ai_seo_content
) VALUES (
    :blog_id,
    :meta_title,
    :meta_keywords,
    :meta_description,
    :seo_schema,
    :ai_seo_content
)
ON DUPLICATE KEY UPDATE
    meta_title       = VALUES(meta_title),
    meta_keywords    = VALUES(meta_keywords),
    meta_description = VALUES(meta_description),
    seo_schema       = VALUES(seo_schema),
    ai_seo_content   = VALUES(ai_seo_content)
";

$stmt = $db->prepare($sql);
$stmt->execute($params);

Logger::auth('Blog SEO updated', [
    'blog_id' => $blogId,
    'by'      => $_SESSION['employee_id']
]);

Response::success('Blog SEO updated successfully');
