<?php

namespace App\Http\Controllers\Superadmin;

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

class EmployeeAssignmentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $assignments = EmployeeAssignment::with('employee', 'kcd', 'school')
            ->orderBy('start_date', 'desc')
            ->get();
        
        // Pass assignment type constants to view
        $assignmentTypes = [
            'TYPE_KCD' => EmployeeAssignment::TYPE_KCD,
            'TYPE_SCHOOL' => EmployeeAssignment::TYPE_SCHOOL,
        ];
        
        return view('superadmin.employee-assignments.index', compact('assignments', 'assignmentTypes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $employees = Employee::where('is_active', true)->orderBy('name')->get();
        $kcds = Kcd::where('is_active', true)->orderBy('name')->get();
        $kabKotas = KabKota::where('is_active', true)->orderBy('name')->get();
        $schools = School::where('is_active', true)->orderBy('name')->get();
        
        // Pass assignment type constants to view
        $assignmentTypes = [
            'TYPE_KCD' => EmployeeAssignment::TYPE_KCD,
            'TYPE_SCHOOL' => EmployeeAssignment::TYPE_SCHOOL,
        ];
        
        return view('superadmin.employee-assignments.create', compact('employees', 'kcds', 'kabKotas', 'schools', 'assignmentTypes'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'assignment_type' => 'required|in:' . EmployeeAssignment::TYPE_KCD . ',' . EmployeeAssignment::TYPE_SCHOOL,
            'kcd_id' => 'required|exists:kcds,id',
            'kab_kota_id' => 'required_if:assignment_type,' . EmployeeAssignment::TYPE_SCHOOL . '|nullable|exists:kab_kota,id',
            'school_id' => 'required_if:assignment_type,' . EmployeeAssignment::TYPE_SCHOOL . '|nullable|exists:schools,id',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
            'notes' => 'nullable|string',
        ], [
            'employee_id.required' => 'Pegawai harus dipilih',
            'assignment_type.required' => 'Tipe penugasan harus dipilih',
            'kcd_id.required' => 'KCD harus dipilih',
            'kab_kota_id.required_if' => 'Kab/Kota harus dipilih untuk penugasan Sekolah',
            'school_id.required_if' => 'Sekolah harus dipilih untuk penugasan Sekolah',
            'start_date.required' => 'Tanggal mulai harus diisi',
            'end_date.after' => 'Tanggal selesai harus setelah tanggal mulai',
        ]);

        $data = $request->all();
        
        // Set null for school-related fields if assignment type is KCD
        if ($request->assignment_type === EmployeeAssignment::TYPE_KCD) {
            $data['kab_kota_id'] = null;
            $data['school_id'] = null;
        }

        EmployeeAssignment::create($data);

        return redirect()->route('superadmin.employee-assignments.index')
            ->with('success', 'Mapping pegawai berhasil ditambahkan');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(EmployeeAssignment $employeeAssignment)
    {
        $employees = Employee::where('is_active', true)->orderBy('name')->get();
        $kcds = Kcd::where('is_active', true)->orderBy('name')->get();
        $kabKotas = KabKota::where('is_active', true)->orderBy('name')->get();
        $schools = School::where('is_active', true)->orderBy('name')->get();
        
        // Pass assignment type constants to view
        $assignmentTypes = [
            'TYPE_KCD' => EmployeeAssignment::TYPE_KCD,
            'TYPE_SCHOOL' => EmployeeAssignment::TYPE_SCHOOL,
        ];
        
        return view('superadmin.employee-assignments.edit', compact('employeeAssignment', 'employees', 'kcds', 'kabKotas', 'schools', 'assignmentTypes'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, EmployeeAssignment $employeeAssignment)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'assignment_type' => 'required|in:' . EmployeeAssignment::TYPE_KCD . ',' . EmployeeAssignment::TYPE_SCHOOL,
            'kcd_id' => 'required|exists:kcds,id',
            'kab_kota_id' => 'required_if:assignment_type,' . EmployeeAssignment::TYPE_SCHOOL . '|nullable|exists:kab_kota,id',
            'school_id' => 'required_if:assignment_type,' . EmployeeAssignment::TYPE_SCHOOL . '|nullable|exists:schools,id',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
            'notes' => 'nullable|string',
        ], [
            'employee_id.required' => 'Pegawai harus dipilih',
            'assignment_type.required' => 'Tipe penugasan harus dipilih',
            'kcd_id.required' => 'KCD harus dipilih',
            'kab_kota_id.required_if' => 'Kab/Kota harus dipilih untuk penugasan Sekolah',
            'school_id.required_if' => 'Sekolah harus dipilih untuk penugasan Sekolah',
            'start_date.required' => 'Tanggal mulai harus diisi',
            'end_date.after' => 'Tanggal selesai harus setelah tanggal mulai',
        ]);

        $data = $request->all();
        
        // Set null for school-related fields if assignment type is KCD
        if ($request->assignment_type === EmployeeAssignment::TYPE_KCD) {
            $data['kab_kota_id'] = null;
            $data['school_id'] = null;
        }

        $employeeAssignment->update($data);

        return redirect()->route('superadmin.employee-assignments.index')
            ->with('success', 'Mapping pegawai berhasil diperbarui');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(EmployeeAssignment $employeeAssignment)
    {
        try {
            $employeeAssignment->delete();
            return redirect()->route('superadmin.employee-assignments.index')
                ->with('success', 'Mapping pegawai berhasil dihapus');
        } catch (\Exception $e) {
            return redirect()->route('superadmin.employee-assignments.index')
                ->with('error', 'Gagal menghapus mapping pegawai');
        }
    }

    /**
     * Toggle active status.
     */
    public function toggleStatus(EmployeeAssignment $employeeAssignment)
    {
        $employeeAssignment->is_active = !$employeeAssignment->is_active;
        $employeeAssignment->save();

        $status = $employeeAssignment->is_active ? 'diaktifkan' : 'dinonaktifkan';
        return redirect()->route('superadmin.employee-assignments.index')
            ->with('success', "Mapping berhasil {$status}");
    }
}
