<?php

namespace App\Controllers\Guru;

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

class PromesController extends BaseController
{
    use DeviceHelperTrait;

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

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

    /**
     * Halaman PROMES (Program Semester)
     */
    public function promes($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!');
        }

        $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);
        $promes = $this->promesModel->getPromesData($id);

        $protaMap = [];
        foreach ($prota as $p) {
            $protaMap[$p['tp_id']] = $p;
        }

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

        $rpeRecord = $this->pekanEfektifModel->where('learning_device_id', $id)->first();
        if ($rpeRecord) {
            $rpeData = json_decode($rpeRecord['content_json'], true);
        } else {
            $rpeData = $this->calculateRpeFromKaldik($id);
        }

        $data = [
            'title'     => 'Program Semester (PROMES)',
            'device'    => $device,
            'tps'       => $tps,
            'protaMap'  => $protaMap,
            'promesMap' => $promesMap,
            'rpeData'   => $rpeData
        ];

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

    /**
     * POST: Simpan PROMES
     */
    public function savePromesAction($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.']);
        }

        $promesPost = $this->request->getPost('promes');

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

        $db->table('learning_device_promes')->where('learning_device_id', $id)->delete();
        if (is_array($promesPost)) {
            foreach ($promesPost as $tpId => $months) {
                if (!is_array($months)) continue;
                foreach ($months as $monthNum => $weeks) {
                    if (!is_array($weeks)) continue;
                    foreach ($weeks as $weekNum => $hours) {
                        $hours = intval($hours);
                        if ($hours > 0) {
                            $this->promesModel->insert([
                                'learning_device_id' => $id,
                                'tp_id'              => $tpId,
                                'month'              => intval($monthNum),
                                'week_number'        => intval($weekNum),
                                'allocated_hours'    => $hours,
                            ]);
                        }
                    }
                }
            }
        }

        $db->transComplete();

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

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

    /**
     * GET: AI Generate Promes Draft
     */
    public function promesGenerateAi($id, $semester)
    {
        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.']);
        }

        $semester = intval($semester);
        if ($semester !== 1 && $semester !== 2) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Semester tidak valid.']);
        }

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

        $prota = $this->protaModel->getDetailedProta($id);
        if (empty($prota)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Program Tahunan (PROTA) belum diisi. Silakan isi Prota terlebih dahulu.']);
        }

        $rpeRecord = $this->pekanEfektifModel->where('learning_device_id', $id)->first();
        if ($rpeRecord) {
            $rpeData = json_decode($rpeRecord['content_json'], true);
        } else {
            $rpeData = $this->calculateRpeFromKaldik($id);
        }

        $aiService = new \App\Services\LearningDeviceAiService();
        $res = $aiService->generatePromesDraft($prota, $rpeData, $device, $semester);

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