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

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

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

/**
 * 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);
}

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

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

$params = ['page_id' => $pageId];

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);
}

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

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

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