<?php
// Ubicación: db/agenda-booking-handler.php

ob_start();

ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);

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

session_set_cookie_params([
    'lifetime' => 86400,
    'path' => '/',
    'secure' => true, 
    'httponly' => true,
    'samesite' => 'Strict'
]);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$response = ['status' => 'error', 'message' => 'Unknown server error.'];

try {
    require_once __DIR__ . '/../core/api.php';
    global $pdo;

    $json_input = file_get_contents('php://input');
    $data = json_decode($json_input, true);

    if (!$data) throw new Exception('Invalid JSON data received.');

    if (isset($data['first_name'], $data['email'], $data['appointment_date'], $data['appointment_time'])) {
        
        $fname = trim($data['first_name']);
        $lname = trim($data['last_name'] ?? '');
        $email = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
        $phone = preg_replace('/[^0-9]/', '', $data['phone']);
        $date  = $data['appointment_date'];
        $time  = $data['appointment_time'];
        
        $address = trim($data['address_line'] ?? '');
        $city    = trim($data['city'] ?? '');
        $state   = trim($data['state'] ?? ''); 
        $zip     = trim($data['zip_code'] ?? '');

        if (!$email) throw new Exception('Invalid email address.');
        if (strlen($phone) < 7) throw new Exception('Invalid phone number.');

        $pdo->beginTransaction();

        try {
            // A. VERIFICAR DISPONIBILIDAD
            $check_sql = "SELECT COUNT(*) FROM unique_appointments 
                          WHERE appointment_date = ? AND appointment_time = ? 
                          AND status NOT IN ('cancelled', 'completed')"; 
            $stmt_check = $pdo->prepare($check_sql);
            $stmt_check->execute([$date, $time]);
            
            // NOTA: La lógica asume capacidad 1, si se implementa capacidad real, esta consulta debe ajustarse
            if ($stmt_check->fetchColumn() >= 1) {
                throw new Exception('Sorry, this time slot is already booked.');
            }

            // B. GESTIONAR CLIENTE O LEAD
            $client_id = null;
            $lead_id = null;

            // B1. Buscar en tabla 'clients'
            $stmt_find_client = $pdo->prepare("SELECT id FROM clients WHERE email = ? LIMIT 1");
            $stmt_find_client->execute([$email]);
            $client_row = $stmt_find_client->fetch(PDO::FETCH_ASSOC);

            if ($client_row) {
                $client_id = $client_row['id'];
            } else {
                // B2. Buscar en tabla 'leads'
                $stmt_find_lead = $pdo->prepare("SELECT id FROM leads WHERE email = ? LIMIT 1");
                $stmt_find_lead->execute([$email]);
                $lead_row = $stmt_find_lead->fetch(PDO::FETCH_ASSOC);

                if ($lead_row) {
                    $lead_id = $lead_row['id'];
                } else {
                    // B3. Crear nuevo Lead
                    $insert_lead = "INSERT INTO leads 
                        (user_id, first_name, last_name, email, phone, street_address, city, state_province, zip_code, source, created_at) 
                        VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, 'Booking System', NOW())";
                    
                    $stmt_lead = $pdo->prepare($insert_lead);
                    $stmt_lead->execute([$fname, $lname, $email, $phone, $address, $city, $state, $zip]);
                    $lead_id = $pdo->lastInsertId();
                }
            }

            // C. INSERTAR CITA CON TOKEN PÚBLICO
            $public_token = bin2hex(random_bytes(32));

            $insert_appt = "INSERT INTO unique_appointments 
                (user_id, client_id, lead_id, appointment_date, appointment_time, status, notes, public_token, created_at) 
                VALUES (1, ?, ?, ?, ?, 'pending', 'Booked From System', ?, NOW())";
            
            $stmt_insert = $pdo->prepare($insert_appt);
            $stmt_insert->execute([$client_id, $lead_id, $date, $time, $public_token]);

            $pdo->commit();
            
            $response = [
                'status' => 'success', 
                'message' => 'Appointment scheduled successfully!',
                'token' => $public_token 
            ];

        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            throw $e;
        }
    } else {
        throw new Exception('Missing required fields.');
    }

} catch (Throwable $e) {
    $response = [
        'status' => 'error', 
        'message' => 'Server Error: ' . $e->getMessage()
    ];
}

if (ob_get_length()) ob_end_clean();

echo json_encode($response);
exit;