<?php

namespace App\Controllers\Admin;

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

class Payouts extends AdminController
{
    public function index()
    {
        $payoutModel = new PayoutModel();
        $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 = $payoutModel->select('*');
        
        // Apply search filter
        if (!empty($search)) {
            $query = $query->groupStart()
                          ->like('payouts.address', $search)
                          ->orLike('payouts.currency', $search)
                          ->orLike('payouts.id', $search)
                          ->groupEnd();
        }
        
        // Apply sorting - map created_at to time_stamp
        $sortColumn = $sort === 'time_stamp' ? 'time_stamp' : $sort;
        $query = $query->orderBy($sortColumn, $order);
        
        // Get payouts with pagination
        $payouts = $query->findAll($perPage, $offset);
        $totalPayouts = $query->countAllResults(false);
        
        // Get statistics in one optimized query
        $today = date('Y-m-d');
        $payoutStats = $payoutModel->select('
            COUNT(*) as total_payouts,
            SUM(amount) as total_amount,
            SUM(CASE WHEN DATE(time_stamp) = "' . $today . '" THEN 1 ELSE 0 END) as today_payouts,
            SUM(CASE WHEN DATE(time_stamp) = "' . $today . '" THEN amount ELSE 0 END) as today_amount
        ')->first();
        
        $stats = [
            'total_payouts' => $payoutStats['total_payouts'] ?? 0,
            'total_amount' => $payoutStats['total_amount'] ?? 0,
            'today_payouts' => $payoutStats['today_payouts'] ?? 0,
            'today_amount' => $payoutStats['today_amount'] ?? 0
        ];
        
        $this->data['payouts'] = $payouts;
        $this->data['stats'] = $stats;
        $this->data['pagination'] = [
            'current_page' => $page,
            'total_pages' => ceil($totalPayouts / $perPage),
            'total_payouts' => $totalPayouts,
            'per_page' => $perPage
        ];
        $this->data['filters'] = [
            'search' => $search,
            'sort' => $sort,
            'order' => $order
        ];
        
        $this->data['title'] = 'Payouts Management';
        return $this->render_admin('admin/payouts', $this->data);
    }
}
