<?php
ob_start();

require_once __DIR__ . '/../core/api.php';
global $pdo;

ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

$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);
    // El frontend usa 'id' (índice + 1) o 'blocked_date' para eliminar
    $id_to_delete = filter_var($input['id'] ?? null, FILTER_VALIDATE_INT);
    $blocked_date = filter_var($input['blocked_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
    if (!$id_to_delete && !$blocked_date) {
        $response['message'] = 'ID O FECHA NO PROPORCIONADA';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    try {
        $pdo->beginTransaction();
        
        // 1. Obtener el JSON actual de blocked_dates
        $stmt_get = $pdo->prepare("SELECT blocked_dates FROM schedule_config WHERE user_id = 1 LIMIT 1");
        $stmt_get->execute();
        $current_blocked_dates_row = $stmt_get->fetch(PDO::FETCH_ASSOC);
        $blocked_dates = json_decode($current_blocked_dates_row['blocked_dates'] ?? '[]', true) ?? [];
        
        $original_count = count($blocked_dates);
        $new_blocked_dates = [];
        $deleted = false;

        // 2. Filtrar el array para eliminar la entrada
        foreach ($blocked_dates as $index => $item) {
            $current_id = $index + 1; // Recrear el ID temporal del frontend

            $is_match = false;
            // Eliminar por ID (índice)
            if ($id_to_delete && $current_id === $id_to_delete) {
                $is_match = true;
            } 
            // Eliminar por fecha
            if ($blocked_date && ($item['date'] ?? '') === $blocked_date) {
                $is_match = true;
            }

            if ($is_match) {
                $deleted = true;
            } else {
                $new_blocked_dates[] = $item;
            }
        }
        
        if ($deleted) {
            // 3. Serializar y actualizar el campo blocked_dates en la base de datos
            $json_blocked_dates = json_encode($new_blocked_dates, JSON_UNESCAPED_UNICODE);
            $stmt_update = $pdo->prepare("UPDATE schedule_config SET blocked_dates = ? WHERE user_id = 1");
            $stmt_update->execute([$json_blocked_dates]);

            $pdo->commit();
            $response = ['status' => 'success', 'message' => 'ELIMINADO'];
        } else {
            $pdo->rollBack();
            $response = ['status' => 'error', 'message' => 'NO SE ENCONTRÓ LA FECHA'];
        }

    } catch (PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack(); 
        }
        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;