<?php

namespace App\Http\Controllers\AdminDinas;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PsajParticipant;
use App\Models\School;
use App\Models\DisabilityType;

class PsajController extends Controller
{
    /**
     * Display a listing of all PSAJ participants (all schools)
     */
    public function index(Request $request)
    {
        $query = PsajParticipant::with(['disabilityType', 'school']);
        
        // Filter by jenjang
        if ($request->has('jenjang') && in_array($request->jenjang, ['SDLB', 'SMPLB', 'SMALB'])) {
            $query->where('jenjang', $request->jenjang);
        }
        
        // Filter by status
        if ($request->has('status')) {
            if ($request->status === 'final') {
                $query->where('is_locked', true);
            } elseif ($request->status === 'draft') {
                $query->where('is_locked', false);
            }
        }
        
        // Filter by school
        if ($request->has('school_id') && $request->school_id) {
            $query->where('school_id', $request->school_id);
        }
        
        // Search
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('nama', 'like', "%{$search}%")
                  ->orWhere('nisn', 'like', "%{$search}%")
                  ->orWhere('nik', 'like', "%{$search}%")
                  ->orWhere('no_peserta', 'like', "%{$search}%");
            });
        }
        
        $participants = $query->orderBy('created_at', 'desc')->paginate(20);
        $schools = School::orderBy('name')->get();
        
        $jenjangOptions = [
            'SDLB' => 'SDLB (Kelas VI)',
            'SMPLB' => 'SMPLB (Kelas IX)',
            'SMALB' => 'SMALB (Kelas XII)'
        ];
        
        return view('admin-dinas.psaj.index', [
            'participants' => $participants,
            'schools' => $schools,
            'jenjangOptions' => $jenjangOptions,
            'filters' => $request->all()
        ]);
    }
    
    /**
     * Display the specified participant
     */
    public function show($id)
    {
        $participant = PsajParticipant::with(['disabilityType', 'school'])
            ->findOrFail($id);
        
        return view('admin-dinas.psaj.show', [
            'participant' => $participant
        ]);
    }
    
    /**
     * Unlock a locked participant (change from final back to draft)
     */
    public function unlock($id)
    {
        $participant = PsajParticipant::findOrFail($id);
        
        if (!$participant->is_locked) {
            return redirect()->back()->with('error', 'Data peserta belum dikunci.');
        }
        
        $participant->update([
            'status' => 'draft',
            'is_locked' => false,
            'submitted_at' => null
        ]);
        
        return redirect()->back()->with('success', 'Data peserta berhasil dibuka kuncinya. Sekolah dapat mengedit kembali.');
    }
    
    /**
     * Bulk unlock participants
     */
    public function bulkUnlock(Request $request)
    {
        $validated = $request->validate([
            'participant_ids' => 'required|array|min:1',
            'participant_ids.*' => 'exists:psaj_participants,id'
        ]);
        
        $participants = PsajParticipant::whereIn('id', $validated['participant_ids'])
            ->where('is_locked', true)
            ->get();
        
        if ($participants->isEmpty()) {
            return redirect()->back()->with('error', 'Tidak ada peserta yang dapat dibuka kuncinya');
        }
        
        $count = 0;
        foreach ($participants as $participant) {
            $participant->update([
                'status' => 'draft',
                'is_locked' => false,
                'submitted_at' => null
            ]);
            $count++;
        }
        
        return redirect()->back()->with('success', "Berhasil membuka kunci {$count} peserta.");
    }
}
