<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\GradeModel;
use App\Models\SchoolSubjectModel;
use App\Models\AiKbCpModel;
use App\Models\AiKbTpModel;
use App\Models\LearningDeviceModel;
use App\Models\LearningDeviceTpModel;
use App\Controllers\Guru\Traits\DeviceHelperTrait;
use Config\Database;

class TpController extends BaseController
{
    use DeviceHelperTrait;

    protected $gradeModel;
    protected $schoolSubjectModel;
    protected $deviceModel;
    protected $deviceTpModel;

    public function __construct()
    {
        $this->gradeModel       = new GradeModel();
        $this->schoolSubjectModel = new SchoolSubjectModel();
        $this->deviceModel      = new LearningDeviceModel();
        $this->deviceTpModel    = new LearningDeviceTpModel();
    }

    /**
     * Halaman Edit/Rumuskan Tujuan Pembelajaran (TP)
     */
    public function tp($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);

        $schoolSubject = $this->schoolSubjectModel->find($device['school_subject_id']);
        $subjectName = $schoolSubject ? $schoolSubject['name'] : '';
        $subjectId = $schoolSubject ? $schoolSubject['subject_id'] : null;

        $tpMasterModel = new AiKbTpModel();
        $masterTp = null;

        if (empty($device['chapters']) && empty($tps)) {
            $masterTp = $tpMasterModel->groupStart()
                ->where('subject_id', $subjectId)
                ->orWhere('subject_name', $subjectName)
                ->groupEnd()
                ->where('grade_id', $device['grade_id'])
                ->orderBy('id', 'DESC')
                ->first();

            if ($masterTp && !empty($masterTp['tps'])) {
                $tps = json_decode($masterTp['tps'], true) ?: [];
            }
        }

        $dplList = [
            'Keimanan dan Ketakwaan terhadap Tuhan Yang Maha Esa',
            'Kewargaan',
            'Penalaran Kritis',
            'Kreativitas',
            'Kolaborasi',
            'Kemandirian',
            'Kesehatan',
            'Komunikasi'
        ];

        $pancaCintaList = [
            'Cinta kepada Tuhan Yang Maha Esa',
            'Cinta kepada Ilmu',
            'Cinta kepada Lingkungan',
            'Cinta kepada Diri dan Sesama',
            'Cinta Tanah Air'
        ];

        $cpElements = json_decode($device['cp_elements'] ?? '[]', true);
        $cpElementNames = [];
        if (is_array($cpElements)) {
            $cpElementNames = array_column($cpElements, 'name');
        }

        $chapterCpMap = json_decode($device['chapter_cp_map'] ?? '{}', true);

        // Fetch RPE (pekan efektif) data
        $pekanEfektifModel = new \App\Models\LearningDevicePekanEfektifModel();
        $rpeRecord = $pekanEfektifModel->where('learning_device_id', $id)->first();
        $rpeData = null;
        if ($rpeRecord) {
            $rpeData = json_decode($rpeRecord['content_json'], true);
        }

        $effectiveWeeksS1 = 0;
        $effectiveWeeksS2 = 0;
        if ($rpeData) {
            if (isset($rpeData['sem1'])) {
                foreach ($rpeData['sem1'] as $row) {
                    $effectiveWeeksS1 += intval($row['effective_weeks'] ?? 0);
                }
            }
            if (isset($rpeData['sem2'])) {
                foreach ($rpeData['sem2'] as $row) {
                    $effectiveWeeksS2 += intval($row['effective_weeks'] ?? 0);
                }
            }
        } else {
            // Fallback default values
            $effectiveWeeksS1 = 18; 
            $effectiveWeeksS2 = 16;
        }

        $data = [
            'title'            => 'Tujuan Pembelajaran (TP) - ' . $device['subject_name'],
            'device'           => $device,
            'tps'              => $tps,
            'masterTp'         => $masterTp,
            'dplList'          => $dplList,
            'pancaCintaList'   => $pancaCintaList,
            'cpElementNames'   => $cpElementNames,
            'chapterCpMap'     => $chapterCpMap,
            'effectiveWeeksS1' => $effectiveWeeksS1,
            'effectiveWeeksS2' => $effectiveWeeksS2,
        ];

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

    /**
     * POST: Simpan TP Mandiri Guru
     */
    public function saveTpAction($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->getTeacher();
        $device = $this->deviceModel->where('id', $id)->where('user_id', $teacher['user_id'])->first();
        if (!$device) {
            return redirect()->to('/guru/learning-devices')->with('error', 'Dokumen tidak ditemukan atau Anda tidak memiliki akses!');
        }

        $tpsPost = $this->request->getPost('tps');
        if (!is_array($tpsPost)) {
            $tpsPost = [];
        }

        $chaptersJson = $this->request->getPost('chapters_json');
        $dplJson = $this->request->getPost('dpl_json');
        $pancaCintaJson = $this->request->getPost('panca_cinta_json');
        $chapterCpMapRaw = $this->request->getPost('chapter_cp_map');
        // Per-chapter DPL & KBC
        $chapterDplJson = $this->request->getPost('chapter_dpl_json');
        $chapterKbcJson = $this->request->getPost('chapter_kbc_json');

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

        if ($chaptersJson) {
            $updateDevice = [
                'chapters' => $chaptersJson,
            ];

            // DPL/KBC global — hanya update jika dikirim (backward compat)
            if ($dplJson !== null) {
                $updateDevice['dpl'] = $dplJson;
            }
            if ($pancaCintaJson !== null) {
                $updateDevice['panca_cinta'] = $pancaCintaJson;
            }

            // Per-chapter DPL & KBC (prioritas baru)
            if ($chapterDplJson) {
                $updateDevice['chapter_dpl'] = $chapterDplJson;
            }
            if ($chapterKbcJson) {
                $updateDevice['chapter_kbc'] = $chapterKbcJson;
            }

            if (!empty($chapterCpMapRaw)) {
                $updateDevice['chapter_cp_map'] = $chapterCpMapRaw;
            }

            $this->deviceModel->update($id, $updateDevice);
        }

        // Hapus draf TP lama
        $db->table('learning_device_tps')->where('learning_device_id', $id)->delete();

        $chapters = json_decode($chaptersJson ?: '[]', true) ?: [];
        $totalTps = 0;
        foreach ($tpsPost as $tp) {
            if (!empty(trim($tp['description']))) $totalTps++;
        }
        // Fallback tpsPerChapter hanya untuk recalculate jika chapter tidak tersedia
        $tpsPerChapter = (count($chapters) > 0 && $totalTps > 0)
            ? (int) ceil($totalTps / count($chapters))
            : $totalTps;

        $tpsForBank = [];
        $index = 1;
        $chapterIdx = 0;
        $tpInChapter = 0;
        foreach ($tpsPost as $tp) {
            if (empty(trim($tp['description']))) continue;

            // Baca chapter langsung dari POST jika ada, fallback ke aritmatika
            $currentChapter = trim($tp['chapter'] ?? '');
            if (empty($currentChapter)) {
                $currentChapter = $chapters[$chapterIdx] ?? '';
                $tpInChapter++;
                if ($tpInChapter >= $tpsPerChapter && $chapterIdx < count($chapters) - 1) {
                    $chapterIdx++;
                    $tpInChapter = 0;
                }
            }

            $tpData = [
                'learning_device_id' => $id,
                'code'               => trim($tp['code']) ?: ('TP-' . $index),
                'description'        => trim($tp['description']),
                'allocated_hours'    => intval($tp['allocated_hours']) ?: 8,
                'sort_order'         => $index,
                'chapter'            => $currentChapter,
            ];

            $this->deviceTpModel->insert($tpData);

            $tpsForBank[] = [
                'code' => $tpData['code'],
                'description' => $tpData['description'],
                'allocated_hours' => $tpData['allocated_hours']
            ];
            $index++;
            $tpInChapter++;

            if ($tpInChapter >= $tpsPerChapter && $chapterIdx < count($chapters) - 1) {
                $chapterIdx++;
                $tpInChapter = 0;
            }
        }

        // Simpan ke Master Bank TP Admin (ai_kb_tp)
        if ($chaptersJson) {
            $schoolSubject = $this->schoolSubjectModel->find($device['school_subject_id']);
            $subjectName = $schoolSubject ? $schoolSubject['name'] : '';
            $subjectId = $schoolSubject ? $schoolSubject['subject_id'] : null;

            $tpMasterModel = new AiKbTpModel();

            $existingMaster = $tpMasterModel->groupStart()
                ->where('subject_id', $subjectId)
                ->orWhere('subject_name', $subjectName)
                ->groupEnd()
                ->where('grade_id', $device['grade_id'])
                ->first();

            if ($existingMaster) {
                $tpMasterModel->update($existingMaster['id'], [
                    'chapters'    => $chaptersJson,
                    'dpl'         => $dplJson,
                    'panca_cinta' => $pancaCintaJson,
                    'tps'         => json_encode($tpsForBank)
                ]);
            } else {
                $grade = $this->gradeModel->find($device['grade_id']);
                $tpMasterModel->insert([
                    'academic_year_id' => $device['academic_year_id'],
                    'user_id'          => $teacher['user_id'],
                    'subject_id'       => $subjectId,
                    'subject_name'     => $subjectName,
                    'grade_id'         => $device['grade_id'],
                    'grade_name'       => $grade ? $grade['name'] : '',
                    'chapters'         => $chaptersJson,
                    'dpl'              => $dplJson,
                    'panca_cinta'      => $pancaCintaJson,
                    'tps'              => json_encode($tpsForBank)
                ]);
            }
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Gagal menyimpan Tujuan Pembelajaran.')->withInput();
        }

        if (empty($tpsPost)) {
            return redirect()->to('/guru/learning-devices/tp/' . $id)
                ->with('success', 'Data Bab berhasil disimpan. Silakan lanjutkan merumuskan TP.');
        }

        return redirect()->to('/guru/learning-devices?device_id=' . $id)
            ->with('success', 'Tujuan Pembelajaran berhasil disimpan!');
    }

    /**
     * POST: Panggil AI untuk merumuskan TP berbasis Bab & Karakter
     */
    public function generateTpAction($id)
    {
        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 atau Anda tidak memiliki akses.']);
        }

        $chaptersPost = $this->request->getPost('chapters');
        $dplPost = $this->request->getPost('dpl') ?? [];
        $pancaCintaPost = $this->request->getPost('panca_cinta') ?? [];
        // Per-chapter DPL & KBC (JSON string dari AJAX)
        $chapterDplMapRaw = $this->request->getPost('chapter_dpl_map');
        $chapterKbcMapRaw = $this->request->getPost('chapter_kbc_map');
        $chapterCpMapRaw  = $this->request->getPost('chapter_cp_map');
        $chapterDplMap = $chapterDplMapRaw ? json_decode($chapterDplMapRaw, true) : [];
        $chapterKbcMap = $chapterKbcMapRaw ? json_decode($chapterKbcMapRaw, true) : [];
        $chapterCpMap  = $chapterCpMapRaw  ? json_decode($chapterCpMapRaw, true)  : [];

        $tpsPerChapter = intval($this->request->getPost('tps_per_chapter')) ?: 4;

        if (empty($chaptersPost)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Daftar Bab/Materi Pokok tidak boleh kosong.']);
        }

        if (is_array($chaptersPost)) {
            $chapters = array_filter(array_map('trim', $chaptersPost));
        } else {
            $chapters = array_filter(array_map('trim', preg_split('/[\r\n,]+/', $chaptersPost)));
        }

        if (empty($chapters)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Daftar Bab/Materi Pokok tidak valid.']);
        }

        $aiService = new \App\Services\LearningDeviceAiService();
        $res = $aiService->generateTpByChaptersAndCharacters(
            $device['cp_elements'] ?? '',
            $device['subject_name'],
            $device['phase'],
            $device['grade_name'],
            $chapters,
            $chapterDplMap,     // DPL per-chapter (array with chapter-index keys)
            $chapterKbcMap,     // KBC per-chapter (array with chapter-index keys)
            $device['school_type'],
            $tpsPerChapter,
            $chapterCpMap       // CP Elements per-chapter (multi-select array)
        );

        // Cek error dari AI
        if ($res['status'] === 'error') {
            return $this->response->setJSON($res);
        }

        $decoded = is_array($res['data']) ? $res['data'] : (json_decode($res['data'], true) ?: []);

        // Tag setiap TP dengan nama babnya berdasarkan posisi/urutan
        $chapters = array_values($chapters);
        $totalChaps = count($chapters);
        foreach ($decoded as $tpIdx => &$tpItem) {
            $chapIdx = (int)floor($tpIdx / $tpsPerChapter);
            if ($chapIdx >= $totalChaps) $chapIdx = $totalChaps - 1;
            $tpItem['chapter'] = $chapters[$chapIdx] ?? '';
        }
        unset($tpItem);

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

    /**
     * POST: Panggil AI untuk merumuskan TP dari CP
     */
    public function generateTp($id)
    {
        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.']);
        }

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

        if ($res['status'] === 'error') {
            return $this->response->setJSON($res);
        }

        $tps = $res['data'];

        $db = Database::connect();
        $db->table('learning_device_tps')->where('learning_device_id', $id)->delete();

        $index = 1;
        foreach ($tps as $tp) {
            $this->deviceTpModel->insert([
                'learning_device_id' => $id,
                'code'               => $tp['code'] ?? ('TP-' . $index),
                'description'        => $tp['description'],
                'allocated_hours'    => $tp['allocated_hours'] ?? 8,
                'sort_order'         => $index,
            ]);
            $index++;
        }

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Draft Tujuan Pembelajaran (TP) berhasil dirumuskan oleh AI!',
            'data'    => $this->deviceTpModel->getByDevice($id)
        ]);
    }

    /**
     * POST: Simpan seluruh edit TP
     */
    public function saveTps($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.']);
        }

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

        $db = Database::connect();
        $db->table('learning_device_tps')->where('learning_device_id', $id)->delete();

        $index = 1;
        foreach ($tpsPost as $tp) {
            if (empty(trim($tp['description']))) continue;

            $this->deviceTpModel->insert([
                'learning_device_id' => $id,
                'code'               => trim($tp['code']) ?: ('TP-' . $index),
                'description'        => trim($tp['description']),
                'allocated_hours'    => intval($tp['allocated_hours']) ?: 8,
                'sort_order'         => $index,
            ]);
            $index++;
        }

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Daftar Tujuan Pembelajaran (TP) berhasil disimpan!',
            'nextUrl' => '/guru/learning-devices/atp/' . $id
        ]);
    }

    // ─── PREVIEW: CP + TP ─────────────────────────────────
    public function previewCpTP($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.');

        $tps = $this->deviceTpModel->getByDevice($id);
        $chapters = json_decode($device['chapters'] ?? '[]', true) ?: [];
        $elements = json_decode($device['cp_elements'] ?? '[]', true);

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

        $tpByChapter = [];
        foreach ($tps as $tp) {
            $tpByChapter[$tp['chapter'] ?? ''][] = $tp;
        }
        $chapterCpMap = json_decode($device['chapter_cp_map'] ?? '{}', true);

        $data = [
            'title' => 'Preview CP & TP',
            'device' => $device,
            'settings' => $settings,
            'chapters' => $chapters,
            'elements' => $elements,
            'tpByChapter' => $tpByChapter,
            'chapterCpMap' => $chapterCpMap,
            'cpText' => $device['cp_content'] ?? '',
            'schoolTypeLabel' => ($device['school_type'] === 'madrasah') ? 'Madrasah' : 'Sekolah',
        ];
        return view('guru/learning_device/preview_cp_tp', $data);
    }

    // ─── DOWNLOAD DOC: CP + TP ─────────────────────────────
    public function downloadCpTP($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.');

        $tps = $this->deviceTpModel->getByDevice($id);
        $chapters = json_decode($device['chapters'] ?? '[]', true) ?: [];
        $elements = json_decode($device['cp_elements'] ?? '[]', true);

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

        $exportService = new \App\Services\DocumentExportService();
        $chapterDplMap = json_decode($device['chapter_dpl']    ?? '{}', true) ?: [];
        $chapterKbcMap = json_decode($device['chapter_kbc']    ?? '{}', true) ?: [];
        $chapterCpMap  = json_decode($device['chapter_cp_map'] ?? '{}', true) ?: [];
        $fileContent = $exportService->exportCpTPWord($device, $tps, $chapters, $elements, $settings, $chapterDplMap, $chapterKbcMap, $chapterCpMap);


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