<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\LearningDeviceModel;
use App\Models\LearningDeviceTpModel;
use App\Models\LearningDeviceProtaModel;
use App\Models\LearningDevicePekanEfektifModel;
use App\Controllers\Guru\Traits\DeviceHelperTrait;
use Config\Database;

class ProtaController extends BaseController
{
    use DeviceHelperTrait;

    protected $deviceModel;
    protected $deviceTpModel;
    protected $protaModel;
    protected $pekanEfektifModel;

    public function __construct()
    {
        $this->deviceModel       = new LearningDeviceModel();
        $this->deviceTpModel     = new LearningDeviceTpModel();
        $this->protaModel        = new LearningDeviceProtaModel();
        $this->pekanEfektifModel = new LearningDevicePekanEfektifModel();
    }

    /**
     * Halaman PROTA (Program Tahunan)
     */
    public function prota($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);

        if (empty($tps)) {
            return redirect()->to('/guru/learning-devices/tp/' . $id)->with('error', 'Harap rumuskan Tujuan Pembelajaran (TP) terlebih dahulu!');
        }

        $rpeRecord = $this->pekanEfektifModel->where('learning_device_id', $id)->first();
        $s1Eff = 18;
        $s2Eff = 18;
        if ($rpeRecord) {
            $rpeData = json_decode($rpeRecord['content_json'], true);
            $s1Eff = 0;
            $s2Eff = 0;
            if (!empty($rpeData['sem1'])) {
                foreach ($rpeData['sem1'] as $m) $s1Eff += intval($m['effective_weeks']);
            }
            if (!empty($rpeData['sem2'])) {
                foreach ($rpeData['sem2'] as $m) $s2Eff += intval($m['effective_weeks']);
            }
        }
        $totalEffectiveWeeks = $s1Eff + $s2Eff;

        $existingProta = $this->protaModel->where('learning_device_id', $id)->first();
        if (!$existingProta) {
            $halfCount = ceil(count($tps) / 2);
            foreach ($tps as $idx => $tp) {
                $sem = ($idx < $halfCount) ? 1 : 2;
                $estimatedWeeks = ceil($tp['allocated_hours'] / 4);
                $this->protaModel->insert([
                    'learning_device_id' => $id,
                    'tp_id'              => $tp['id'],
                    'semester'           => $sem,
                    'allocated_weeks'    => $estimatedWeeks,
                    'allocated_hours'    => $tp['allocated_hours'],
                    'notes'              => ''
                ]);
            }
        }

        $prota = $this->protaModel->getDetailedProta($id);
        $protaMap = [];
        foreach ($prota as $p) {
            $protaMap[$p['tp_id']] = $p;
        }

        $data = [
            'title'               => 'Program Tahunan (PROTA)',
            'device'              => $device,
            'tps'                 => $tps,
            'protaMap'            => $protaMap,
            'totalEffectiveWeeks' => $totalEffectiveWeeks,
            's1EffectiveWeeks'    => $s1Eff,
            's2EffectiveWeeks'    => $s2Eff
        ];

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

    /**
     * POST: Simpan PROTA
     */
    public function saveProtaAction($id)
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir.']);
        }

        $teacher = $this->getTeacher();
        $device = $this->deviceModel->where('id', $id)->where('user_id', $teacher['user_id'])->first();
        if (!$device) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Dokumen tidak ditemukan.']);
        }

        $protaPost = $this->request->getPost('prota');
        if (!is_array($protaPost)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data Prota tidak valid.']);
        }

        $db = Database::connect();
        $db->transStart();

        $db->table('learning_device_prota')->where('learning_device_id', $id)->delete();
        foreach ($protaPost as $tpId => $pData) {
            $this->protaModel->insert([
                'learning_device_id' => $id,
                'tp_id'              => $tpId,
                'semester'           => intval($pData['semester']) ?: 1,
                'allocated_weeks'    => intval($pData['allocated_weeks']) ?: 0,
                'allocated_hours'    => intval($pData['allocated_hours']) ?: 0,
                'notes'              => trim($pData['notes']) ?: '',
            ]);
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Gagal menyimpan Program Tahunan.']);
        }

        return $this->response->setJSON(['status' => 'success', 'message' => 'Program Tahunan berhasil disimpan.']);
    }

    /**
     * GET: AI Generate Prota Draft
     */
    public function protaGenerateAi($id)
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir.']);
        }

        $teacher = $this->getTeacher();
        $device = $this->deviceModel->getDetail($id, $teacher['user_id']);
        if (!$device) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Dokumen tidak ditemukan.']);
        }

        $tps = $this->deviceTpModel->getByDevice($id);
        if (empty($tps)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Tujuan Pembelajaran belum dirumuskan. Silakan isi TP terlebih dahulu.']);
        }

        $rpeRecord = $this->pekanEfektifModel->where('learning_device_id', $id)->first();
        $s1Eff = 18;
        $s2Eff = 18;
        if ($rpeRecord) {
            $rpeData = json_decode($rpeRecord['content_json'], true);
            $s1Eff = 0;
            $s2Eff = 0;
            if (!empty($rpeData['sem1'])) {
                foreach ($rpeData['sem1'] as $m) $s1Eff += intval($m['effective_weeks']);
            }
            if (!empty($rpeData['sem2'])) {
                foreach ($rpeData['sem2'] as $m) $s2Eff += intval($m['effective_weeks']);
            }
        }

        $aiService = new \App\Services\LearningDeviceAiService();
        $res = $aiService->generateProtaDraft($tps, $s1Eff, $s2Eff, $device);

        return $this->response->setJSON($res);
    }
}
