<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\TeachingJournalModel;
use App\Models\AcademicPeriodModel;

class DashboardJurnal extends BaseController
{
    protected $journalModel;
    protected $periodModel;

    public function __construct()
    {
        $this->journalModel = new TeachingJournalModel();
        $this->periodModel  = new AcademicPeriodModel();
    }

    public function index()
    {
        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.');
        }

        $periodId   = $this->request->getGet('periode');
        $activePeriod = $this->periodModel->where('is_active', 1)->first();
        $periodId = $periodId ?: ($activePeriod['id'] ?? null);

        $progress = $this->journalModel->getTeacherProgress($periodId);

        $periods = $this->periodModel->where('deleted_at', null)->orderBy('academic_year_id', 'DESC')->orderBy('semester', 'ASC')->findAll();

        $data = [
            'title'    => 'Monitoring Jurnal Mengajar',
            'progress' => $progress,
            'periodId' => $periodId,
            'periods'  => $periods,
        ];

        return view('admin/dashboard_jurnal', $data);
    }
}
