<?php

namespace App\Controllers\Master;

use App\Controllers\BaseController;
use App\Models\KelasModel;
use App\Services\RombelGenerator;
use App\Services\RombelSyncService;

class Kelas extends BaseController
{
    protected $kelas;

    public function __construct()
    {
        $this->kelas = new KelasModel();
    }

    public function index()
    {
        return view('master/kelas/index');
    }

    public function data()
    {
        $request = service('request');

        $draw = $request->getGet('draw');
        $start = $request->getGet('start');
        $length = $request->getGet('length');
        $search = $request->getGet('search')['value'];

        $builder = $this->kelas;

        if ($search) {
            $builder->like('nama_kelas', $search);
        }

        $totalFiltered = $builder->countAllResults(false);

        $data = $builder
            ->orderBy('id', 'ASC')
            ->findAll($length, $start);

        return $this->response->setJSON([
            'draw' => intval($draw),
            'recordsTotal' => $this->kelas->countAll(),
            'recordsFiltered' => $totalFiltered,
            'data' => $data
        ]);
    }

    public function create()
    {
        return view('master/kelas/create', [
            'tahun_ajaran' => '2024/2025'
        ]);
    }

    public function store()
    {
        $rules = [
            'kode_kelas' => 'required',
            'nama_kelas' => 'required|min_length[3]',
            'jenjang' => 'required',
            'tingkat' => 'required',
            'tahun_ajaran' => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }

        // CEK UNIQUE
        if ($this->kelas->where('kode_kelas', $this->request->getPost('kode_kelas'))->first()) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Kode kelas sudah digunakan');
        }

        $data = [
            'kode_kelas' => trim($this->request->getPost('kode_kelas')),
            'nama_kelas' => trim($this->request->getPost('nama_kelas')),
            'jenjang' => $this->request->getPost('jenjang'),
            'tingkat' => $this->request->getPost('tingkat'),
            'program' => $this->request->getPost('program'),
            'tahun_ajaran' => $this->request->getPost('tahun_ajaran'),
            'kapasitas' => $this->request->getPost('kapasitas') ?? 30,
            'wali_guru_id' => null,
            'status' => 'aktif',
            'created_by' => session('user_id') ?? 1,
        ];

        // ✅ INSERT SEKALI & AMBIL ID
        $kelasId = $this->kelas->insert($data);

        // ✅ AMBIL DATA KELAS
        $kelas = $this->kelas->find($kelasId);

        // ✅ AUTO GENERATE ROMBEL
        RombelGenerator::generate($kelas);

        return redirect()->to('master/kelas')
            ->with('success', 'Kelas & rombel berhasil dibuat');
    }

    public function edit($id)
    {
        $kelas = $this->kelas->find($id);

        if (!$kelas) {
            return redirect()->to('master/kelas')
                ->with('error', 'Data kelas tidak ditemukan');
        }

        return view('master/kelas/edit', [
            'kelas' => $kelas
        ]);
    }

    public function update($id)
    {
        $kelas = $this->kelas->find($id);

        if (!$kelas) {
            return redirect()->to('master/kelas')
                ->with('error', 'Data kelas tidak ditemukan');
        }

        $rules = [
            'nama_kelas' => 'required|min_length[3]',
            'jenjang' => 'required',
            'tingkat' => 'required',
            'tahun_ajaran' => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors());
        }

        // 🔥 SIMPAN TINGKAT LAMA
        $tingkatLama = $kelas['tingkat'];
        $tingkatBaru = $this->request->getPost('tingkat');

        // CEK UNIQUE KODE (KECUALI DIRI SENDIRI)
        $kode = $this->request->getPost('kode_kelas');

        if (
            $this->kelas
                ->where('kode_kelas', $kode)
                ->where('id !=', $id)
                ->first()
        ) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Kode kelas sudah digunakan');
        }

        // ✅ UPDATE KELAS
        $this->kelas->update($id, [
            'kode_kelas' => $kode,
            'nama_kelas' => $this->request->getPost('nama_kelas'),
            'jenjang' => $this->request->getPost('jenjang'),
            'tingkat' => $tingkatBaru,
            'program' => $this->request->getPost('program'),
            'tahun_ajaran' => $this->request->getPost('tahun_ajaran'),
            'kapasitas' => $this->request->getPost('kapasitas'),
            'status' => $this->request->getPost('status'),
        ]);

        // 🔥 AUTO SYNC ROMBEL JIKA TINGKAT BERUBAH
        if ($tingkatLama != $tingkatBaru) {
            RombelSyncService::syncTingkat($kelas, $tingkatBaru);
        }

        return redirect()->to('master/kelas')
            ->with('success', 'Data kelas & rombel berhasil diperbarui');
    }

}

