<?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);
    $action = $input['action'] ?? null; 

    try {
        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 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(); 
            $new_hours = [];

            foreach ($updates as $day_data) {
                $day = filter_var($day_data['day'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $is_open = $day_data['is_open'] ? 1 : 0; 
                $open_time = filter_var($day_data['open_time'] ?? '00:00:00', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $close_time = filter_var($day_data['close_time'] ?? '00:00:00', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                
                if (empty($day)) continue;

                $stmt = $pdo->prepare(
                    "INSERT INTO cms_weekly_hours (schedule_id, day, is_open, open_time, close_time) 
                     VALUES (1, ?, ?, ?, ?)
                     ON DUPLICATE KEY UPDATE is_open = VALUES(is_open), open_time = VALUES(open_time), close_time = VALUES(close_time)"
                );
                $stmt->execute([$day, $is_open, $open_time, $close_time]);
                
                $new_hours[] = ['day' => $day, 'is_open' => (bool)$is_open, 'open_time' => $open_time, 'close_time' => $close_time];
            }

            $pdo->commit(); 
            $response = ['status' => 'success', 'message' => 'GUARDADO', 'new_hours' => $new_hours];
            
        } 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;