<?php

namespace App\Controllers\Admin;

use App\Controllers\AdminController;
use App\Models\UserModel;
use App\Models\PayoutModel;
use App\Models\FaucetHistoryModel;
use App\Models\ShortlinkHistoryModel;

class Dashboard extends AdminController
{
    public function index()
    {
        $this->data['title'] = 'Admin Dashboard';
        //check update
        require_once APPPATH . 'Config/Script.php';
        $version =  \Config\Script::$version;
        $product =  \Config\Script::$product;
        $this->data['update_available'] = check_update($product, $version);

        // Get statistics
        $userModel = new UserModel();
        $payoutModel = new PayoutModel();
        $faucetHistoryModel = new FaucetHistoryModel();
        $shortlinkHistoryModel = new ShortlinkHistoryModel();

        $sevenDaysAgo = date('Y-m-d H:i:s', strtotime('-7 days'));
        $todayStart = date('Y-m-d 00:00:00');
        
        $userStats = $userModel->select('
            COUNT(*) as total_users,
            SUM(CASE WHEN last_active > "' . $sevenDaysAgo . '" THEN 1 ELSE 0 END) as active_users,
            SUM(CASE WHEN registered_date >= "' . $todayStart . '" THEN 1 ELSE 0 END) as new_users_today
        ')->first();
        
        $this->data['totalUsers'] = $userStats['total_users'] ?? 0;
        $this->data['activeUsers'] = $userStats['active_users'] ?? 0;
        $this->data['newUsersToday'] = $userStats['new_users_today'] ?? 0;
        
        // Get recent users (separate query for recent users only)
        $this->data['recentUsers'] = $userModel->select('id, email, ip, currency, registered_date, last_active')
            ->orderBy('registered_date', 'DESC')
            ->findAll(10);

        // Payout statistics
        $this->data['totalPayouts'] = $payoutModel->countAllResults();
        $this->data['totalPaidAmount'] = $payoutModel->selectSum('amount')->first()['amount'] ?? 0;

        // Recent payouts
        $this->data['recentPayouts'] = $payoutModel->orderBy('time_stamp', 'DESC')->findAll(10);

        return $this->render_admin('admin/dashboard', $this->data);
    }
}
