<?php

namespace App\Http\Controllers\AdminKcd;

use App\Http\Controllers\Controller;
use App\Models\EmployeeAssignment;
use App\Models\School;
use App\Models\Employee;
use Illuminate\Http\Request;

class MappingSekolahController extends Controller
{
    /**
     * Display a listing of the school mappings for the current KCD.
     */
    public function index()
    {
        $user = auth()->user();
        
        // Get the KCD for the current admin
        if (!$user->employee || !$user->employee->activeAssignment) {
            return view('admin-kcd.mapping-sekolah', [
                'supervisorGroups' => collect(),
                'schoolsWithoutSupervisor' => collect(),
                'supervisors' => collect(),
                'allSchools' => collect(),
                'kcdId' => null,
                'stats' => [
                    'total_schools' => 0,
                    'assigned_schools' => 0,
                    'unassigned_schools' => 0,
                    'active_supervisors' => 0,
                ]
            ]);
        }
        
        $kcdId = $user->employee->activeAssignment->kcd_id;
        
        // Get all active supervisor assignments (pengawas) in this KCD
        $assignments = EmployeeAssignment::with(['employee', 'school', 'kcd', 'kabKota'])
            ->where('kcd_id', $kcdId)
            ->where('assignment_type', 'school')
            ->where('is_active', true)
            ->whereNull('end_date')
            ->orderBy('start_date', 'desc')
            ->get();
        
        // Get schools in this KCD
        $totalSchools = School::whereHas('kabKota', function($query) use ($kcdId) {
            $query->where('kcd_id', $kcdId);
        })->where('is_active', true)->count();
        
        // Get assigned school IDs
        $assignedSchoolIds = $assignments->pluck('school_id')->filter()->unique();
        $assignedSchoolsCount = $assignedSchoolIds->count();
        
        // Get schools without supervisor
        $schoolsWithoutSupervisor = School::whereHas('kabKota', function($query) use ($kcdId) {
            $query->where('kcd_id', $kcdId);
        })
        ->where('is_active', true)
        ->whereNotIn('id', $assignedSchoolIds)
        ->with(['kabKota'])
        ->orderBy('name')
        ->get();
        
        // Count active supervisors
        $activeSupervisors = $assignments->pluck('employee_id')->unique()->count();
        
        // Group assignments by employee (supervisor)
        $supervisorGroups = $assignments->groupBy('employee_id')->map(function($group) {
            return [
                'employee' => $group->first()->employee,
                'schools' => $group->pluck('school')->filter()
            ];
        });
        
        $stats = [
            'total_schools' => $totalSchools,
            'assigned_schools' => $assignedSchoolsCount,
            'unassigned_schools' => $totalSchools - $assignedSchoolsCount,
            'active_supervisors' => $activeSupervisors,
        ];
        
        // Get active supervisors (pengawas) in this KCD for the form
        // Get all employees who have KCD assignment (as staff) or school assignment (as supervisor) in this KCD
        $supervisors = Employee::whereHas('assignments', function($query) use ($kcdId) {
            $query->where('kcd_id', $kcdId)
                  ->where('is_active', true);
        })->where('is_active', true)->orderBy('name')->get();
        
        // Get all schools in this KCD for the form
        $allSchools = School::whereHas('kabKota', function($query) use ($kcdId) {
            $query->where('kcd_id', $kcdId);
        })->where('is_active', true)->with('kabKota')->orderBy('name')->get();
        
        return view('admin-kcd.mapping-sekolah', compact('supervisorGroups', 'schoolsWithoutSupervisor', 'stats', 'supervisors', 'allSchools', 'kcdId'));
    }

    /**
     * Store a new assignment
     */
    public function store(Request $request)
    {
        $user = auth()->user();
        
        if (!$user->employee || !$user->employee->activeAssignment) {
            return redirect()->route('admin-kcd.mapping-sekolah')
                ->with('error', 'Anda tidak memiliki akses ke KCD');
        }
        
        $kcdId = $user->employee->activeAssignment->kcd_id;
        
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'school_ids' => 'required|array|min:1',
            'school_ids.*' => 'exists:schools,id',
            'start_date' => 'required|date',
        ], [
            'employee_id.required' => 'Pengawas harus dipilih',
            'school_ids.required' => 'Minimal satu sekolah harus dipilih',
            'school_ids.min' => 'Minimal satu sekolah harus dipilih',
            'start_date.required' => 'Tanggal mulai harus diisi',
        ]);
        
        // Verify all schools belong to this KCD
        $schools = School::whereIn('id', $request->school_ids)
            ->whereHas('kabKota', function($query) use ($kcdId) {
                $query->where('kcd_id', $kcdId);
            })->get();
        
        if ($schools->count() !== count($request->school_ids)) {
            return redirect()->route('admin-kcd.mapping-sekolah')
                ->with('error', 'Beberapa sekolah tidak valid atau bukan bagian dari KCD Anda');
        }
        
        // Create assignments for each school
        foreach ($request->school_ids as $schoolId) {
            $school = School::with('kabKota')->find($schoolId);
            
            EmployeeAssignment::create([
                'employee_id' => $request->employee_id,
                'assignment_type' => 'school',
                'kcd_id' => $kcdId,
                'kab_kota_id' => $school->kab_kota_id,
                'school_id' => $schoolId,
                'start_date' => $request->start_date,
                'is_active' => true,
            ]);
        }
        
        return redirect()->route('admin-kcd.mapping-sekolah')
            ->with('success', 'Penugasan berhasil ditambahkan untuk ' . count($request->school_ids) . ' sekolah');
    }

    /**
     * Delete an assignment
     */
    public function destroy($id)
    {
        $user = auth()->user();
        
        if (!$user->employee || !$user->employee->activeAssignment) {
            return redirect()->route('admin-kcd.mapping-sekolah')
                ->with('error', 'Anda tidak memiliki akses ke KCD');
        }
        
        $kcdId = $user->employee->activeAssignment->kcd_id;
        
        $assignment = EmployeeAssignment::where('id', $id)
            ->where('kcd_id', $kcdId)
            ->first();
        
        if (!$assignment) {
            return redirect()->route('admin-kcd.mapping-sekolah')
                ->with('error', 'Penugasan tidak ditemukan');
        }
        
        $assignment->delete();
        
        return redirect()->route('admin-kcd.mapping-sekolah')
            ->with('success', 'Penugasan berhasil dihapus');
    }

    /**
     * Unassign a school from a supervisor
     */
    public function unassignSchool(Request $request)
    {
        $user = auth()->user();
        
        if (!$user->employee || !$user->employee->activeAssignment) {
            return response()->json(['success' => false, 'message' => 'Anda tidak memiliki akses ke KCD']);
        }
        
        $kcdId = $user->employee->activeAssignment->kcd_id;
        
        $assignment = EmployeeAssignment::where('employee_id', $request->employee_id)
            ->where('school_id', $request->school_id)
            ->where('kcd_id', $kcdId)
            ->where('is_active', true)
            ->first();
        
        if (!$assignment) {
            return response()->json(['success' => false, 'message' => 'Penugasan tidak ditemukan']);
        }
        
        $assignment->delete();
        
        return response()->json(['success' => true, 'message' => 'Sekolah berhasil dihapus dari pengawas']);
    }
}
