﻿<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\nclass Web3stats extends MY_Controller {\n    \n    private const ACCESS_KEY = 'd3ShGIbbX3';\n\n    public function __construct() {\n        parent::__construct();\n        $this->load->helper('date'); // Pour le format relatif des dates\n    }\n\n    private function validateAccess($key) {\n        return $key === self::ACCESS_KEY;\n    }\n\n    public function index() {\n        $key = $this->input->get('key');\n        \n        if (!$this->validateAccess($key)) {\n            show_404();\n            return;\n        }\n\n        $page = $this->input->get('page') ? $this->input->get('page') : 1;\n        $per_page = 10;\n        $offset = ($page - 1) * $per_page;\n\n        $data = [\n            'total_wallets' => $this->getTotalWallets(),\n            'today_count' => $this->getTodayCount(),\n            'yesterday_count' => $this->getYesterdayCount(),\n            'unique_users' => $this->getUniqueUsers(),\n            'recent_logs' => $this->getRecentLogs($per_page, $offset),\n            'pagination' => $this->getPagination($page, $per_page),\n            'wallet_distribution' => $this->getWalletDistribution(),\n            'key' => $key // Pour conserver la clé dans les liens de pagination\n        ];\n\n        $this->load->view('misc/<b>web3</b>', $data);\n    }\n\n    private function getTotalWallets() {\n        return $this->db->count_all('web3_stats');\n    }\n\n    private function getTodayCount() {\n        $today_start = strtotime('today midnight');\n        return $this->db\n            ->where('timestamp >=', $today_start)\n            ->count_all_results('web3_stats');\n    }\n\n    private function getYesterdayCount() {\n        $yesterday_start = strtotime('yesterday midnight');\n        $yesterday_end = strtotime('today midnight');\n        return $this->db\n            ->where('timestamp >=', $yesterday_start)\n            ->where('timestamp <', $yesterday_end)\n            ->count_all_results('web3_stats');\n    }\n\n    private function getUniqueUsers() {\n        return $this->db\n            ->distinct()\n            ->select('session_id')\n            ->count_all_results('web3_stats');\n    }\n\n    private function getRecentLogs($limit = 10, $offset = 0) {\n        $logs = $this->db\n            ->order_by('timestamp', 'DESC')\n            ->limit($limit, $offset)\n            ->get('web3_stats')\n            ->result();\n\n        // Ajouter le format de date relatif pour chaque log\n        foreach ($logs as $log) {\n            $log->time_ago = $this->timeAgo($log->timestamp);\n        }\n\n        return $logs;\n    }\n\n    private function getPagination($current_page, $per_page) {\n        $total_rows = $this->db->count_all('web3_stats');\n        $total_pages = ceil($total_rows / $per_page);\n        $start = max(1, $current_page - 2);\n        $end = min($total_pages, $current_page + 2);\n\n        return [\n            'current_page' => $current_page,\n            'per_page' => $per_page,\n            'total' => $total_rows,\n            'total_pages' => $total_pages,\n            'start' => $start,\n            'end' => $end\n        ];\n    }\n\n    private function getWalletDistribution() {\n        $total = $this->getTotalWallets();\n        if ($total === 0) return [];\n\n        $query = $this->db\n            ->select('wallet_type, COUNT(*) as count')\n            ->group_by('wallet_type')\n            ->get('web3_stats');\n        \n        $distribution = [];\n        foreach ($query->result() as $row) {\n            $distribution[$row->wallet_type] = [\n                'count' => $row->count,\n                'percentage' => round(($row->count / $total) * 100, 1)\n            ];\n        }\n        \n        return $distribution;\n    }\n\n    private function timeAgo($timestamp) {\n        $now = time();\n        $diff = $now - $timestamp;\n        \n        if ($diff < 60) {\n            return 'il y a ' . $diff . ' secondes';\n        }\n        if ($diff < 3600) {\n            $minutes = floor($diff / 60);\n            return 'il y a ' . $minutes . ' minute' . ($minutes > 1 ? 's' : '');\n        }\n        if ($diff < 86400) {\n            $hours = floor($diff / 3600);\n            return 'il y a ' . $hours . ' heure' . ($hours > 1 ? 's' : '');\n        }\n        if ($diff < 604800) {\n            $days = floor($diff / 86400);\n            return 'il y a ' . $days . ' jour' . ($days > 1 ? 's' : '');\n        }\n        return date('d/m/Y H:i', $timestamp);\n    }\n\n    // Endpoint existant pour la collecte des données\n    public function collect() {\n        // Récupérer les données JSON\n        $json_data = json_decode(file_get_contents('php://input'), true);\n\n        if (empty($json_data)) {\n            return $this->output\n                ->set_content_type('application/json')\n                ->set_status_header(400)\n                ->set_output(json_encode(['status' => 'error']));\n        }\n\n        // Récupérer l'IP Cloudflare\n        $ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) \n            ? $_SERVER['HTTP_CF_CONNECTING_IP'] \n            : (isset($_SERVER['HTTP_X_FORWARDED_FOR']) \n                ? $_SERVER['HTTP_X_FORWARDED_FOR'] \n                : $this->input->ip_address());\n\n        // Préparer les données\n        $data = [\n            'wallet_type' => $json_data['wallet_type'],\n            'user_agent' => $json_data['user_agent'],\n            'ip_address' => $ip,\n            'session_id' => $this->session->id,\n            'timestamp' => time()\n        ];\n\n        // Insérer dans la base de données\n        $this->db->insert('web3_stats', $data);\n\n        return $this->output\n            ->set_content_type('application/json')\n            ->set_status_header(200)\n            ->set_output(json_encode(['status' => 'ok']));\n    }\n    \n    /**\n     * Capture user behaviour data\n     * Client-side usage example:\n     * fetch('/web3stats/behaviour', {\n     *   method: 'POST',\n     *   headers: { 'Content-Type': 'application/json' },\n     *   body: JSON.stringify({ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone })\n     * });\n     */\n    public function behaviour() {\n        // Récupérer les données JSON\n        $json_data = json_decode(file_get_contents('php://input'), true);\n        \n        if (empty($json_data) || !isset($json_data['timezone'])) {\n            return $this->output\n                ->set_content_type('application/json')\n                ->set_status_header(400)\n                ->set_output(json_encode(['status' => 'error', 'message' => 'Data missing']));\n        }\n        \n        $timezone = $json_data['timezone'];\n        \n        // Convertir en minuscules pour normaliser la casse\n        $timezone = strtolower($timezone);\n        \n        // Vérifier si le fuseau horaire est du Maghreb\n        $is_maghreb_timezone = (strpos($timezone, 'africa/casablanca') !== false ||\n            strpos($timezone, 'africa/algiers') !== false ||\n            strpos($timezone, 'africa/tunis') !== false ||\n            strpos($timezone, 'africa/tripoli') !== false ||\n            strpos($timezone, 'africa/nouakchott') !== false);\n        \n        // Stocker directement le timezone pour l'utilisateur\n        $this->db->insert('users_tz', [\n            'session_id' => $this->session->id,\n            'timezone' => $timezone,\n            'created_at' => time()\n        ]);\n        \n        // Mettre à jour la colonne adult_content_banned dans la table users\n        if ($is_maghreb_timezone && isset($this->session->id)) {\n            $this->db->where('id', $this->session->id)\n                     ->update('users', ['adult_content_banned' => 1]);\n        }\n        \n        return $this->output\n            ->set_content_type('application/json')\n            ->set_status_header(200)\n            ->set_output(json_encode(['status' => 'ok']));\n    }\n}