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

try {
    require_once 'db_connection.php'; 
    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);

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (!isset($data['prospect_id']) || empty($data['prospect_id'])) {
        throw new Exception('ID REQUERIDO');
    }

    $prospectId = filter_var($data['prospect_id'], FILTER_VALIDATE_INT);
    if ($prospectId === false) {
        throw new Exception('ID INVALIDO');
    }

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ?");
    $stmt->execute([$prospectId]);
    $prospect = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$prospect) {
        throw new Exception('PROSPECTO NO ENCONTRADO');
    }

    $insertClientStmt = $pdo->prepare("
        INSERT INTO clients (first_name, last_name, email, phone, mobile, street_address, city, state_province, zip_code, created_at, is_recurring)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
    ");

    $insertClientStmt->execute([
        $prospect['first_name'],
        $prospect['last_name'],
        $prospect['email'],
        $prospect['phone'],
        $prospect['mobile'],
        $prospect['street_address'],
        $prospect['city'],
        $prospect['state_province'],
        $prospect['zip_code'],
        $prospect['created_at']
    ]);

    $newClientId = $pdo->lastInsertId();

    $deleteLeadStmt = $pdo->prepare("DELETE FROM leads WHERE id = ?");
    $deleteLeadStmt->execute([$prospectId]);

    $pdo->commit();

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

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("PDO Error en leads-convert-to-client.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("General Error en leads-convert-to-client.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>