<?php
namespace Models;
require_once __DIR__ . '/../models/Database.php';
use PDO;

class ActivityLog
{
    private static $pdo;

// Initialiser la connexion à la base de données
    public static function init() {
        if (self::$pdo == null) {
            self::$pdo = Database::getInstance()->getConnection();
            self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    }

    /**
     * Enregistre une nouvelle activité
     */
    public function create(array $data): bool
    {
        $query = "INSERT INTO activity_logs 
                 (user_id, action, description, ip_address, user_agent, created_at) 
                 VALUES (:user_id, :action, :description, :ip_address, :user_agent, NOW())";
        self::init();
        $stmt = self::$pdo->prepare($query);
        return $stmt->execute([
            ':user_id'     => $data['user_id'] ?? null,
            ':action'      => $data['action'],
            ':description' => $data['description'],
            ':ip_address'  => $data['ip_address'] ?? $_SERVER['REMOTE_ADDR'],
            ':user_agent'  => $data['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    }

    /**
     * Récupère les activités paginées
     */
    public function getAll(int $page = 1, int $perPage = 20): array
    {
        $offset = ($page - 1) * $perPage;
        self::init();
        $stmt = self::$pdo->prepare(
            "SELECT * FROM activity_logs 
             ORDER BY created_at DESC 
             LIMIT :limit OFFSET :offset"
        );
        
        $stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Purge les logs anciens
     */
    public function purgeOldLogs(int $days = 30): int
    {
        self::init();
        $stmt = self::$pdo->prepare(
            "DELETE FROM activity_logs 
             WHERE created_at < DATE_SUB(NOW(), INTERVAL :days DAY)"
        );
        $stmt->execute([':days' => $days]);
        return $stmt->rowCount();
    }

    /**
     * Statistiques des activités
     */
    public function getStats(): array
    {
        self::init();
        $stmt = self::$pdo->query(
            "SELECT 
                COUNT(*) as total,
                COUNT(DISTINCT user_id) as unique_users,
                action 
             FROM activity_logs 
             GROUP BY action"
        );
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
    /**
 * Récupère la date de la dernière activité
 */
public static function getLastDate() {
    self::init();
    $stmt = self::$pdo->query("SELECT MAX(created_at) as last_date FROM activity_logs");
    return $stmt->fetchColumn();
}

public static function getRecent($limit = 5) {
    self::init();
    $stmt = self::$pdo->prepare("SELECT * FROM activity_logs ORDER BY created_at DESC LIMIT :limit");
    $stmt->bindValue(':limit', (int)$limit, \PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}


}