<?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);

    $type = $input['type'] ?? 'unica';
    
    $client_id = isset($input['client_id']) ? filter_var($input['client_id'], FILTER_VALIDATE_INT) : null;
    $lead_id = isset($input['lead_id']) ? filter_var($input['lead_id'], FILTER_VALIDATE_INT) : null;
    $notes = filter_var($input['notes'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if ((!$client_id && !$lead_id)) {
        $response['message'] = 'SE DEBE SELECCIONAR UN CLIENTE O UN PROSPECTO';
        ob_end_clean();
        echo json_encode($response);
        exit;
    }

    try {
        if ($type === 'unica') {
            $appointment_date = $input['appointment_date'] ?? null;
            $appointment_time = $input['appointment_time'] ?? null; 

            if (!$appointment_date || !$appointment_time) {
                $response['message'] = 'FALTAN DATOS OBLIGATORIOS (FECHA Y HORA)';
                ob_end_clean();
                echo json_encode($response);
                exit;
            }
            
            $stmt_config = $pdo->query("SELECT capacity FROM schedule_config WHERE id = 1");
            $config = $stmt_config->fetch(PDO::FETCH_ASSOC);
            if (!$config) throw new Exception("LA CONFIGURACIÓN DE LA AGENDA NO EXISTE");
            
            $capacity = (int)$config['capacity'];

            $stmt_booked = $pdo->prepare("SELECT COUNT(*) FROM unique_appointments WHERE appointment_date = ? AND appointment_time = ? AND status != 'cancelled'");
            $stmt_booked->execute([$appointment_date, $appointment_time]);
            $booked_count = (int)$stmt_booked->fetchColumn();

            if ($booked_count >= $capacity) {
                $response['status'] = 'error';
                $response['message'] = 'LO SENTIMOS, ESTE HORARIO SE ACABA DE LLENAR';
                ob_end_clean();
                echo json_encode($response);
                exit;
            }

            $status = 'pending';
            $stmt = $pdo->prepare(
                "INSERT INTO unique_appointments (client_id, lead_id, appointment_date, appointment_time, status, notes) 
                 VALUES (?, ?, ?, ?, ?, ?)"
            );
            $stmt->execute([ $client_id, $lead_id, $appointment_date, $appointment_time, $status, $notes ]);
            $response = ['status' => 'success', 'message' => 'GUARDADO'];

        } elseif ($type === 'recurrente') {
            $frequency = $input['frequency'] ?? null;
            $next_appointment_date = $input['next_appointment_date'] ?? null;
            
            if (!$frequency || !$next_appointment_date) {
                $response['message'] = 'FALTAN DATOS OBLIGATORIOS PARA CITA RECURRENTE';
                ob_end_clean();
                echo json_encode($response);
                exit;
            }

            $stmt = $pdo->prepare(
                "INSERT INTO recurring_appointments (client_id, lead_id, frequency, next_appointment_date, notes) 
                 VALUES (?, ?, ?, ?, ?)"
            );
            $stmt->execute([ $client_id, $lead_id, $frequency, $next_appointment_date, $notes ]);
            $response = ['status' => 'success', 'message' => 'GUARDADO'];
        }

    } catch (Exception $e) {
        error_log("Error en agenda-create.php: " . $e->getMessage());
        $response['message'] = 'ERROR AL AGENDAR';
    }
}

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