<?php

namespace App\Controllers\Master;

use App\Controllers\BaseController;
use App\Models\Master\JadwalModel;

class Jadwal extends BaseController
{
    protected $jadwal;

    public function __construct()
    {
        $this->jadwal = new JadwalModel();
    }

    // ===============================
    // INDEX
    // ===============================
    public function index()
    {
        return view('master/jadwal/index', [
            'title' => 'Jadwal Pelajaran',
            'subjects' => $this->jadwal->getSubjects(),
            'gurus' => $this->jadwal->getGurus()
        ]);
    }

    // ===============================
    // LOAD DATA (GRID)
    // ===============================
    public function data()
    {
        return $this->response->setJSON(
            $this->jadwal->getGrid(
                $this->request->getGet('tahun_ajaran'),
                $this->request->getGet('semester'),
                $this->request->getGet('kelas_id')
            )
        );
    }

    // ===============================
    // SIMPAN / UPDATE SLOT JADWAL
    // ===============================
    public function store()
    {
        $data = [
            'tahun_ajaran' => $this->request->getPost('tahun_ajaran'),
            'semester' => $this->request->getPost('semester'),
            'kelas_id' => $this->request->getPost('kelas_id'),
            'hari' => $this->request->getPost('hari'),
            'jam_ke' => $this->request->getPost('jam_ke'),
            'subject_id' => $this->request->getPost('subject_id'),
            'guru_id' => $this->request->getPost('guru_id'),
            'ruang' => $this->request->getPost('ruang'),
        ];

        // 🚫 CEK BENTROK
        $bentrok = $this->jadwal->cekBentrokGuru($data);

        if ($bentrok) {
            return $this->response->setJSON([
                'status' => false,
                'msg' => 'Guru sudah mengajar di kelas lain pada jam yang sama!'
            ]);
        }

        
        // 🧹 HAPUS SLOT LAMA (SLOT YANG SAMA)
        $this->jadwal->where([
            'tahun_ajaran' => $data['tahun_ajaran'],
            'semester' => $data['semester'],
            'kelas_id' => $data['kelas_id'],
            'hari' => $data['hari'],
            'jam_ke' => $data['jam_ke'],
        ])->delete();

        // ✅ INSERT BARU
        $this->jadwal->insert($data);

        return $this->response->setJSON([
            'status' => true,
            'msg' => 'Jadwal berhasil disimpan'
        ]);
    }

    // ===============================
    // HAPUS SLOT
    // ===============================
    public function delete()
    {
        $this->jadwal->where([
            'kelas_id' => $this->request->getPost('kelas_id'),
            'hari' => $this->request->getPost('hari'),
            'jam_ke' => $this->request->getPost('jam_ke')
        ])->delete();

        return $this->response->setJSON(['status' => true]);
    }
}
