<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\LearningDeviceModel;
use App\Models\LearningDeviceTpModel;
use App\Models\LearningDevicePromesModel;
use App\Models\LearningDeviceRpeModel;
use App\Controllers\Guru\Traits\DeviceHelperTrait;

class PenilaianController extends BaseController
{
    use DeviceHelperTrait;

    protected $deviceModel;
    protected $deviceTpModel;
    protected $promesModel;
    protected $rpeModel;

    public function __construct()
    {
        $this->deviceModel   = new LearningDeviceModel();
        $this->deviceTpModel = new LearningDeviceTpModel();
        $this->promesModel   = new LearningDevicePromesModel();
        $this->rpeModel      = new LearningDeviceRpeModel();
    }

    /**
     * Halaman Perencanaan Penilaian
     */
    public function penilaian($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return redirect()->to('/dashboard')->with('error', 'Data guru tidak ditemukan!');
        }

        $device = $this->deviceModel->getDetail($id, $teacher['user_id']);
        if (!$device) {
            return redirect()->to('/guru/learning-devices')->with('error', 'Dokumen tidak ditemukan.');
        }

        $tps = $this->deviceTpModel->getByDevice($id);
        $promes = $this->promesModel->getPromesData($id);

        if (empty($tps) || empty($promes)) {
            return redirect()->to('/guru/learning-devices/promes/' . $id)->with('error', 'Harap isi Program Semester (PROMES) terlebih dahulu agar jadwal penilaian dapat disinkronkan!');
        }

        $rpeRecord = $this->rpeModel->where('learning_device_id', $id)->first();

        $promesMap = [];
        foreach ($promes as $pr) {
            $promesMap[$pr['tp_id']][$pr['month']][$pr['week_number']] = $pr['allocated_hours'];
        }

        $data = [
            'title'         => 'Perencanaan Penilaian',
            'device'        => $device,
            'tps'           => $tps,
            'promesMap'     => $promesMap,
            'penilaianData' => $rpeRecord ? json_decode($rpeRecord['content_json'], true) : null
        ];

        return view('guru/learning_device/penilaian', $data);
    }

    /**
     * POST: Generate Perencanaan Penilaian via AI
     * Delegasikan ke RpeController karena sama logikanya
     */
    public function generatePenilaianAction($id)
    {
        // Delegasikan ke RPE logic — penilaian menyimpan di rpe (tabel learning_device_rpe)
        $rpeController = new RpeController();
        return $rpeController->saveRpeAction($id);
    }

    /**
     * POST: Simpan Perencanaan Penilaian manual
     */
    public function savePenilaianAction($id)
    {
        // Delegasikan ke RPE logic
        $rpeController = new RpeController();
        return $rpeController->saveRpeAction($id);
    }
}
