<?php
ob_start();
require_once '../files/guardiankey.php';
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once 'db_connection.php';

$response = ['status' => 'error', 'message' => 'SOLICITUD NO VÁLIDA'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $blocked_date = filter_var($input['blocked_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $blocked_date)) {
        $response['message'] = 'FORMATO DE FECHA INVÁLIDO (DEBE SER AA-MM-DD)';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    try {
        $stmt = $pdo->prepare("INSERT IGNORE INTO cms_blocked_dates (website_config_id, blocked_date) VALUES (1, ?)");
        $stmt->execute([$blocked_date]);

        if ($stmt->rowCount() > 0) {
            $response = ['status' => 'success', 'message' => 'GUARDADO', 'id' => $pdo->lastInsertId()];
        } else {
            // No se notifica si ya existía, solo se devuelve éxito
            $response = ['status' => 'success'];
        }

    } catch (PDOException $e) {
        error_log("Error en agenda-config-create.php: " . $e->getMessage());
        $response['message'] = 'ERROR DE BASE DE DATOS';
    }
}

ob_end_clean();
echo json_encode($response);
exit;