<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SubjectTargetModel;

class SubjectTarget extends BaseController
{
    protected SubjectTargetModel $targetModel;

    public function __construct()
    {
        $this->targetModel = new SubjectTargetModel();
    }

    // Halaman utama master target
    public function index()
    {
        $data = [
            'title' => 'Master Target Jam per Mapel',
            'targets' => $this->targetModel->getAllWithNames(),
        ];
        return view('admin/subject_target/index', $data);
    }

    // Form edit target
    public function edit($subjectId)
    {
        $subjectModel = new \App\Models\SchoolSubjectModel();
        $gradeModel = new \App\Models\GradeModel();

        $subject = $subjectModel->find($subjectId);
        if (!$subject) {
            return redirect()->to('/subject-target')->with('error', 'Mapel tidak ditemukan');
        }

        $grades = $gradeModel->orderBy('order')->findAll();
        $targets = $this->targetModel->getBySubject($subjectId);

        $targetMap = [];
        foreach ($targets as $t) {
            $targetMap[$t['grade_id']] = $t['target_hours'];
        }

        $data = [
            'title' => 'Edit Target Jam: ' . $subject['name'],
            'subject' => $subject,
            'grades' => $grades,
            'targetMap' => $targetMap,
        ];
        return view('admin/subject_target/edit', $data);
    }

    // Update target
    public function update($subjectId)
    {
        $rules = [
            'targets' => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->with('error', 'Data tidak valid');
        }

        $targets = $this->request->getPost('targets');
        foreach ($targets as $gradeId => $targetHours) {
            $targetHours = (int)$targetHours;
            if ($targetHours >= 0) {
                $this->targetModel->setTarget($subjectId, $gradeId, $targetHours);
            }
        }

        return redirect()->to('/subject-target')->with('success', 'Target jam berhasil diperbarui');
    }
}