<?php

namespace App\Http\Controllers\AdminSekolah;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\School;
use App\Models\PsajParticipant;
use App\Models\DisabilityType;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class PsajController extends Controller
{
    /**
     * Get the school for the authenticated admin
     */
    private function getSchool()
    {
        $user = Auth::user();
        $school = null;
        
        // Check direct school_id assignment
        if ($user->school_id) {
            $school = School::find($user->school_id);
        }
        
        // Try via employee active assignment
        if (!$school && $user->employee && $user->employee->activeAssignment) {
            $school = $user->employee->activeAssignment->school;
        }
        
        return $school;
    }
    
    /**
     * Check if school is SLB type
     */
    private function checkSlbSchool($school)
    {
        // Check if school level or name contains SLB
        $level = strtoupper($school->level ?? '');
        $name = strtoupper($school->name ?? '');
        
        if (!str_contains($level, 'SLB') && !str_contains($name, 'SLB')) {
            abort(403, 'PSAJ hanya tersedia untuk sekolah SLB');
        }
    }
    
    /**
     * Display a listing of PSAJ participants
     */
    public function index($jenjang = null)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        // Commented out temporarily - allow all schools to access PSAJ
        // $this->checkSlbSchool($school);
        
        $query = PsajParticipant::where('school_id', $school->id)
            ->with(['disabilityType', 'school']);
        
        if ($jenjang && in_array(strtoupper($jenjang), ['SDLB', 'SMPLB', 'SMALB'])) {
            $query->where('jenjang', strtoupper($jenjang));
        }
        
        $participants = $query->orderBy('created_at', 'desc')->get();
        
        // Get available jenjang options - allow all jenjang for now
        $jenjangOptions = [
            'SDLB' => 'SDLB (Kelas VI)',
            'SMPLB' => 'SMPLB (Kelas IX)',
            'SMALB' => 'SMALB (Kelas XII)'
        ];
        
        return view('admin-sekolah.psaj.index', [
            'school' => $school,
            'participants' => $participants,
            'jenjang' => $jenjang ? strtoupper($jenjang) : null,
            'jenjangOptions' => $jenjangOptions
        ]);
    }
    
    /**
     * Show the form for creating a new participant
     */
    public function create(Request $request)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $jenjang = $request->query('jenjang');
        
        // Allow all jenjang
        $jenjangOptions = [
            'SDLB' => 'SDLB (Kelas VI)',
            'SMPLB' => 'SMPLB (Kelas IX)',
            'SMALB' => 'SMALB (Kelas XII)'
        ];
        
        $disabilityTypes = DisabilityType::active()->get();
        
        return view('admin-sekolah.psaj.create', [
            'school' => $school,
            'jenjangOptions' => $jenjangOptions,
            'disabilityTypes' => $disabilityTypes,
            'selectedJenjang' => $jenjang
        ]);
    }
    
    /**
     * Store a newly created participant
     */
    public function store(Request $request)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'nik' => 'required|numeric|digits:16',
            'nisn' => 'required|numeric|digits:10|unique:psaj_participants,nisn',
            'nis' => 'nullable|string|max:50',
            'jenjang' => 'required|in:SDLB,SMPLB,SMALB',
            'tempat_lahir' => 'required|string|max:255',
            'tanggal_lahir' => 'required|date|before:today',
            'nama_ibu' => 'required|string|max:255',
            'disability_type_id' => 'required|exists:disability_types,id',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ], [
            'nik.required' => 'NIK harus diisi',
            'nik.numeric' => 'NIK hanya boleh berupa angka',
            'nik.digits' => 'NIK harus 16 digit',
            'nisn.required' => 'NISN harus diisi',
            'nisn.numeric' => 'NISN hanya boleh berupa angka',
            'nisn.digits' => 'NISN harus 10 digit',
            'nisn.unique' => 'NISN sudah terdaftar',
        ]);
        
        // Auto-assign kelas based on jenjang
        $validated['kelas'] = PsajParticipant::getDefaultKelas($validated['jenjang']);
        $validated['school_id'] = $school->id;
        
        // Generate no_peserta
        $validated['no_peserta'] = PsajParticipant::generateNoPeserta($validated['jenjang'], $school->id);
        
        // Handle photo upload
        if ($request->hasFile('photo')) {
            $photo = $request->file('photo');
            $photoName = time() . '_' . $validated['nisn'] . '.' . $photo->getClientOriginalExtension();
            $validated['photo'] = $photo->storeAs('psaj_photos', $photoName, 'public');
        }
        
        PsajParticipant::create($validated);
        
        // Update no_peserta with disability type
        $participant = PsajParticipant::where('school_id', $school->id)
            ->where('nisn', $validated['nisn'])
            ->first();
        
        if ($participant) {
            $participant->updateNoPesertaWithDisability();
        }
        
        return redirect()
            ->route('admin-sekolah.psaj.index', ['jenjang' => strtolower($validated['jenjang'])])
            ->with('success', 'Peserta PSAJ berhasil ditambahkan dengan No. Peserta: ' . $participant->no_peserta);
    }
    
    /**
     * Display the specified participant
     */
    public function show($id)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $participant = PsajParticipant::where('school_id', $school->id)
            ->with(['disabilityType', 'school'])
            ->findOrFail($id);
        
        return view('admin-sekolah.psaj.show', [
            'school' => $school,
            'participant' => $participant
        ]);
    }
    
    /**
     * Show the form for editing the specified participant
     */
    public function edit($id)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $participant = PsajParticipant::where('school_id', $school->id)
            ->findOrFail($id);
        
        // Check if data is locked
        if ($participant->is_locked) {
            return redirect()->route('admin-sekolah.psaj.show', $id)
                ->with('error', 'Data peserta sudah final dan terkunci. Tidak dapat diedit.');
        }
        
        // Allow all jenjang
        $jenjangOptions = [
            'SDLB' => 'SDLB (Kelas VI)',
            'SMPLB' => 'SMPLB (Kelas IX)',
            'SMALB' => 'SMALB (Kelas XII)'
        ];
        $disabilityTypes = DisabilityType::active()->get();
        
        return view('admin-sekolah.psaj.edit', [
            'school' => $school,
            'participant' => $participant,
            'jenjangOptions' => $jenjangOptions,
            'disabilityTypes' => $disabilityTypes
        ]);
    }
    
    /**
     * Update the specified participant
     */
    public function update(Request $request, $id)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $participant = PsajParticipant::where('school_id', $school->id)
            ->findOrFail($id);
        
        // Check if data is locked
        if ($participant->is_locked) {
            return redirect()->route('admin-sekolah.psaj.show', $id)
                ->with('error', 'Data peserta sudah final dan terkunci. Tidak dapat diupdate.');
        }
        
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'nik' => 'required|numeric|digits:16',
            'nisn' => 'required|numeric|digits:10|unique:psaj_participants,nisn,' . $id,
            'nis' => 'nullable|string|max:50',
            'jenjang' => 'required|in:SDLB,SMPLB,SMALB',
            'tempat_lahir' => 'required|string|max:255',
            'tanggal_lahir' => 'required|date|before:today',
            'nama_ibu' => 'required|string|max:255',
            'disability_type_id' => 'required|exists:disability_types,id',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
        ], [
            'nik.required' => 'NIK harus diisi',
            'nik.numeric' => 'NIK hanya boleh berupa angka',
            'nik.digits' => 'NIK harus 16 digit',
            'nisn.required' => 'NISN harus diisi',
            'nisn.numeric' => 'NISN hanya boleh berupa angka',
            'nisn.digits' => 'NISN harus 10 digit',
            'nisn.unique' => 'NISN sudah terdaftar',
        ]);
        
        // Auto-assign kelas based on jenjang (if changed)
        if ($validated['jenjang'] !== $participant->jenjang) {
            $validated['kelas'] = PsajParticipant::getDefaultKelas($validated['jenjang']);
        }
        
        // Handle photo upload
        if ($request->hasFile('photo')) {
            // Delete old photo if exists
            if ($participant->photo) {
                Storage::disk('public')->delete($participant->photo);
            }
            
            $photo = $request->file('photo');
            $photoName = time() . '_' . $validated['nisn'] . '.' . $photo->getClientOriginalExtension();
            $validated['photo'] = $photo->storeAs('psaj_photos', $photoName, 'public');
        }
        
        $participant->update($validated);
        
        return redirect()
            ->route('admin-sekolah.psaj.index', ['jenjang' => strtolower($validated['jenjang'])])
            ->with('success', 'Data peserta PSAJ berhasil diperbarui');
    }
    
    /**
     * Remove the specified participant
     */
    public function destroy($id)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $participant = PsajParticipant::where('school_id', $school->id)
            ->findOrFail($id);
        
        // Check if data is locked
        if ($participant->is_locked) {
            return redirect()->route('admin-sekolah.psaj.index', ['jenjang' => strtolower($participant->jenjang)])
                ->with('error', 'Data peserta sudah final dan terkunci. Tidak dapat dihapus.');
        }
        
        // Delete photo if exists
        if ($participant->photo) {
            Storage::disk('public')->delete($participant->photo);
        }
        
        $jenjang = strtolower($participant->jenjang);
        $participant->delete();
        
        return redirect()
            ->route('admin-sekolah.psaj.index', ['jenjang' => $jenjang])
            ->with('success', 'Peserta PSAJ berhasil dihapus');
    }
    
    /**
     * Generate participant card (PDF)
     */
    public function generateKartu($id)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $participant = PsajParticipant::where('school_id', $school->id)
            ->with(['disabilityType', 'school'])
            ->findOrFail($id);
        
        return view('admin-sekolah.psaj.kartu', [
            'school' => $school,
            'participant' => $participant
        ]);
    }
    
    /**
     * Submit participants as final (lock data)
     */
    public function submit(Request $request)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $validated = $request->validate([
            'participant_ids' => 'required|array|min:1',
            'participant_ids.*' => 'exists:psaj_participants,id'
        ]);
        
        $participants = PsajParticipant::where('school_id', $school->id)
            ->whereIn('id', $validated['participant_ids'])
            ->where('is_locked', false)
            ->get();
        
        if ($participants->isEmpty()) {
            return redirect()->back()->with('error', 'Tidak ada peserta yang dapat difinalisasi');
        }
        
        $count = 0;
        foreach ($participants as $participant) {
            $participant->update([
                'status' => 'final',
                'is_locked' => true,
                'submitted_at' => now()
            ]);
            $count++;
        }
        
        return redirect()->back()->with('success', "Berhasil memfinalisasi {$count} peserta. Data telah terkunci.");
    }
    
    /**
     * Generate batch participant cards (4 per A4 page)
     */
    public function generateKartuBatch(Request $request)
    {
        $school = $this->getSchool();
        
        if (!$school) {
            return redirect()->route('dashboard')->with('error', 'Sekolah tidak ditemukan');
        }
        
        $jenjang = $request->query('jenjang');
        
        $query = PsajParticipant::where('school_id', $school->id)
            ->with(['disabilityType', 'school'])
            ->orderBy('no_peserta');
        
        if ($jenjang && in_array(strtoupper($jenjang), ['SDLB', 'SMPLB', 'SMALB'])) {
            $query->where('jenjang', strtoupper($jenjang));
        }
        
        $participants = $query->get();
        
        if ($participants->isEmpty()) {
            return redirect()->back()->with('error', 'Tidak ada peserta untuk dicetak');
        }
        
        return view('admin-sekolah.psaj.kartu-batch', [
            'school' => $school,
            'participants' => $participants,
            'jenjang' => $jenjang
        ]);
    }
}
