<?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' || $_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $input = json_decode(file_get_contents('php://input'), true);
    $id = filter_var($input['id'] ?? null, FILTER_VALIDATE_INT);
    $blocked_date = filter_var($input['blocked_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (!$id && !$blocked_date) {
        $response['message'] = 'ID O FECHA NO PROPORCIONADA';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    try {
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM cms_blocked_dates WHERE id = ?");
            $stmt->execute([$id]);
        } elseif ($blocked_date) {
            $stmt = $pdo->prepare("DELETE FROM cms_blocked_dates WHERE blocked_date = ?");
            $stmt->execute([$blocked_date]);
        } else {
             throw new Exception("PARÁMETROS INVÁLIDOS");
        }

        if ($stmt->rowCount() > 0) {
            $response = ['status' => 'success', 'message' => 'ELIMINADO'];
        } else {
            $response = ['status' => 'error', 'message' => 'NO SE ENCONTRÓ LA FECHA'];
        }

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

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