<?php
header('Content-Type: application/json');

// Incluye el archivo de conexión a la base de datos
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);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['status' => 'error', 'message' => 'Error al decodificar JSON: ' . json_last_error_msg()]);
        exit;
    }

    $client_id = $input['client_id'] ?? null;
    $lead_id = $input['lead_id'] ?? null;
    $notes = $input['notes'] ?? '';
    $type = $input['type'] ?? null; // 'unica' o 'recurrente'

    // ✅ CORRECCIÓN: Se comprueba que al menos uno de los dos (cliente o prospecto) tenga valor.
    if ((!$client_id && !$lead_id) || !$type) {
        $response['message'] = 'Faltan datos obligatorios (se requiere un cliente o un prospecto, y un tipo de cita).';
        echo json_encode($response);
        exit;
    }

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

            if (!$appointment_date || !$appointment_time) {
                $response['message'] = 'Faltan datos para cita única (appointment_date, appointment_time).';
                echo json_encode($response);
                exit;
            }

            $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' => 'Cita única agendada con éxito.'];

        } elseif ($type === 'recurrente') {
            $frequency = $input['frequency'] ?? null;
            $next_appointment_date = $input['next_appointment_date'] ?? null;

            if (!$frequency || !$next_appointment_date) {
                $response['message'] = 'Faltan datos para cita recurrente (frequency, next_appointment_date).';
                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' => 'Cita recurrente agendada con éxito.'];

        } else {
            $response['message'] = 'Tipo de cita no reconocido.';
        }

    } catch (PDOException $e) {
        $response['message'] = 'Error de base de datos al agendar cita: ' . $e->getMessage();
        error_log("Error al crear cita: " . $e->getMessage()); // Para depuración en el servidor
    }
}

echo json_encode($response);
?>