<?php

namespace App\Controllers;

use App\Services\Database;

class ApiController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Extender sesión actual
     */
    public function extendSession()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar autenticación
            if (!isset($_SESSION['user'])) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            // Verificar método
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                http_response_code(405);
                echo json_encode(['success' => false, 'message' => 'Método no permitido']);
                return;
            }

            // Validar CSRF token
            $csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
            if ($csrfToken !== ($_SESSION['csrf_token'] ?? '')) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Token CSRF inválido']);
                return;
            }

            // Actualizar tiempo de última actividad en la sesión
            $_SESSION['last_activity'] = time();
            
            // Actualizar en base de datos si existe registro de sesión
            if (isset($_SESSION['session_id'])) {
                $db = Database::getInstance();
                $stmt = $db->prepare("
                    UPDATE sessions 
                    SET last_activity = NOW(), expires_at = DATE_ADD(NOW(), INTERVAL 20 MINUTE)
                    WHERE id = ? AND user_id = ?
                ");
                $stmt->execute([$_SESSION['session_id'], $_SESSION['user']['id']]);
            }

            echo json_encode([
                'success' => true, 
                'message' => 'Sesión extendida',
                'expires_in' => 20 * 60 // 20 minutos en segundos
            ]);

        } catch (\Exception $e) {
            error_log("Error extending session: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }

    /**
     * Verificar estado de la sesión
     */
    public function sessionStatus()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar si hay sesión activa
            if (!isset($_SESSION['user'])) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            $currentTime = time();
            $lastActivity = $_SESSION['last_activity'] ?? $currentTime;
            $timeElapsed = $currentTime - $lastActivity;
            $maxInactivity = 20 * 60; // 20 minutos

            if ($timeElapsed > $maxInactivity) {
                // Sesión expirada
                http_response_code(401);
                echo json_encode([
                    'success' => false, 
                    'message' => 'Sesión expirada',
                    'expired' => true
                ]);
                return;
            }

            // Sesión válida
            echo json_encode([
                'success' => true,
                'message' => 'Sesión activa',
                'time_left' => $maxInactivity - $timeElapsed,
                'expires_in' => $maxInactivity - $timeElapsed
            ]);

        } catch (\Exception $e) {
            error_log("Error checking session status: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }

    /**
     * Obtener estadísticas del dashboard
     */
    public function dashboardStats()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar autenticación
            if (!$this->authMiddleware->requireAuth()) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            $db = Database::getInstance();
            
            $stats = [
                'users' => [
                    'total' => $db->query("SELECT COUNT(*) as count FROM users")->fetch()['count'],
                    'active' => $db->query("SELECT COUNT(*) as count FROM users WHERE is_active = 1")->fetch()['count'],
                    'recent_logins' => $db->query("
                        SELECT COUNT(*) as count 
                        FROM users 
                        WHERE last_login >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                    ")->fetch()['count']
                ],
                'roles' => [
                    'total' => $db->query("SELECT COUNT(*) as count FROM roles")->fetch()['count'],
                    'with_users' => $db->query("
                        SELECT COUNT(DISTINCT role_id) as count 
                        FROM users 
                        WHERE role_id IS NOT NULL
                    ")->fetch()['count']
                ],
                'sessions' => [
                    'active' => $db->query("
                        SELECT COUNT(*) as count 
                        FROM sessions 
                        WHERE expires_at > NOW()
                    ")->fetch()['count']
                ]
            ];

            echo json_encode(['success' => true, 'stats' => $stats]);

        } catch (\Exception $e) {
            error_log("Error getting dashboard stats: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }

    /**
     * Buscar usuarios (para autocompletado)
     */
    public function searchUsers()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar autenticación y permisos
            if (!isset($_SESSION['user'])) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            $user = $_SESSION['user'];
            if (!in_array($user['role_name'] ?? '', ['super_admin', 'admin'])) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Permisos insuficientes']);
                return;
            }

            $query = $_GET['q'] ?? '';
            $limit = min(intval($_GET['limit'] ?? 10), 50); // Máximo 50 resultados

            if (strlen($query) < 2) {
                echo json_encode(['success' => true, 'users' => []]);
                return;
            }

            $db = Database::getInstance();
            $stmt = $db->prepare("
                SELECT u.id, u.first_name, u.last_name, u.email, 
                       r.display_name as role_name, u.is_active
                FROM users u
                LEFT JOIN roles r ON u.role_id = r.id
                WHERE u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?
                ORDER BY u.first_name, u.last_name
                LIMIT ?
            ");
            
            $searchTerm = "%{$query}%";
            $stmt->execute([$searchTerm, $searchTerm, $searchTerm, $limit]);
            $users = $stmt->fetchAll();

            echo json_encode(['success' => true, 'users' => $users]);

        } catch (\Exception $e) {
            error_log("Error searching users: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }

    /**
     * Obtener notificaciones del usuario
     */
    public function getNotifications()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar autenticación
            if (!$this->authMiddleware->requireAuth()) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            $userId = $_SESSION['user']['id'];
            $limit = min(intval($_GET['limit'] ?? 20), 100);

            $db = Database::getInstance();
            
            // Por ahora retornamos notificaciones de ejemplo
            // En el futuro esto vendría de una tabla de notificaciones
            $notifications = [
                [
                    'id' => 1,
                    'type' => 'info',
                    'title' => 'Bienvenido al Sistema',
                    'message' => 'Tu cuenta ha sido activada correctamente.',
                    'created_at' => date('Y-m-d H:i:s'),
                    'read' => false
                ]
            ];

            echo json_encode(['success' => true, 'notifications' => $notifications]);

        } catch (\Exception $e) {
            error_log("Error getting notifications: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }

    /**
     * Marcar notificación como leída
     */
    public function markNotificationRead()
    {
        header('Content-Type: application/json');
        
        try {
            // Verificar autenticación
            if (!$this->authMiddleware->requireAuth()) {
                http_response_code(401);
                echo json_encode(['success' => false, 'message' => 'No autenticado']);
                return;
            }

            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                http_response_code(405);
                echo json_encode(['success' => false, 'message' => 'Método no permitido']);
                return;
            }

            $notificationId = $_POST['notification_id'] ?? '';
            
            if (empty($notificationId)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'ID de notificación requerido']);
                return;
            }

            // TODO: Implementar lógica para marcar notificación como leída
            // Por ahora solo retornamos éxito
            
            echo json_encode(['success' => true, 'message' => 'Notificación marcada como leída']);

        } catch (\Exception $e) {
            error_log("Error marking notification as read: " . $e->getMessage());
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error interno del servidor']);
        }
    }
}