<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SettingJamModel;

class SettingJam extends BaseController
{
    protected $settingJamModel;

    public function __construct()
    {
        $this->settingJamModel = new SettingJamModel();
    }

    public function index()
    {
        $data = [
            'title' => 'Setting Jam Absensi',
            'guru'  => $this->settingJamModel->where('type', 'guru')->first(),
            'siswa' => $this->settingJamModel->where('type', 'siswa')->first(),
            'validation' => \Config\Services::validation()
        ];
        return view('admin/setting_jam/index', $data);
    }

    public function update()
    {
        // Validasi input
        if (!$this->validate([
            'guru_masuk_mulai' => 'required',
            'guru_masuk_akhir' => 'required',
            'guru_pulang_mulai' => 'required',
            'guru_pulang_akhir' => 'required',
            'siswa_masuk_mulai' => 'required',
            'siswa_masuk_akhir' => 'required',
            'siswa_pulang_mulai' => 'required',
            'siswa_pulang_akhir' => 'required',
        ])) {
            return redirect()->back()->withInput()->with('error', 'Semua jam harus diisi.');
        }

        // Update Guru
        $guru = $this->settingJamModel->where('type', 'guru')->first();
        $this->settingJamModel->update($guru['id'], [
            'jam_masuk_mulai'  => $this->request->getPost('guru_masuk_mulai'),
            'jam_masuk_akhir'  => $this->request->getPost('guru_masuk_akhir'),
            'jam_pulang_mulai' => $this->request->getPost('guru_pulang_mulai'),
            'jam_pulang_akhir' => $this->request->getPost('guru_pulang_akhir'),
        ]);

        // Update Siswa
        $siswa = $this->settingJamModel->where('type', 'siswa')->first();
        $this->settingJamModel->update($siswa['id'], [
            'jam_masuk_mulai'  => $this->request->getPost('siswa_masuk_mulai'),
            'jam_masuk_akhir'  => $this->request->getPost('siswa_masuk_akhir'),
            'jam_pulang_mulai' => $this->request->getPost('siswa_pulang_mulai'),
            'jam_pulang_akhir' => $this->request->getPost('siswa_pulang_akhir'),
        ]);

        return redirect()->to('/admin/setting-jam')->with('success', 'Pengaturan jam berhasil diperbarui.');
    }
}