<?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';

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

/**
 * faq_id is mandatory
 */
Validator::required($data, ['faq_id']);

$faqId = (int)$data['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);
}

/**
 * Allowed SEO fields
 */
$seoFields = [
    'meta_title',
    'meta_keywords',
    'meta_description',
    'seo_schema',
    'ai_seo_content'
];

$insertColumns = ['faq_id'];
$insertValues  = [':faq_id'];
$updateParts   = [];

$params = ['faq_id' => $faqId];

foreach ($seoFields as $field) {
    if (array_key_exists($field, $data)) {
        $insertColumns[] = $field;
        $insertValues[]  = ':' . $field;
        $updateParts[]   = "$field = VALUES($field)";
        $params[$field]  = trim((string)$data[$field]);
    }
}

/**
 * Nothing to update
 */
if (count($insertColumns) === 1) {
    Response::error('No SEO fields provided for update', 422);
}

/**
 * Proper UPSERT
 */
$sql = "
    INSERT INTO faq_seo (" . implode(', ', $insertColumns) . ")
    VALUES (" . implode(', ', $insertValues) . ")
    ON DUPLICATE KEY UPDATE
        " . implode(', ', $updateParts) . "
";

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

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