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