<?php

namespace App\Http\Controllers;

use App\Models\Admin\Tdaftarexcul;
use App\Models\Admin\Tkelas;
use App\Models\Admin\Tkelsis;
use App\Models\Admin\Tkelsis1;
use App\Models\Admin\Tstopexcul;
use App\Models\Datmas\Excul;
use App\Models\Datmas\Indentitas;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ExculController extends Controller
{
    public function subs(Request $req, $nouid)
    {
        $v = $req->validate([
            'excul' => 'required|integer|exists:mai1.tkelas,id',
            'tgl' => 'required|date_format:Y-m', // Expect YYYY-MM
            'ket' => 'required|string',
        ]);
        logger("Request Subs Excul ", ['req' => $req->all()]);

        try {
            $ident = Indentitas::with('kelsis')->where('nouid', $nouid)->firstOrFail();

            // Format date to first of month for consistency
            $reqDate = \Carbon\Carbon::createFromFormat('Y-m', $v['tgl'])->startOfMonth();
            $tgl = $reqDate->format('Y-m-d');

            // Cek apakah sudah terdaftar di bulan yang sama (Tdaftarexcul source of truth per bulan)
            $existingMonthly = Tdaftarexcul::where('idsis', $ident->idok)
                ->where('idkel', $v['excul'])
                ->whereYear('tgl', $reqDate->year)
                ->whereMonth('tgl', $reqDate->month)
                ->whereIn('sta', [0, 1]) // 0: Waiting, 1: Active
                ->first();

            if ($existingMonthly) {
                return back(409)->with([
                    'success' => false,
                    'message' => 'Anda sudah terdaftar pada ekstrakurikuler ini untuk bulan ' . $reqDate->format('F Y'),
                ]);
            }

            DB::transaction(function () use ($ident, $v, $tgl) {
                // 1. Update/Create Master Status (Tkelsis1) - Represents "Current/Latest" status
                // We don't block based on this anymore, just update it to reflect "Active" generally
                $tkelsis = Tkelsis1::firstOrNew([
                    'ids' => $ident->idok,
                    'idkel' => $v['excul']
                ]);

                $tkelsis->tin = $ident->kelsis->tin;
                $tkelsis->idta = $ident->kelsis->idta;
                $tkelsis->idmen = $ident->idmen;
                $tkelsis->idtra = random_int(1, 999);
                $tkelsis->sta = 0; // Set to waiting/registered
                $tkelsis->save();

                // 2. Create Monthly Record (Tdaftarexcul)
                Tdaftarexcul::create([
                    'tin' => $ident->kelsis->tin,
                    'idta' => $ident->kelsis->idta,
                    'idsis' => $ident->kelsis->ids,
                    'tgl' => $tgl,
                    'idkel' => $v['excul'],
                    'ket' => $v['ket'],
                    'sta' => 0, // Waiting
                ]);
            });

            return back()->with([
                "success" => true,
                "message" => "Berhasil mendaftar ekstrakurikuler untuk bulan " . $reqDate->translatedFormat('F Y')
            ]);
        } catch (\Exception $e) {
            logger()->error("Error Menambahkan Excul", [
                'nouid' => $nouid,
                'error' => $e->getMessage()
            ]);

            return back()->with([
                'success' => false,
                'message' => "Terjadi kesalahan saat memproses pendaftaran"
            ]);
        }
    }

    public function unsubs(Request $req, $nouid)
    {
        $v = $req->validate([
            'excul' => 'required|integer|exists:mai1.tkelas,id',
            'tgl' => 'required', // Bisa date or string Y-m
            'ket' => 'required|string',
        ]);

        try {
            $ident = Indentitas::with('kelsis')->where('nouid', $nouid)->firstOrFail();

            // Handle both date formats if necessary, but frontend should send Y-m now
            // Default to current month if format fails, or just strict parsing
            try {
                $reqDate = \Carbon\Carbon::parse($v['tgl'])->startOfMonth();
            } catch (\Exception $e) {
                return back(400)->with(['success' => false, 'message' => 'Format tanggal salah']);
            }

            // Cari pendaftaran di bulan tersebut
            $monthlyRecord = Tdaftarexcul::where('idsis', $ident->idok)
                ->where('idkel', $v['excul'])
                ->whereYear('tgl', $reqDate->year)
                ->whereMonth('tgl', $reqDate->month)
                ->whereIn('sta', [0, 1])
                ->first();

            if (!$monthlyRecord) {
                return back(404)->with([
                    'success' => false,
                    'message' => 'Tidak ditemukan pendaftaran aktif untuk bulan ' . $reqDate->format('F Y'),
                ]);
            }

            DB::transaction(function () use ($ident, $v, $reqDate, $monthlyRecord) {
                // Cancel monthly record
                $monthlyRecord->update(['sta' => -2]); // -2: Cancelled/Exited

                // Create Stop History
                Tstopexcul::create([
                    'tin' => $ident->kelsis->tin,
                    'idta' => $ident->kelsis->idta,
                    'idsis' => $ident->kelsis->ids,
                    'tgl' => now(), // Tanggal pengajuan stop
                    'idkel' => $v['excul'],
                    'ala' => $v['ket'],
                    'idks1' => $monthlyRecord->id, // Link to daftarexcul id preferably, or keep legacy logic
                    'tglex' => $reqDate->format('Y-m-d'), // Bulan yang distop
                ]);

                // Update Master Tkelsis1 ONLY if there are no other active months? 
                // Or just set it to -2? 
                // If we treat Tkelsis1 as "Latest Status", then setting it to -2 is fine
                // But if they have other future months active, this might be wrong.
                // For simplicity, let's update Tkelsis1 to -2 to reflect "User performed Stop action"
                Tkelsis1::where('ids', $ident->idok)
                    ->where('idkel', $v['excul'])
                    ->update(['sta' => -2]);
            });

            return back()->with([
                'success' => true,
                'message' => 'Berhasil membatalkan pendaftaran ekskul bulan ' . $reqDate->translatedFormat('F Y'),
            ]);
        } catch (\Exception $e) {
            logger("Error Membatalkan Excul", ['error' => $e->getMessage()]);
            return back()->with([
                'success' => false,
                'message' => 'Terjadi kesalahan',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public static function Excul(int $ids)
    {
        try {
            $subscriptions = Tkelsis1::where('ids', $ids)->get();

            $sub = $subscriptions->whereIn('sta', 1)->pluck('idkel')->toArray();
            $waiting = $subscriptions->where('sta', 0)->pluck('idkel')->toArray();
            $rejected = $subscriptions->where('sta', -1)->pluck('idkel')->toArray();
            $exited = $subscriptions->where('sta', -2)->pluck('idkel')->toArray();
            $excul = Tkelas::with('jenis')
                ->whereHas('jenis', function ($q) {
                    $q->where('tip', 1)->where('sta', 0);
                })
                ->where('idta', idta()->id)
                ->select('id', 'nam as name', 'qty as quota')
                ->get()
                ->map(function ($item) {
                    $item->registered = 0;
                    return $item;
                });

            $registeredCounts = Tkelsis1::whereIn('idkel', $excul->pluck('id')->toArray())->whereIn('sta', [0, 1])
                ->select('idkel', DB::raw('count(*) as count'))
                ->groupBy('idkel')
                ->pluck('count', 'idkel');

            $excul = $excul->map(function ($item) use ($registeredCounts) {
                $item->registered = $registeredCounts[$item->id] ?? 0;
                return $item;
            });

            $data = [
                'excul' => $excul,
                'sub' => $sub,
                'waiting' => $waiting,
                'rejected' => $rejected,
                'exited' => $exited,
            ];

            return $data;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    public function simulasi(Request $req, $simulasi)
    {
        $v = $req->validate([
            'nouid' => 'required|exists:mai2.tindentitas,nouid',
            'excul' => 'required|integer|exists:mai1.tkelas,id',
        ]);

        $ident = Indentitas::with([
            'kelsis1' => function ($q) use ($v) {
                $q->where('idkel', $v['excul']);
            },
            'daftarexcul' => function ($q) use ($v) {
                $q->where('idkel', $v['excul']);
            },
            'stopexcul' => function ($q) use ($v) {
                $q->where('idkel', $v['excul']);
            }
        ])->where('nouid', $v['nouid'])->firstOrFail();

        return DB::transaction(function () use ($simulasi, $ident, $v) {
            $exculId = $v['excul'];

            switch ($simulasi) {
                case 'acc':
                    // Only update the specific extracurricular
                    $ident->kelsis1()->where('idkel', $exculId)->update(['sta' => 1]);
                    $ident->daftarexcul()->where('idkel', $exculId)->update(['sta' => 1]);
                    $ident->stopexcul()->where('idkel', $exculId)->update(['sta' => 1]);
                    break;

                case 'reject':
                    // Only update the specific extracurricular
                    $ident->kelsis1()->where('idkel', $exculId)->update(['sta' => -1]);
                    $ident->daftarexcul()->where('idkel', $exculId)->update(['sta' => -1]);
                    $ident->stopexcul()->where('idkel', $exculId)->update(['sta' => -1]);
                    break;

                default:
                    return back(400)->withErrors(['message' => 'Invalid simulation type']);
            }

            return redirect()->intended(route('siswa.index', [
                'nouid' => $v['nouid'],
                'page' => 'index',
                'tab' => 'kegiatan'
            ]));
        });
    }
}
