<?php
require_once __DIR__ . '/../../database/config.php';
require_once __DIR__ . '/../../database/connection.php';

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Función de autenticación (definida si no existe)
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

// Establecer headers para JSON
header('Content-Type: application/json');

// Verificar autenticación
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

// Obtener parámetros
$lead_id = isset($_GET['lead_id']) ? (int)$_GET['lead_id'] : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 5; // Número de actividades por página

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

try {
    $db = getDB();
    $conn = $db->getConnection();
    
    // Calcular offset
    $offset = ($page - 1) * $per_page;
    
    // Obtener el total de actividades
    $count_sql = "SELECT COUNT(*) FROM lead_activities WHERE lead_id = ?";
    $count_stmt = $conn->prepare($count_sql);
    $count_stmt->execute([$lead_id]);
    $total_activities = $count_stmt->fetchColumn();
    $total_pages = ceil($total_activities / $per_page);
    
    // Obtener las actividades para esta página
    $sql = "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 ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, $lead_id, PDO::PARAM_INT);
    $stmt->bindValue(2, $per_page, PDO::PARAM_INT);
    $stmt->bindValue(3, $offset, PDO::PARAM_INT);
    $stmt->execute();
    
    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Generar HTML de las actividades
    $html = '';
    if (empty($activities)) {
        $html = '
            <div class="empty-state">
                <div class="empty-icon">📝</div>
                <h4>No hay actividades registradas</h4>
                <p>Utiliza las acciones rápidas para comenzar a registrar actividades.</p>
            </div>';
    } else {
        $html .= '<div class="timeline-header">
                    <div class="timeline-column">Fecha de Creación</div>
                    <div class="timeline-column">Actividad</div>
                    <div class="timeline-column">Comentario</div>
                    <div class="timeline-column">Creado Por</div>
                  </div>';
        
        foreach ($activities as $activity) {
            $icon = match($activity['type']) {
                'call' => '📞',
                'email' => '📧',
                'meeting' => '🤝',
                'note' => '📝',
                'task' => '✅',
                'system' => '⚙️',
                default => '📌'
            };
            
            $typeName = match($activity['type']) {
                'call' => 'Llamada',
                'email' => 'Email',
                'meeting' => 'Reunión',
                'task' => 'Tarea',
                'note' => 'Nota',
                'system' => 'Sistema',
                default => 'Actividad'
            };
            
            $creator_name = !empty($activity['creator_name']) ? htmlspecialchars($activity['creator_name']) : 
                           (!empty($activity['creator_username']) ? htmlspecialchars($activity['creator_username']) : 'Sistema');
            
            $description = !empty($activity['description']) ? nl2br(htmlspecialchars($activity['description'])) : '';
            $date = date('d/m/Y H:i', strtotime($activity['created_at']));
            
            $html .= "
                <div class=\"timeline-row\">
                    <div class=\"timeline-column\" data-label=\"Fecha de Creación\">
                        <span class=\"activity-date\">{$date}</span>
                    </div>
                    <div class=\"timeline-column\" data-label=\"Actividad\">
                        <div class=\"activity-type\">
                            <span class=\"activity-icon\">{$icon}</span>
                            <span class=\"activity-name\">{$typeName}</span>
                        </div>
                    </div>
                    <div class=\"timeline-column\" data-label=\"Comentario\">
                        <div class=\"activity-description\">
                            {$description}
                        </div>
                    </div>
                    <div class=\"timeline-column\" data-label=\"Creado Por\">
                        <span class=\"activity-user\">{$creator_name}</span>
                    </div>
                </div>";
        }
    }
    
    // Generar HTML de paginación
    $pagination_html = '';
    if ($total_pages > 1) {
        $pagination_html = '<div class="pagination-container">';
        
        // Botón Anterior
        if ($page > 1) {
            $pagination_html .= '<button class="pagination-btn pagination-prev" onclick="loadActivitiesPage(' . ($page - 1) . ')" title="Página anterior">« Anterior</button>';
        }
        
        // Números de página
        $start_page = max(1, $page - 2);
        $end_page = min($total_pages, $page + 2);
        
        if ($start_page > 1) {
            $pagination_html .= '<button class="pagination-btn" onclick="loadActivitiesPage(1)">1</button>';
            if ($start_page > 2) {
                $pagination_html .= '<span class="pagination-dots">...</span>';
            }
        }
        
        for ($i = $start_page; $i <= $end_page; $i++) {
            $active_class = ($i == $page) ? ' pagination-active' : '';
            $pagination_html .= '<button class="pagination-btn' . $active_class . '" onclick="loadActivitiesPage(' . $i . ')">' . $i . '</button>';
        }
        
        if ($end_page < $total_pages) {
            if ($end_page < $total_pages - 1) {
                $pagination_html .= '<span class="pagination-dots">...</span>';
            }
            $pagination_html .= '<button class="pagination-btn" onclick="loadActivitiesPage(' . $total_pages . ')">' . $total_pages . '</button>';
        }
        
        // Botón Siguiente
        if ($page < $total_pages) {
            $pagination_html .= '<button class="pagination-btn pagination-next" onclick="loadActivitiesPage(' . ($page + 1) . ')" title="Página siguiente">Siguiente »</button>';
        }
        
        $pagination_html .= '</div>';
    }
    
    echo json_encode([
        'success' => true,
        'html' => $html,
        'pagination_html' => $pagination_html,
        'total_pages' => $total_pages,
        'current_page' => $page,
        'total_activities' => $total_activities
    ]);
    
} catch (PDOException $e) {
    error_log("Error al cargar actividades: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error al cargar actividades']);
}
?>