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

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

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

$dealerId = (int)$data['dealer_id'];

$db = Database::getInstance();

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

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

/**
 * Prepare SEO values (NULL safe)
 */
$params = [
    'dealer_id'        => $dealerId,
    '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
 */
$hasSeoData = false;
foreach ($params as $key => $value) {
    if ($key !== 'dealer_id' && $value !== null) {
        $hasSeoData = true;
        break;
    }
}

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

/**
 * UPSERT SEO DATA (SAFE)
 */
$sql = "
INSERT INTO dealer_seo (
    dealer_id,
    meta_title,
    meta_keywords,
    meta_description,
    seo_schema,
    ai_seo_content
) VALUES (
    :dealer_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('Dealer SEO updated', [
    'dealer_id' => $dealerId,
    'by'        => $_SESSION['employee_id']
]);

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