<?php 
header('Content-Type: application/json; charset=utf-8');

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

$response = ['success' => false, 'message' => 'Error desconocido'];

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

    if (!isset($pdo)) {
        throw new Exception("Error: La conexión a BD no se estableció correctamente.");
    }

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

    if (!$data) {
        throw new Exception('No se recibieron datos JSON válidos.');
    }

    if (!isset($data['id']) || !is_numeric($data['id'])) {
        throw new Exception('ID DE PROSPECTO INVALIDO O FALTANTE');
    }

    $id = (int)$data['id'];
    $first_name = trim($data['first_name'] ?? '');
    $last_name = trim($data['last_name'] ?? '');
    $company = !empty($data['company']) ? trim($data['company']) : null;
    $email = !empty($data['email']) ? filter_var(trim($data['email']), FILTER_SANITIZE_EMAIL) : null;
    
    $phone = !empty($data['phone']) ? preg_replace('/[^0-9]/', '', $data['phone']) : null;
    $mobile = !empty($data['mobile']) ? preg_replace('/[^0-9]/', '', $data['mobile']) : null;
    
    $source = $data['source'] ?? 'Desconocida';
    $status = $data['status'] ?? 'New';
    $priority = $data['priority'] ?? 'Medium';
    
    $street_address = !empty($data['street_address']) ? trim($data['street_address']) : null;
    $city = !empty($data['city']) ? trim($data['city']) : null;
    $state_province = !empty($data['state_province']) ? trim($data['state_province']) : null;
    $zip_code = !empty($data['zip_code']) ? trim($data['zip_code']) : null;
    
    $lost_reason = $data['lost_reason'] ?? null;
    
    if (strpos($status, 'Perdido') === false && strpos($status, 'Archivado') === false) {
        $lost_reason = null;
    }

    $sql_check = "SELECT id FROM leads WHERE id != :id AND (
        (email IS NOT NULL AND email != '' AND email = :email) OR 
        (phone IS NOT NULL AND phone != '' AND phone = :phone)
    ) LIMIT 1";
    
    $stmt = $pdo->prepare($sql_check);
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->bindValue(':email', $email, $email ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':phone', $phone, $phone ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->execute();

    if ($stmt->fetch()) {
        throw new Exception('El Email o Teléfono ya están registrados en otro prospecto.');
    }

    $sql_update = "UPDATE leads SET 
        first_name = :fn, last_name = :ln, company = :co, 
        email = :em, phone = :ph, mobile = :mo, 
        source = :so, status = :st, priority = :pr,
        street_address = :addr, city = :ci, state_province = :state, zip_code = :zip,
        lost_reason = :lr, 
        updated_at = NOW()
        WHERE id = :id";

    $stmt = $pdo->prepare($sql_update);
    $stmt->bindValue(':fn', $first_name);
    $stmt->bindValue(':ln', $last_name);
    $stmt->bindValue(':co', $company, $company ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':em', $email, $email ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':ph', $phone, $phone ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':mo', $mobile, $mobile ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':so', $source);
    $stmt->bindValue(':st', $status);
    $stmt->bindValue(':pr', $priority);
    $stmt->bindValue(':addr', $street_address, $street_address ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':ci', $city, $city ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':state', $state_province, $state_province ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':zip', $zip_code, $zip_code ? PDO::PARAM_STR : PDO::PARAM_NULL);
    $stmt->bindValue(':lr', $lost_reason, $lost_reason ? PDO::PARAM_STR : PDO::PARAM_NULL); 
    $stmt->bindValue(':id', $id, PDO::PARAM_INT);

    if ($stmt->execute()) {
        $response['success'] = true;
        $response['message'] = 'PROSPECTO ACTUALIZADO';
        $response['lost_reason'] = $lost_reason;
    } else {
        throw new Exception('Error SQL al actualizar base de datos.');
    }

} catch (Exception $e) {
    error_log("Error Leads Update: " . $e->getMessage());
    $response['success'] = false;
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
exit;
?>