<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\SchoolSettingModel;
use App\Models\LearningDeviceModel;
use App\Models\LearningDeviceTpModel;
use App\Models\LearningDeviceKktpModel;
use App\Controllers\Guru\Traits\DeviceHelperTrait;
use Config\Database;

class KktpController extends BaseController
{
    use DeviceHelperTrait;

    protected $deviceModel;
    protected $deviceTpModel;
    protected $kktpModel;

    public function __construct()
    {
        $this->deviceModel   = new LearningDeviceModel();
        $this->deviceTpModel = new LearningDeviceTpModel();
        $this->kktpModel     = new LearningDeviceKktpModel();
    }

    /**
     * Halaman Kriteria Ketercapaian Tujuan Pembelajaran (KKTP)
     */
    public function kktp($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 atau Anda tidak memiliki akses!');
        }

        $tps = $this->deviceTpModel->getByDevice($id);
        $kktpsData = $this->kktpModel->getByDevice($id);

        $kktpMap = [];
        foreach ($kktpsData as $k) {
            $kktpMap[$k['tp_id']] = $k;
        }

        $intervalsJson = $device['kktp_intervals'] ?? '';
        $intervals = json_decode($intervalsJson, true) ?: [
            'bimbingan' => 59,
            'cukup'     => 69,
            'baik'      => 84
        ];

        $data = [
            'title'     => 'KKTP - ' . $device['subject_name'],
            'device'    => $device,
            'tps'       => $tps,
            'kktpMap'   => $kktpMap,
            'intervals' => $intervals,
        ];

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

    /**
     * POST: Generate KKTP menggunakan AI untuk TP tertentu
     */
    public function generateKktpAction($id)
    {
        set_time_limit(120);
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir, silakan login kembali.']);
        }

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

        $tpId = $this->request->getPost('tp_id');
        $tp = $this->deviceTpModel->find($tpId);
        if (!$tp || $tp['learning_device_id'] != $id) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'TP tidak valid.']);
        }

        $aiService = new \App\Services\LearningDeviceAiService();
        $res = $aiService->generateKktpForTp($tp['description'], $device['cp_content'], $device['grade_name'], $device['subject_name']);

        if ($res['status'] === 'success') {
            $indicators = is_array($res['data']['indicators']) ? implode("\n", $res['data']['indicators']) : $res['data']['indicators'];

            $saveData = [
                'learning_device_id' => $id,
                'tp_id'              => $tpId,
                'indicators'         => $indicators,
                'rubric_bimbingan'   => $res['data']['rubric_bimbingan'] ?? '',
                'rubric_cukup'       => $res['data']['rubric_cukup'] ?? '',
                'rubric_baik'        => $res['data']['rubric_baik'] ?? '',
                'rubric_sangat_baik' => $res['data']['rubric_sangat_baik'] ?? '',
            ];

            $existing = $this->kktpModel->where('tp_id', $tpId)->first();
            if ($existing) {
                $this->kktpModel->update($existing['id'], $saveData);
            } else {
                $this->kktpModel->insert($saveData);
            }

            return $this->response->setJSON([
                'status' => 'success',
                'data'   => $saveData
            ]);
        }

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

    /**
     * POST: Simpan Edit Manual KKTP (AJAX)
     */
    public function saveKktpAction($id)
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir, silakan login kembali.']);
        }

        $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.']);
        }

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

        $kktpData = $payload['kktp'] ?? [];
        $intervals = $payload['intervals'] ?? null;

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

        if ($intervals) {
            $this->deviceModel->update($id, [
                'kktp_intervals' => json_encode($intervals)
            ]);
        }

        foreach ($kktpData as $tpId => $data) {
            $saveData = [
                'learning_device_id' => $id,
                'tp_id'              => $tpId,
                'indicators'         => trim($data['indicators'] ?? ''),
                'rubric_bimbingan'   => trim($data['rubric_bimbingan'] ?? ''),
                'rubric_cukup'       => trim($data['rubric_cukup'] ?? ''),
                'rubric_baik'        => trim($data['rubric_baik'] ?? ''),
                'rubric_sangat_baik' => trim($data['rubric_sangat_baik'] ?? ''),
            ];

            $existing = $this->kktpModel->where('tp_id', $tpId)->first();
            if ($existing) {
                $this->kktpModel->update($existing['id'], $saveData);
            } else {
                $this->kktpModel->insert($saveData);
            }
        }

        $db->transComplete();

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

        return $this->response->setJSON(['status' => 'success', 'message' => 'Seluruh KKTP berhasil disimpan!']);
    }

    /**
     * Halaman Cetak KKTP
     */
    public function printKktp($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 atau Anda tidak memiliki akses!');
        }

        $kktpsData = $this->kktpModel->getByDevice($id);

        $schoolSettingModel = new SchoolSettingModel();
        $settings = $schoolSettingModel->getSettings();

        $intervalsJson = $device['kktp_intervals'] ?? '';
        $intervals = json_decode($intervalsJson, true) ?: [
            'bimbingan' => 59,
            'cukup'     => 69,
            'baik'      => 84
        ];

        $data = [
            'title'     => 'Cetak KKTP - ' . $device['subject_name'],
            'device'    => $device,
            'kktps'     => $kktpsData,
            'teacher'   => $teacher,
            'settings'  => $settings,
            'intervals' => $intervals,
        ];

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

    // ─── DOWNLOAD DOC: KKTP ─────────────────────────────────
    public function downloadKktp($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;
        $teacher = $this->getTeacher();
        $device = $this->deviceModel->getDetail($id, $teacher['user_id']);
        if (!$device) return redirect()->to('/guru/learning-devices')->with('error', 'Dokumen tidak ditemukan.');

        $kktpsData = $this->kktpModel->getByDevice($id);
        $intervalsJson = $device['kktp_intervals'] ?? '';
        $intervals = json_decode($intervalsJson, true) ?: ['bimbingan' => 59, 'cukup' => 69, 'baik' => 84];

        $schoolSettingModel = new SchoolSettingModel();
        $settings = $schoolSettingModel->getSettings();
        $device['teacher_name'] = $teacher['name'] ?? '';
        $device['teacher_nip'] = $teacher['nip'] ?? '';

        $exportService = new \App\Services\DocumentExportService();
        $fileContent = $exportService->exportKktpWord($device, $kktpsData, $intervals, $settings);

        return $this->response->setStatusCode(200)
            ->setContentType('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
            ->setHeader('Content-Disposition', 'attachment; filename="KKTP_' . $device['subject_name'] . '_Kelas_' . $device['grade_name'] . '.docx"')
            ->setBody($fileContent);
    }
}
