<?php

namespace App\Http\Controllers\API\v1\Admin\Allowance;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SummaryController extends Controller
{
    public function __invoke(Request $request)
    {
        $electionId = (int) Util::getCurrentElection();

        $q = DB::table('allowance_payouts as ap')
            ->leftJoin('users as u', 'u.id', '=', 'ap.paid_by_admin_id')
            ->where('ap.election_id', $electionId)
            ->where('ap.status', 'paid')
            ->selectRaw('ap.paid_by_admin_id as admin_id')
            ->selectRaw('MAX(u.name) as admin_name')
            ->selectRaw('MAX(u.email) as admin_email')
            ->selectRaw('COUNT(*) as payouts_count')
            ->selectRaw('COALESCE(SUM(ap.amount_cents), 0) as total_amount_cents')
            ->selectRaw("COALESCE(SUM(CASE WHEN ap.method = 'cash' THEN ap.amount_cents ELSE 0 END), 0) as cash_amount_cents")
            ->selectRaw("COALESCE(SUM(CASE WHEN ap.method = 'cash' THEN 1 ELSE 0 END), 0) as cash_count")
            ->selectRaw("COALESCE(SUM(CASE WHEN ap.method = 'bank' THEN ap.amount_cents ELSE 0 END), 0) as bank_amount_cents")
            ->selectRaw("COALESCE(SUM(CASE WHEN ap.method = 'bank' THEN 1 ELSE 0 END), 0) as bank_count")
            ->groupBy('ap.paid_by_admin_id')
            ->orderByDesc('total_amount_cents');

        // Optional: filter by method (?method=cash|bank)
        $method = $request->query('method');
        if ($method === 'cash' || $method === 'bank') {
            $q->where('ap.method', $method);
        }

        $rows = $q->get();

        $defaultCashCents = 30000;
        $defaultBankCents = 15000;

        $outstandingCash = (int) DB::table('voter as v')
            ->where('v.election_id', $electionId)
            ->where('v.kehadiran', 1)
            ->where(function ($outer) use ($electionId) {
                $outer->whereExists(function ($sub) use ($electionId) {
                    $sub->select(DB::raw(1))
                        ->from('result as r')
                        ->whereColumn('r.voter_id', 'v.id')
                        ->where('r.election_id', $electionId);
                })->orWhere(function ($q) {
                    $q->whereNotNull('v.fizikal_registration_verified_at')
                        ->whereRaw('COALESCE(v.saham, 0) < 500');
                });
            })
            ->whereNotExists(function ($sub) use ($electionId) {
                $sub->select(DB::raw(1))
                    ->from('allowance_payouts as ap')
                    ->whereColumn('ap.voter_id', 'v.id')
                    ->where('ap.election_id', $electionId)
                    ->where('ap.method', 'cash')
                    ->where('ap.status', 'paid');
            })
            ->count();

        $outstandingBank = (int) DB::table('voter as v')
            ->where('v.election_id', $electionId)
            ->where('v.kehadiran', 2)
            ->whereExists(function ($sub) use ($electionId) {
                $sub->select(DB::raw(1))
                    ->from('result as r')
                    ->whereColumn('r.voter_id', 'v.id')
                    ->where('r.election_id', $electionId);
            })
            ->whereNotExists(function ($sub) use ($electionId) {
                $sub->select(DB::raw(1))
                    ->from('allowance_payouts as ap')
                    ->whereColumn('ap.voter_id', 'v.id')
                    ->where('ap.election_id', $electionId)
                    ->where('ap.method', 'bank')
                    ->where('ap.status', 'paid');
            })
            ->count();

        $outstandingAllowanceCents = ($outstandingCash * $defaultCashCents) + ($outstandingBank * $defaultBankCents);

        return response()->json([
            'status' => 'success',
            'election_id' => $electionId,
            'rows' => $rows,
            'outstanding_allowance' => [
                'cents' => $outstandingAllowanceCents,
                'cash_count' => $outstandingCash,
                'bank_count' => $outstandingBank,
                'default_cash_cents' => $defaultCashCents,
                'default_bank_cents' => $defaultBankCents,
            ],
        ]);
    }
}

