<?php
// db/schedule-update.php
ob_start();
header('Content-Type: application/json');
require_once '../core/api.php'; 

try {
    $user_id = 1; 
    
    // 1. Recibir datos básicos
    $slot = $_POST['slot_duration'] ?? 30;
    $capacity = $_POST['capacity'] ?? 1;
    $days = $_POST['work_days'] ?? ''; 
    
    // 2. Recibir horarios globales (respaldo)
    $start = $_POST['start_time'] ?? '09:00:00';
    $end = $_POST['end_time'] ?? '17:00:00';

    // 3. Recibir JSONs complejos
    $daily_hours = $_POST['daily_hours'] ?? '{}'; 
    $blocked_dates = $_POST['blocked_dates'] ?? '[]'; 

    // Verificar si existe registro (Sentencia preparada)
    $check = $pdo->prepare("SELECT id FROM schedule_config WHERE user_id = ?");
    $check->execute([$user_id]);

    if ($check->fetch()) {
        // ACTUALIZAR (Sentencia preparada)
        $sql = "UPDATE schedule_config SET 
                slot_duration=?, 
                capacity=?, 
                work_days=?, 
                start_time=?, 
                end_time=?, 
                daily_hours=?, 
                blocked_dates=? 
                WHERE user_id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$slot, $capacity, $days, $start, $end, $daily_hours, $blocked_dates, $user_id]);
    } else {
        $sql = "INSERT INTO schedule_config 
                (user_id, slot_duration, capacity, work_days, start_time, end_time, daily_hours, blocked_dates) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user_id, $slot, $capacity, $days, $start, $end, $daily_hours, $blocked_dates]);
    }

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
ob_end_clean();
?>