<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\MenuModel;
use App\Models\CommissionsPaidModel;
use CodeIgniter\Database\Exceptions\DataException;

class CommissionsPaid extends Controller
{
    public function index()
    {
        // 1. Ensure the user is logged in
        if (!service('auth')->loggedIn()) {
            return redirect()->to('/login');
        }

        // 2. Retrieve the current user entity
        $user = service('auth')->user();

        // 3. Check if user is admin (is_admin == 1).
        if ((int) $user->is_admin !== 1) {
            return redirect()->to('/')->with('error', 'Access denied: Admins only.');
        }

        // 4. Fetch the navigation menu:
        $menuModel = new MenuModel();
        $menuItems = $menuModel->orderBy('order', 'ASC')->findAll();

        // 5. Get the distinct payout batches (DESC for display, but we also want ASC for the chart data)
        $commissionsModel = new CommissionsPaidModel();

        // For dropdown, newest first:
        $distinctBatches = $commissionsModel
            ->select('payout_batch, from_date, to_date')
            ->groupBy('payout_batch')
            ->orderBy('payout_batch', 'DESC')
            ->findAll();

        // For chart, oldest first (so the line chart goes left -> right in chronological order)
        $batchesAsc = $commissionsModel
            ->select('payout_batch, from_date, to_date')
            ->groupBy('payout_batch')
            ->orderBy('payout_batch', 'ASC')
            ->findAll();

        // 6. Determine the selected batch/user from GET parameters
        $selectedBatch = $this->request->getGet('batch_id');
        $selectedUser  = $this->request->getGet('user_id');

        // If no batch is selected, default to the latest (first in $distinctBatches)
        if (!$selectedBatch && !empty($distinctBatches)) {
            $selectedBatch = $distinctBatches[0]['payout_batch'];
        }

        // 7. Build a query for data (for the main table)
        $builder = $commissionsModel
            ->select('commissions_paid.*, bbt_users.first_name, bbt_users.last_name')
            ->join('bbt_users', 'commissions_paid.user_id = bbt_users.id', 'left')
            ->orderBy('commissions_paid.id', 'ASC');

        if ($selectedBatch) {
            $builder->where('commissions_paid.payout_batch', $selectedBatch);
        }

        // 8. Get the distinct users for the selected batch (for the user filter)
        $distinctUsers = [];
        if ($selectedBatch) {
            $distinctUsersModel = new CommissionsPaidModel();
            $distinctUsers = $distinctUsersModel
                ->distinct()
                ->select('commissions_paid.user_id, bbt_users.first_name, bbt_users.last_name')
                ->join('bbt_users', 'commissions_paid.user_id = bbt_users.id', 'left')
                ->where('commissions_paid.payout_batch', $selectedBatch)
                ->orderBy('bbt_users.first_name', 'ASC')
                ->findAll();
        }

        // 9. Filter by selected user if not 'all'
        if ($selectedUser && $selectedUser !== 'all') {
            $builder->where('commissions_paid.user_id', $selectedUser);
        }

        // 10. Fetch the data for the main table
        $dataForSelectedBatch = $builder->findAll();

        // 11. Calculate the total sum of 'amount' for the displayed rows
        $totalSum = 0.0;
        foreach ($dataForSelectedBatch as $row) {
            $totalSum += floatval($row['amount']);
        }

        // 12. Calculate the total for each user (for the top-right summary)
        $amountsByUser = [];
        foreach ($dataForSelectedBatch as $row) {
            $uid = $row['user_id'];
            $userName = trim($row['first_name'] . ' ' . $row['last_name']);

            if (!isset($amountsByUser[$uid])) {
                $amountsByUser[$uid] = [
                    'name'  => $userName ?: 'Unknown',
                    'total' => 0,
                ];
            }

            $amountsByUser[$uid]['total'] += floatval($row['amount']);
        }

        // 13. Prepare line chart data for *all* batches across *all* users
        //     (irrespective of the filter above). We want to show a line
        //     where each batch is a point on the x-axis.
        //     We'll store user-based totals in $lineTotals[userId][batch] = total
        $allLineData = $commissionsModel
            ->select('user_id, payout_batch, SUM(amount) as batch_total')
            ->groupBy(['user_id', 'payout_batch'])
            ->orderBy('payout_batch', 'ASC')
            ->findAll();

        $lineTotals = [];
        foreach ($allLineData as $row) {
            $uid   = $row['user_id'];
            $batch = $row['payout_batch'];
            $amt   = floatval($row['batch_total']);

            if (!isset($lineTotals[$uid])) {
                $lineTotals[$uid] = [];
            }
            $lineTotals[$uid][$batch] = $amt;
        }

        // Also gather an overall total for each batch (all users combined)
        $allTotalsData = $commissionsModel
            ->select('payout_batch, SUM(amount) as batch_total')
            ->groupBy('payout_batch')
            ->orderBy('payout_batch', 'ASC')
            ->findAll();

        $allTotals = [];
        foreach ($allTotalsData as $row) {
            $batch = $row['payout_batch'];
            $amt   = floatval($row['batch_total']);
            $allTotals[$batch] = $amt;
        }

        // 14. Pass all data to the view
        return view('commissionspaid/index', [
            'menuItems'            => $menuItems,
            'distinctBatches'      => $distinctBatches,
            'batchesAsc'           => $batchesAsc,
            'distinctUsers'        => $distinctUsers,
            'selectedBatch'        => $selectedBatch,
            'selectedUser'         => $selectedUser ?? 'all',
            'dataForSelectedBatch' => $dataForSelectedBatch,
            'totalSum'             => $totalSum,
            'amountsByUser'        => $amountsByUser,
            'lineTotals'           => $lineTotals,
            'allTotals'            => $allTotals,
        ]);
    }
}
