<?php

namespace App\Controllers\Guru;

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

class AtpController extends BaseController
{
    use DeviceHelperTrait;

    protected $deviceModel;
    protected $deviceTpModel;

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

    /**
     * Halaman Alur Tujuan Pembelajaran (ATP) Drag & Drop
     */
    public function atp($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);

        $semester1 = [];
        $semester2 = [];

        foreach ($tps as $tp) {
            if ($tp['semester'] == 2) {
                $semester2[] = $tp;
            } else {
                $semester1[] = $tp;
            }
        }

        $data = [
            'title'     => 'Alur Tujuan Pembelajaran (ATP) - ' . $device['subject_name'],
            'device'    => $device,
            'semester1' => $semester1,
            'semester2' => $semester2,
        ];

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

    /**
     * POST: Simpan urutan ATP via AJAX
     */
    public function saveAtpAction($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 (!isset($payload['semester1']) || !isset($payload['semester2'])) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data tidak valid.']);
        }

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

        $order = 1;
        foreach ($payload['semester1'] as $tpId) {
            $this->deviceTpModel->update($tpId, [
                'semester'   => 1,
                'sort_order' => $order++
            ]);
        }

        foreach ($payload['semester2'] as $tpId) {
            $this->deviceTpModel->update($tpId, [
                'semester'   => 2,
                'sort_order' => $order++
            ]);
        }

        $db->transComplete();

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

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

    // ─── PREVIEW: ATP ──────────────────────────────────────
    public function previewAtp($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) ?: [];
        $dplSelected = json_decode($device['dpl'] ?? '[]', true) ?: [];
        $pcSelected = json_decode($device['panca_cinta'] ?? '[]', 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;
        }

        $data = [
            'title' => 'Preview ATP',
            'device' => $device,
            'settings' => $settings,
            'chapters' => $chapters,
            'tpByChapter' => $tpByChapter,
            'dplText' => implode(', ', $dplSelected),
            'pcText' => implode(', ', $pcSelected),
            'schoolTypeLabel' => ($device['school_type'] === 'madrasah') ? 'Madrasah' : 'Sekolah',
        ];
        return view('guru/learning_device/preview_atp', $data);
    }

    // ─── DOWNLOAD DOC: ATP ─────────────────────────────────
    public function downloadAtp($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) ?: [];
        $chapterDplMap = json_decode($device['chapter_dpl'] ?? '{}', true) ?: [];
        $chapterKbcMap = json_decode($device['chapter_kbc'] ?? '{}', true) ?: [];

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

        $exportService = new \App\Services\DocumentExportService();
        $fileContent = $exportService->exportAtpWord($device, $tps, $chapters, $chapterDplMap, $chapterKbcMap, $settings);

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