<?php
ob_start();
ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';
global $pdo;

$response = ['status' => 'error', 'message' => 'INVALID REQUEST'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $type = $input['type'] ?? 'unica';
    $client_id = isset($input['client_id']) && $input['client_id'] ? filter_var($input['client_id'], FILTER_VALIDATE_INT) : null;
    $lead_id = isset($input['lead_id']) && $input['lead_id'] ? filter_var($input['lead_id'], FILTER_VALIDATE_INT) : null;
    $notes = filter_var($input['notes'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
    $raw_time = $input['appointment_time'] ?? '09:00';
    $appointment_time = date('H:i:s', strtotime($raw_time));

    if (!$client_id && !$lead_id) {
        echo json_encode(['status' => 'error', 'message' => 'CLIENT OR LEAD REQUIRED']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        $stmt_config = $pdo->prepare("SELECT capacity FROM schedule_config WHERE id = 1 LIMIT 1");
        $stmt_config->execute();
        $config = $stmt_config->fetch(PDO::FETCH_ASSOC);
        $capacity = (int)($config['capacity'] ?? 1);
        
        $user_id = 1; 

        if ($type === 'unica') {
            $appointment_date = filter_var($input['appointment_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            if (empty($appointment_date)) {
                throw new Exception('FALTA DATO OBLIGATORIO (FECHA)');
            }

            $public_token = bin2hex(random_bytes(32)); 

            $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM unique_appointments WHERE appointment_date = ? AND appointment_time = ? AND status != 'cancelled'");
            $stmt_check->execute([$appointment_date, $appointment_time]);
            
            if ($stmt_check->fetchColumn() >= $capacity) {
                throw new Exception('SLOT NOT AVAILABLE');
            }

            $sql = "INSERT INTO unique_appointments 
                    (user_id, client_id, lead_id, appointment_date, appointment_time, status, notes, public_token) 
                    VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$user_id, $client_id, $lead_id, $appointment_date, $appointment_time, $notes, $public_token]);
            $response = ['status' => 'success', 'message' => 'CITA ÚNICA CREADA', 'id' => $pdo->lastInsertId()];

        } elseif ($type === 'recurrente') {
            $frequency = filter_var($input['frequency'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $count = filter_var($input['count'] ?? 0, FILTER_VALIDATE_INT);
            $start_date = filter_var($input['first_appointment_date'] ?? null, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            
            if (empty($frequency) || $count < 1 || empty($start_date)) {
                 throw new Exception('FALTAN DATOS OBLIGATORIOS (FRECUENCIA, CANTIDAD, FECHA INICIO)');
            }

            $sql_master = "INSERT INTO recurring_appointments 
                (user_id, client_id, lead_id, frequency, first_appointment_date, appointment_time, notes, next_appointment_date) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt_master = $pdo->prepare($sql_master);
            $stmt_master->execute([$user_id, $client_id, $lead_id, $frequency, $start_date, $appointment_time, $notes, $start_date]);
            $master_id = $pdo->lastInsertId();

            $sql_children = "INSERT INTO unique_appointments 
                (user_id, client_id, lead_id, appointment_date, appointment_time, status, notes, recurring_parent_id, public_token) 
                VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)";
            $stmt_insert_child = $pdo->prepare($sql_children);

            $currentDate = new DateTime($start_date);
            $intervalInDays = ($frequency === 'daily') ? 1 : (($frequency === 'weekly') ? 7 : (($frequency === 'biweekly') ? 14 : 0));
            $generated_count = 0;

            for ($i = 0; $i < $count; $i++) {
                $dateStr = $currentDate->format('Y-m-d');
                $timeStr = $appointment_time; 
                
                $child_token = bin2hex(random_bytes(32));

                $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM unique_appointments WHERE appointment_date = ? AND appointment_time = ? AND status != 'cancelled'");
                $stmt_check->execute([$dateStr, $timeStr]);
                
                if ($stmt_check->fetchColumn() < $capacity) {
                    $stmt_insert_child->execute([$user_id, $client_id, $lead_id, $dateStr, $timeStr, $notes, $master_id, $child_token]);
                    $generated_count++;
                }

                if ($frequency === 'monthly') $currentDate->modify('+1 month'); 
                else $currentDate->modify("+$intervalInDays days");
            }

            $last_generated_date = ($generated_count > 0) ? $currentDate->modify("-$intervalInDays days")->format('Y-m-d') : $start_date;
            $stmt_update_master = $pdo->prepare("UPDATE recurring_appointments SET next_appointment_date = ? WHERE id = ?");
            $stmt_update_master->execute([$last_generated_date, $master_id]);

            $pdo->commit();
            $response = ['status' => 'success', 'message' => "RECURRING SERIES CREATED ($generated_count generated).", 'id' => $master_id];
        } else {
            throw new Exception("TIPO DE CITA NO VÁLIDO");
        }

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log("Error Agenda: " . $e->getMessage());
        $response = ['status' => 'error', 'message' => 'ERROR: ' . $e->getMessage()];
    }

}

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