<?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') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? null; 

    try {
        // 1. OBTENER CONFIGURACIÓN ACTUAL DE schedule_config
        $stmt_current = $pdo->prepare("SELECT daily_hours FROM schedule_config WHERE user_id = 1 LIMIT 1");
        $stmt_current->execute();
        $current_config = $stmt_current->fetch(PDO::FETCH_ASSOC);
        $daily_hours = json_decode($current_config['daily_hours'] ?? '{}', true) ?? [];

        if ($action === 'update_schedule_config') {
            $slot_duration = filter_var($input['slot_duration'] ?? null, FILTER_VALIDATE_INT);
            $capacity = filter_var($input['capacity'] ?? null, FILTER_VALIDATE_INT);

            if ($slot_duration === false || $capacity === false || $slot_duration < 15 || $capacity < 1) {
                throw new Exception("VALORES INVÁLIDOS");
            }

            $stmt = $pdo->prepare("UPDATE schedule_config SET slot_duration = ?, capacity = ? WHERE user_id = 1");
            $stmt->execute([$slot_duration, $capacity]);

            $response = ['status' => 'success', 'message' => 'GUARDADO'];
            
        } elseif ($action === 'update_weekly_hours') {
            $updates = $input['updates'] ?? [];
            if (empty($updates) || !is_array($updates)) {
                throw new Exception("DATOS DE HORARIO INVÁLIDOS");
            }
            
            $pdo->beginTransaction(); 
            
            // Reconstruir el array daily_hours con las actualizaciones
            foreach ($updates as $day_data) {
                $day_index = filter_var($day_data['day'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $is_open = $day_data['is_open'] ? true : false; 
                $open_time = filter_var($day_data['open_time'] ?? '00:00', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $close_time = filter_var($day_data['close_time'] ?? '00:00', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                
                if (isset($daily_hours[$day_index])) {
                    $daily_hours[$day_index]['active'] = $is_open;
                    $daily_hours[$day_index]['start'] = $open_time;
                    $daily_hours[$day_index]['end'] = $close_time;
                }
            }
            
            $json_daily_hours = json_encode($daily_hours, JSON_UNESCAPED_UNICODE);

            $stmt = $pdo->prepare("UPDATE schedule_config SET daily_hours = ? WHERE user_id = 1");
            $stmt->execute([$json_daily_hours]);

            $pdo->commit(); 

            // Devolvemos el array daily_hours modificado para la actualización del lado del cliente
            $new_hours_formatted = [];
            foreach ($daily_hours as $day => $data) {
                $new_hours_formatted[$day] = [
                    'is_open' => $data['active'], 
                    'open_time' => $data['start'], 
                    'close_time' => $data['end']
                ];
            }
            
            $response = ['status' => 'success', 'message' => 'GUARDADO', 'new_hours' => $new_hours_formatted];
            
        } else {
            $response['message'] = 'ACCIÓN NO RECONOCIDA';
        }

    } catch (PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack(); 
        }
        error_log("Error PDO en agenda-config-update.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;