<?php

namespace App\Controllers\Admin;

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

class Users extends AdminController
{
    public function index()
    {
        $userModel = new UserModel();
        $payoutModel = new PayoutModel();
        
        // Get search parameters
        $search = $this->request->getGet('search') ?? '';
        $sort = $this->request->getGet('sort') ?? 'id';
        $order = $this->request->getGet('order') ?? 'DESC';
        
        // Get pagination parameters
        $page = $this->request->getGet('page') ?? 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        // Build query with JOIN to get referrer email
        $query = $userModel->select('users.*, referrers.email as referrer_email, referrers.id as referrer_id')
                          ->join('users as referrers', 'referrers.id = users.ref', 'left');
        
        // Apply search filter
        if (!empty($search)) {
            $query = $query->groupStart()
                          ->like('users.email', $search)
                          ->orLike('users.ip', $search)
                          ->orLike('users.id', $search)
                          ->groupEnd();
        }
        
        // Apply sorting
        $query = $query->orderBy($sort, $order);
        
        // Get users with pagination
        $users = $query->findAll($perPage, $offset);
        $totalUsers = $query->countAllResults(false);
        
        // Get user statistics in one optimized query
        $today = date('Y-m-d');
        $userStats = $userModel->select('
            COUNT(*) as total_users,
            SUM(CASE WHEN DATE(registered_date) = "' . $today . '" THEN 1 ELSE 0 END) as new_today
        ')->first();
        
        $totalPages = ceil($totalUsers / $perPage);
        
        // Get total earned amount
        $totalEarned = $payoutModel->selectSum('amount')->first()['amount'] ?? 0;
        
        $stats = [
            'total_users' => $userStats['total_users'] ?? 0,
            'new_today' => $userStats['new_today'] ?? 0,
            'total_earned' => $totalEarned
        ];
        
        $this->data['users'] = $users;
        $this->data['stats'] = $stats;
        $this->data['pagination'] = [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_users' => $totalUsers,
            'per_page' => $perPage
        ];
        $this->data['filters'] = [
            'search' => $search,
            'sort' => $sort,
            'order' => $order
        ];
        
        $this->data['title'] = 'Users Management';
        return $this->render_admin('admin/users', $this->data);
    }
}
