<?php

namespace App\Http\Controllers;

use App\Models\Rap;
use App\Models\RapBonusCair;
use App\Models\RapKomisiCair;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LaporanRapController extends Controller
{
    /**
     * Display RAP report with leaderboard and filters.
     */
    public function index(Request $request)
    {
        // =============================
        // QUERY UTAMA
        // =============================
        $query = Rap::query()->valid();

        if ($request->filled('tipe') && $request->tipe !== 'all') {
            $query->where('tipe', $request->tipe);
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        // FILTER KAMPUS - PERBAIKAN: Gunakan WHERE exact match
        if ($request->filled('kampus') && $request->kampus !== 'all') {
            $query->where('kampus', $request->kampus);
        }

        $tahunAjaranFilter = $request->tahun_ajaran;
        if ($tahunAjaranFilter && $tahunAjaranFilter !== 'all') {
            $query->whereHas('mahasiswa', function ($q) use ($tahunAjaranFilter) {
                $q->where('tahun_ajaran', $tahunAjaranFilter);
            });
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                    ->orWhere('marketing', 'like', "%{$search}%")
                    ->orWhere('kampus', 'like', "%{$search}%");
            });
        }

        $rapList = $query->orderByDesc('total_mahasiswa_daftar')
            ->paginate(10)
            ->withQueryString();

        // =============================
        // LEADERBOARD (TOP 5)
        // =============================
        $allRapList = Rap::query()
            ->valid()
            ->when($request->filled('tipe') && $request->tipe !== 'all', function ($q) use ($request) {
                $q->where('tipe', $request->tipe);
            })
            ->when($request->filled('status') && $request->status !== 'all', function ($q) use ($request) {
                $q->where('status', $request->status);
            })
            ->when($request->filled('kampus') && $request->kampus !== 'all', function ($q) use ($request) {
                $q->where('kampus', $request->kampus); // Exact match
            })
            ->when($request->filled('tahun_ajaran') && $request->tahun_ajaran !== 'all', function ($q) use ($request) {
                $q->whereHas('mahasiswa', function ($sub) use ($request) {
                    $sub->where('tahun_ajaran', $request->tahun_ajaran);
                });
            })
            ->get();

        // Ambil semua bonus & komisi SEKALI (anti N+1)
        $bonusCairMap = RapBonusCair::where('status', 'disetujui')
            ->select('rap_id', DB::raw('SUM(nominal) as total'))
            ->groupBy('rap_id')
            ->pluck('total', 'rap_id');

        $komisiCairMap = RapKomisiCair::where('status', 'disetujui')
            ->select('rap_id', DB::raw('SUM(nominal) as total'))
            ->groupBy('rap_id')
            ->pluck('total', 'rap_id');

        // Mapping leaderboard
        $leaderboard = $allRapList
            ->map(function (Rap $rap) use ($bonusCairMap, $komisiCairMap) {
                $bonusRule = $rap->getBonusRule();
                $bonusCair = $bonusCairMap[$rap->id] ?? 0;
                $komisiCair = $komisiCairMap[$rap->id] ?? 0;

                return (object)[
                    'id' => $rap->id,
                    'nama' => $rap->nama,
                    'tipe' => $rap->tipe,
                    'kampus' => $rap->kampus,
                    'marketing' => $rap->marketing,
                    'total_mahasiswa' => $rap->total_mahasiswa_daftar,
                    'potensi_bonus' => $bonusRule ? $bonusRule->nominal_bonus : 0,
                    'bonus_cair' => $bonusCair,
                    'komisi_cair' => $komisiCair,
                    'total_pendapatan' => $bonusCair + $komisiCair,
                ];
            })
            ->sortByDesc('total_mahasiswa')
            ->values();

        // Top 5 untuk leaderboard
        $top5 = $leaderboard->take(5);

        // =============================
        // STATISTIK
        // =============================
        $statistik = [
            'total' => Rap::valid()->count(),
            'aktif' => Rap::valid()->where('status', 'aktif')->count(),
            'nonaktif' => Rap::valid()->where('status', 'nonaktif')->count(),
            'mahasiswa' => Rap::valid()->where('tipe', 'mahasiswa')->count(),
            'non_mahasiswa' => Rap::valid()->where('tipe', 'non_mahasiswa')->count(),
        ];

        // =============================
        // TAHUN AJARAN & KAMPUS
        // =============================
        $tahunAjaranList = DB::table('mahasiswa')
            ->whereNotNull('tahun_ajaran')
            ->distinct()
            ->pluck('tahun_ajaran')
            ->toArray();
        sort($tahunAjaranList);

        // Ambil daftar kampus unik untuk filter
        $kampusList = Rap::valid()
            ->whereNotNull('kampus')
            ->distinct()
            ->pluck('kampus')
            ->toArray();
        sort($kampusList);

        return view('laporan.rap', compact(
            'rapList',
            'leaderboard',
            'top5',
            'statistik',
            'tahunAjaranList',
            'kampusList',
            'tahunAjaranFilter'
        ));
    }

    /**
     * Cetak PDF laporan RAP dengan filter yang sama (BUKA DI TAB BARU).
     */
    public function cetakPdf(Request $request)
    {
        $query = Rap::query()->valid();

        if ($request->filled('tipe') && $request->tipe !== 'all') {
            $query->where('tipe', $request->tipe);
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        // FILTER KAMPUS - Exact match
        if ($request->filled('kampus') && $request->kampus !== 'all') {
            $query->where('kampus', $request->kampus);
        }

        $tahunAjaranFilter = $request->tahun_ajaran;
        if ($tahunAjaranFilter && $tahunAjaranFilter !== 'all') {
            $query->whereHas('mahasiswa', function ($q) use ($tahunAjaranFilter) {
                $q->where('tahun_ajaran', $tahunAjaranFilter);
            });
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                    ->orWhere('marketing', 'like', "%{$search}%")
                    ->orWhere('kampus', 'like', "%{$search}%");
            });
        }

        $rapList = $query->orderByDesc('total_mahasiswa_daftar')->get();

        // Leaderboard untuk PDF (TOP 5)
        $allRapList = Rap::query()
            ->valid()
            ->when($request->filled('tipe') && $request->tipe !== 'all', function ($q) use ($request) {
                $q->where('tipe', $request->tipe);
            })
            ->when($request->filled('status') && $request->status !== 'all', function ($q) use ($request) {
                $q->where('status', $request->status);
            })
            ->when($request->filled('kampus') && $request->kampus !== 'all', function ($q) use ($request) {
                $q->where('kampus', $request->kampus);
            })
            ->when($request->filled('tahun_ajaran') && $request->tahun_ajaran !== 'all', function ($q) use ($request) {
                $q->whereHas('mahasiswa', function ($sub) use ($request) {
                    $sub->where('tahun_ajaran', $request->tahun_ajaran);
                });
            })
            ->get();

        $leaderboard = $allRapList
            ->map(function (Rap $rap) {
                $bonusRule = $rap->getBonusRule();
                $bonusCair = RapBonusCair::where('rap_id', $rap->id)
                    ->where('status', 'disetujui')
                    ->sum('nominal');
                $komisiCair = RapKomisiCair::where('rap_id', $rap->id)
                    ->where('status', 'disetujui')
                    ->sum('nominal');

                return (object)[
                    'nama' => $rap->nama,
                    'tipe' => $rap->tipe,
                    'kampus' => $rap->kampus,
                    'marketing' => $rap->marketing,
                    'total_mahasiswa' => $rap->total_mahasiswa_daftar,
                    'potensi_bonus' => $bonusRule ? $bonusRule->nominal_bonus : 0,
                    'bonus_cair' => $bonusCair,
                    'komisi_cair' => $komisiCair,
                    'total_pendapatan' => $bonusCair + $komisiCair,
                ];
            })
            ->sortByDesc('total_mahasiswa')
            ->values()
            ->take(5);

        $filters = [
            'tipe' => $request->tipe,
            'status' => $request->status,
            'search' => $request->search,
            'kampus' => $request->kampus,
            'tahun_ajaran' => $tahunAjaranFilter,
        ];

        $pdf = Pdf::loadView('laporan.pdf.rap', compact('rapList', 'leaderboard', 'filters'));
        $pdf->setPaper('A4', 'landscape');

        return $pdf->stream('laporan_rap_' . now()->format('Y-m-d_H-i-s') . '.pdf');
    }
}
