<?php

namespace App\Http\Controllers\AdminKcd;

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

class SekolahController extends Controller
{
    /**
     * Display a listing of schools in the KCD.
     */
    public function index()
    {
        $user = auth()->user();
        
        // Get the KCD for the current admin
        if (!$user->employee || !$user->employee->activeAssignment) {
            return view('admin-kcd.sekolah', [
                'schools' => collect(),
                'stats' => [
                    'total' => 0,
                    'active' => 0,
                    'inactive' => 0,
                ]
            ]);
        }
        
        $kcdId = $user->employee->activeAssignment->kcd_id;
        
        // Get all schools in this KCD - using direct kcd_id or through kabKota
        $schools = School::where(function($query) use ($kcdId) {
            $query->where('kcd_id', $kcdId)
                  ->orWhereHas('kabKota', function($q) use ($kcdId) {
                      $q->where('kcd_id', $kcdId);
                  });
        })
        ->with(['kcd', 'kabKota.kcd', 'employeeAssignments' => function($query) {
            $query->where('is_active', true)
                  ->whereNull('end_date')
                  ->with('employee');
        }])
        ->orderBy('name')
        ->get();
        
        // Calculate stats
        $stats = [
            'total' => $schools->count(),
            'active' => $schools->where('is_active', true)->count(),
            'inactive' => $schools->where('is_active', false)->count(),
        ];
        
        return view('admin-kcd.sekolah', compact('schools', 'stats'));
    }
}
