<?php

namespace App\Controllers\Admin;

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

class Faucet extends AdminController
{
    public function index()
    {
        $faucetHistoryModel = new FaucetHistoryModel();
        $userModel = new UserModel();
        
        // 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
        $query = $faucetHistoryModel->select('faucet_history.*, users.email as user_email')
                                  ->join('users', 'users.id = faucet_history.user_id', 'left');
        
        // Apply search filter
        if (!empty($search)) {
            $query = $query->groupStart()
                          ->like('users.email', $search)
                          ->orLike('faucet_history.id', $search)
                          ->groupEnd();
        }
        
        // Apply sorting - map created_at to time_stamp
        $sortColumn = $sort === 'created_at' ? 'time_stamp' : $sort;
        $query = $query->orderBy($sortColumn, $order);
        
        // Get faucet history with pagination
        $faucetHistory = $query->findAll($perPage, $offset);
        $totalHistory = $query->countAllResults(false);
        
        // Get statistics in one optimized query
        $today = date('Y-m-d');
        $faucetStats = $faucetHistoryModel->select('
            COUNT(*) as total_claims,
            SUM(CASE WHEN DATE(time_stamp) = "' . $today . '" THEN 1 ELSE 0 END) as today_claims,
            COUNT(DISTINCT user_id) as unique_users
        ')->first();
        
        $stats = [
            'total_claims' => $faucetStats['total_claims'] ?? 0,
            'today_claims' => $faucetStats['today_claims'] ?? 0,
            'unique_users' => $faucetStats['unique_users'] ?? 0
        ];
        
        $this->data['faucet_history'] = $faucetHistory;
        $this->data['stats'] = $stats;
        $this->data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($totalHistory / $perPage),
            'total_history' => $totalHistory,
            'per_page' => $perPage
        ];
        $this->data['filters'] = [
            'search' => $search,
            'sort' => $sort,
            'order' => $order
        ];
        
        $this->data['title'] = 'Faucet Management';
        return $this->render_admin('admin/faucet', $this->data);
    }
    
    public function clearHistory()
    {
        if ($this->request->getMethod() === 'post') {
            $faucetHistoryModel = new FaucetHistoryModel();
            $faucetHistoryModel->truncate();
            
            return redirect()->to('/admin/faucet')->with('success', 'Faucet history cleared successfully!');
        }
        
        return redirect()->to('/admin/faucet');
    }
}
