<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ScheduleTeacherSettingModel;

class SettingsController extends BaseController
{
    protected ScheduleTeacherSettingModel $settingModel;

    public function __construct()
    {
        $this->settingModel = new ScheduleTeacherSettingModel();
    }

    // ----------------------------------------------------------
    // Halaman setting jadwal (global)
    // ----------------------------------------------------------
    public function schedule()
    {
        // Cek login & role
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }

        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';

        $data = [
            'title' => 'Pengaturan Jadwal Otomatis',
            'schedule_source'  => $scheduleSource,
        ];

        return view('settings/schedule', $data);
    }

    // ----------------------------------------------------------
    // Simpan setting global
    // ----------------------------------------------------------
    public function saveSchedule()
    {
        // Cek login & role
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }

        $rules = [
            'schedule_source'  => 'required|in_list[local,asc,manual]',
        ];

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

        $scheduleSource = $this->request->getPost('schedule_source');

        $db = \Config\Database::connect();
        $exists = $db->table('settings')->where('setting_key', 'schedule_source')->countAllResults();
        if ($exists) {
            $db->table('settings')->where('setting_key', 'schedule_source')->update(['setting_value' => $scheduleSource]);
        } else {
            $db->table('settings')->insert(['setting_key' => 'schedule_source', 'setting_value' => $scheduleSource]);
        }

        // Update session cache untuk sidebar secara langsung
        $settingsCache = session()->get('sidebar_settings_cache') ?? [];
        $settingsCache['schedule_source'] = $scheduleSource;
        session()->set('sidebar_settings_cache', $settingsCache);

        return redirect()->to('/settings/schedule')
            ->with('success', 'Pengaturan jadwal berhasil disimpan!');
    }
}