<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    require_once __DIR__ . '/../core/api.php';

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

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

    if (!isset($data['prospect_id']) || empty($data['prospect_id'])) {
        throw new Exception('ID DE PROSPECTO REQUERIDO');
    }

    $prospectId = filter_var($data['prospect_id'], FILTER_VALIDATE_INT);

    $pdo->beginTransaction();

    // 1. Obtener datos del Lead
    $stmt = $pdo->prepare("SELECT 
        first_name, last_name, company, email, phone, mobile, 
        street_address, city, state_province, zip_code, created_at, user_id
        FROM leads WHERE id = ?");
    $stmt->execute([$prospectId]);
    $prospect = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$prospect) {
        throw new Exception('El prospecto no existe en la base de datos.');
    }

    // 2. Insertar en Clientes
    $sql_client = "INSERT INTO clients (
            user_id, first_name, last_name, company, email, phone, mobile, 
            street_address, city, state_province, zip_code, created_at, is_recurring
        ) VALUES (
            :uid, :fn, :ln, :co, :em, :ph, :mo, 
            :addr, :ci, :st, :zip, :created, 0
        )";

    $insertClientStmt = $pdo->prepare($sql_client);
    
    $phone = !empty($prospect['phone']) ? $prospect['phone'] : null;
    $mobile = !empty($prospect['mobile']) ? $prospect['mobile'] : null;
    
    $insertClientStmt->execute([
        ':uid' => $prospect['user_id'] ?? 1,
        ':fn' => $prospect['first_name'],
        ':ln' => $prospect['last_name'],
        ':co' => $prospect['company'],
        ':em' => $prospect['email'],
        ':ph' => $phone,
        ':mo' => $mobile,
        ':addr' => $prospect['street_address'],
        ':ci' => $prospect['city'],
        ':st' => $prospect['state_province'],
        ':zip' => $prospect['zip_code'],
        ':created' => $prospect['created_at']
    ]);

    $newClientId = $pdo->lastInsertId();

    // 3. Borrar de Leads
    $deleteLeadStmt = $pdo->prepare("DELETE FROM leads WHERE id = ?");
    $deleteLeadStmt->execute([$prospectId]);

    $pdo->commit();

    $response = [
        'success' => true,
        'message' => 'CONVERTIDO A CLIENTE CORRECTAMENTE',
        'new_client_id' => $newClientId
    ];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    
    $errMsg = $e->getMessage();
    
    if (strpos($errMsg, 'Duplicate entry') !== false) {
        if (strpos($errMsg, 'email') !== false) {
            $response = ['success' => false, 'message' => 'Error: El EMAIL ya existe en la lista de clientes.'];
        } elseif (strpos($errMsg, 'phone') !== false) {
            $response = ['success' => false, 'message' => 'Error: El TELÉFONO ya existe en la lista de clientes.'];
        } elseif (strpos($errMsg, 'mobile') !== false) {
            $response = ['success' => false, 'message' => 'Error: El CELULAR ya existe en la lista de clientes.'];
        } else {
            $response = ['success' => false, 'message' => 'Error: Datos duplicados (Email o Teléfono ya existen).'];
        }
    } else {
        error_log("DB Error Converting: " . $errMsg);
        $response = ['success' => false, 'message' => 'Error de Base de Datos: ' . $errMsg];
    }
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $response = ['success' => false, 'message' => $e->getMessage()];
}

if (ob_get_length()) ob_clean();
echo json_encode($response);
exit;
?>