<?php
/**
 * Módulo Leads - Perfil del Lead Ultra Luxury
 */

$started = false;
if (session_status() === PHP_SESSION_NONE) { session_start(); $started = true; }
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';
if (!function_exists('isLoggedIn')) {
    function isLoggedIn(){ return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']); }
}

$current_module = 'leads';

if (!isLoggedIn()) {
    header('Location: ' . get_base_path() . '/index.php?module=auth&action=login');
    exit;
}

$db = getDB();
$current_user_id = $_SESSION['user_id'] ?? 0;
// Función de permisos real (usando roles y permisos)
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;
        }
    }
}
$lead_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($lead_id <= 0) {
    header('Location: ' . get_base_path() . '/index.php?module=leads&error=invalid_id');
    exit;
}

// Obtener datos del lead con información extendida; si falla, usar consulta simple
$pdo_local = $db->getConnection();
$lead = null;

// Log de inicio del proceso
error_log("VIEW.PHP: Iniciando búsqueda de lead ID: $lead_id");

try {
    // Log de la consulta principal
    error_log("VIEW.PHP: Ejecutando consulta principal con JOINs para lead $lead_id");
    
    $stmt = $pdo_local->prepare(
        "SELECT l.*, 
                l.job_title AS position,
                u.username AS assigned_user,
                CONCAT(u.first_name, ' ', u.last_name) AS assigned_name,
                d.name AS desk_name
         FROM leads l
         LEFT JOIN users u ON l.assigned_to = u.id
         LEFT JOIN desks d ON l.desk_id = d.id
         WHERE l.id = ?"
    );
    $stmt->execute([$lead_id]);
    $lead = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($lead) {
        error_log("VIEW.PHP: ✓ Lead $lead_id encontrado con consulta principal");
    } else {
        error_log("VIEW.PHP: ⚠️ Consulta principal no devolvió resultados para lead $lead_id, intentando fallback");
    }
    
    // Si la consulta no devuelve resultados, intentar sin JOINs
    if (!$lead) {
        error_log("VIEW.PHP: Ejecutando consulta fallback para lead $lead_id");
        
        $stmt = $pdo_local->prepare("SELECT * FROM leads WHERE id = ? LIMIT 1");
        $stmt->execute([$lead_id]);
        $basic_lead = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($basic_lead) {
            error_log("VIEW.PHP: ✓ Lead $lead_id encontrado con consulta fallback");
            
            // Agregar manualmente los datos de usuario y desk
            $lead = $basic_lead;
            
            // Obtener datos del usuario asignado
            if ($lead['assigned_to']) {
                try {
                    error_log("VIEW.PHP: Obteniendo datos de usuario ID: " . $lead['assigned_to']);
                    $user_stmt = $pdo_local->prepare("SELECT username, CONCAT(first_name, ' ', last_name) AS full_name FROM users WHERE id = ?");
                    $user_stmt->execute([$lead['assigned_to']]);
                    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
                    if ($user) {
                        $lead['assigned_user'] = $user['username'];
                        $lead['assigned_name'] = $user['full_name'];
                        error_log("VIEW.PHP: ✓ Datos de usuario obtenidos: " . $user['username']);
                    } else {
                        error_log("VIEW.PHP: ⚠️ Usuario ID " . $lead['assigned_to'] . " no encontrado");
                    }
                } catch (Exception $e) {
                    error_log("VIEW.PHP: ❌ Error obteniendo usuario: " . $e->getMessage());
                    // Si falla, dejar valores por defecto
                    $lead['assigned_user'] = null;
                    $lead['assigned_name'] = null;
                }
            }
            
            // Obtener datos del desk
            if ($lead['desk_id']) {
                try {
                    error_log("VIEW.PHP: Obteniendo datos de desk ID: " . $lead['desk_id']);
                    $desk_stmt = $pdo_local->prepare("SELECT name FROM desks WHERE id = ?");
                    $desk_stmt->execute([$lead['desk_id']]);
                    $desk = $desk_stmt->fetch(PDO::FETCH_ASSOC);
                    if ($desk) {
                        $lead['desk_name'] = $desk['name'];
                        error_log("VIEW.PHP: ✓ Datos de desk obtenidos: " . $desk['name']);
                    } else {
                        error_log("VIEW.PHP: ⚠️ Desk ID " . $lead['desk_id'] . " no encontrado");
                    }
                } catch (Exception $e) {
                    error_log("VIEW.PHP: ❌ Error obteniendo desk: " . $e->getMessage());
                    // Si falla, dejar valores por defecto
                    $lead['desk_name'] = null;
                }
            }
            
            // Agregar position si no existe
            if (!isset($lead['position'])) {
                $lead['position'] = $lead['job_title'] ?? null;
            }
        } else {
            error_log("VIEW.PHP: ❌ Lead $lead_id NO encontrado ni siquiera con consulta fallback");
        }
    }
} catch (Throwable $e) {
    // Log del error para debugging
    error_log("VIEW.PHP: ❌ Error crítico en consulta de lead $lead_id: " . $e->getMessage());
    error_log("VIEW.PHP: Stack trace: " . $e->getTraceAsString());
    $lead = false;
}

if (!$lead) {
    error_log("VIEW.PHP: ❌ LEAD NO ENCONTRADO - Redirigiendo a error. Lead ID: $lead_id");
    header('Location: ' . get_base_path() . '/index.php?module=leads&error=not_found&id=' . $lead_id);
    exit;
} else {
    error_log("VIEW.PHP: ✓ LEAD PROCESADO EXITOSAMENTE - ID: $lead_id, Nombre: " . ($lead['first_name'] ?? '') . " " . ($lead['last_name'] ?? ''));
}

// Validación de acceso: si no tiene 'leads.view_all', solo puede ver sus propios leads
$canViewAll = userHasPermissionByName($pdo_local, 'leads.view_all', $current_user_id);
if (!$canViewAll) {
    $assignedTo = isset($lead['assigned_to']) ? (int)$lead['assigned_to'] : 0;
    if ($assignedTo !== (int)$current_user_id) {
        header('Location: ' . get_base_path() . '/index.php?module=leads&error=no_access&id=' . $lead_id);
        exit;
    }
}

// Paginación para actividades
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 5;
$offset = ($page - 1) * $limit;

// Contar total de actividades para paginación
$total_activities = $db->selectOne(
    "SELECT COUNT(*) as total FROM lead_activities WHERE lead_id = ?",
    [$lead_id]
)['total'];

$total_pages = ceil($total_activities / $limit);

// Actividades del lead con paginaciÃ³n
$activities = $db->select(
    "SELECT la.*, u.username AS creator_username, 
            CONCAT(u.first_name, ' ', u.last_name) AS creator_name
     FROM lead_activities la
     LEFT JOIN users u ON la.created_by = u.id
     WHERE la.lead_id = ?
     ORDER BY la.created_at DESC
     LIMIT ? OFFSET ?",
    [$lead_id, $limit, $offset]
);

// EstadÃ­sticas del lead
$stats = $db->selectOne(
    "SELECT 
        COUNT(CASE WHEN la.type = 'call' THEN 1 END) as total_calls,
        COUNT(CASE WHEN la.type = 'email' THEN 1 END) as total_emails,
        COUNT(CASE WHEN la.type = 'meeting' THEN 1 END) as total_meetings,
        COUNT(CASE WHEN la.type = 'task' AND la.status = 'completed' THEN 1 END) as completed_tasks,
        COUNT(CASE WHEN la.type = 'task' AND la.status = 'pending' THEN 1 END) as pending_tasks,
        MAX(la.created_at) as last_activity
     FROM lead_activities la
     WHERE la.lead_id = ?",
    [$lead_id]
);

// Permisos del usuario (variables ya definidas arriba)

$canViewEmailFull = userHasPermissionByName($pdo_local, 'leads.view_email_full', $current_user_id);
$canViewPhoneFull = userHasPermissionByName($pdo_local, 'leads.view_phone_full', $current_user_id);
$canClickToCall = userHasPermissionByName($pdo_local, 'voiso.click_to_call', $current_user_id);

// Preparar variables de layout para usar el diseÃ±o corporativo con menÃº lateral
$page_title = 'Perfil del Lead - ' . htmlspecialchars(trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? '')));
$module = 'leads';
$action = 'view';
$content_file = __DIR__ . '/view_content.php';

// Renderizar mediante el layout compartido que incluye el sidebar y estilos globales
include BASE_PATH . '/modules/shared/layout.php';
