<?php
// Endpoint: Obtener datos de un lead por ID (JSON)
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

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

if (!function_exists('isLoggedIn')) {
    function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
}

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

$lead_id = isset($_GET['lead_id']) ? intval($_GET['lead_id']) : 0;
if ($lead_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ID de lead inválido']);
    exit;
}

try {
    $db = getDB();
    $pdo = $db->getConnection();
    $current_user_id = (int)($_SESSION['user_id'] ?? 0);

    if (!function_exists('userHasPermissionByName')) {
        function userHasPermissionByName($pdo, $permName, $userId) {
            if (empty($userId)) return false;
            try {
                $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
                $stmt->execute([$userId, $permName]);
                return (bool)$stmt->fetchColumn();
            } catch (Exception $e) { return false; }
        }
    }

    $stmt = $pdo->prepare(
        "SELECT l.*, 
                CONCAT(l.first_name, ' ', l.last_name) AS full_name,
                d.name AS desk_name,
                d.color AS desk_color,
                u.username AS assigned_user,
                CONCAT(u.first_name, ' ', u.last_name) AS assigned_name
         FROM leads l
         LEFT JOIN desks d ON l.desk_id = d.id
         LEFT JOIN users u ON l.assigned_to = u.id
         WHERE l.id = ?"
    );
    $stmt->execute([$lead_id]);
    $lead = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$lead) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Lead no encontrado']);
        exit;
    }

    // Aplicar máscara según permisos
    $canViewEmailFull = userHasPermissionByName($pdo, 'lead_email_mask', $current_user_id)
        || userHasPermissionByName($pdo, 'leads.view_email_full', $current_user_id);
    $canViewPhoneFull = userHasPermissionByName($pdo, 'lead_number_mask', $current_user_id)
        || userHasPermissionByName($pdo, 'leads.view_phone_full', $current_user_id);

    $email = $lead['email'] ?? '';
    $phone = $lead['phone'] ?? '';

    if (!$canViewEmailFull && function_exists('maskEmail')) {
        $email = maskEmail($email);
    }
    if (!$canViewPhoneFull && function_exists('maskPhone')) {
        $phone = maskPhone($phone);
    }

    $payload = [
        'id' => (int)$lead['id'],
        'first_name' => $lead['first_name'] ?? '',
        'last_name' => $lead['last_name'] ?? '',
        'full_name' => trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? '')),
        'email' => $email,
        'phone' => $phone,
        'country' => $lead['country'] ?? '',
        'status' => $lead['status'] ?? '',
        'desk_name' => $lead['desk_name'] ?? '',
        'desk_color' => $lead['desk_color'] ?? '#999',
        'assigned_name' => $lead['assigned_name'] ?? ($lead['assigned_user'] ?? ''),
    ];

    echo json_encode(['success' => true, 'lead' => $payload]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error obteniendo lead', 'error' => $e->getMessage()]);
}
?>