<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\GradeModel;
use App\Models\SchoolSubjectModel;
use App\Models\AiKbCpModel;
use App\Models\LearningDeviceModel;
use App\Controllers\Guru\Traits\DeviceHelperTrait;

class CpController extends BaseController
{
    use DeviceHelperTrait;

    protected $gradeModel;
    protected $schoolSubjectModel;
    protected $cpModel;
    protected $deviceModel;

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

    /**
     * Halaman Edit Capaian Pembelajaran (CP) Mandiri Guru
     */
    public function cp($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!');
        }

        $grade = $this->gradeModel->find($device['grade_id']);
        $phase = $this->deducePhase($grade ? $grade['name'] : 'VII');

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

        $cp = $this->cpModel->groupStart()
            ->where('subject_id', $subjectId)
            ->orWhere('subject_name', $subjectName)
            ->groupEnd()
            ->where('phase', $phase)
            ->first();

        $masterCpElements = $cp ? $cp['elements'] : '[]';

        $data = [
            'title'           => 'Capaian Pembelajaran (CP) - ' . $device['subject_name'],
            'device'          => $device,
            'masterCpElements' => $masterCpElements,
        ];

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

    /**
     * POST: Simpan Teks CP yang Diedit Guru
     */
    public function saveCp($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.']);
        }

        $cpContent = $this->request->getPost('cp_content');
        if (empty(trim($cpContent))) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Teks CP tidak boleh kosong.']);
        }

        $this->deviceModel->update($id, ['cp_content' => $cpContent]);

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

    /**
     * POST: Simpan CP Mandiri Guru (Elemen CP)
     */
    public function saveCpAction($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!');
        }

        $elementsInput = $this->request->getPost('elements');
        $elements = null;
        if (is_array($elementsInput) && !empty($elementsInput['name'])) {
            $parsedElements = [];
            foreach ($elementsInput['name'] as $idx => $name) {
                if (!empty(trim($name))) {
                    $parsedElements[] = [
                        'name' => trim($name),
                        'description' => trim($elementsInput['description'][$idx] ?? '')
                    ];
                }
            }
            if (!empty($parsedElements)) {
                $elements = json_encode($parsedElements);
            }
        }

        if (empty($elements)) {
            return redirect()->back()->with('error', 'Minimal harus ada 1 Elemen CP dan Deskripsinya.')->withInput();
        }

        $this->deviceModel->update($id, ['cp_elements' => $elements]);

        // SINKRONISASI KE MASTER BANK CP ADMIN (ai_kb_cp)
        $grade = $this->gradeModel->find($device['grade_id']);
        $phase = $this->deducePhase($grade ? $grade['name'] : 'VII');
        $schoolSubject = $this->schoolSubjectModel->find($device['school_subject_id']);
        $subjectName = $schoolSubject ? $schoolSubject['name'] : '';
        $subjectId = $schoolSubject ? $schoolSubject['subject_id'] : null;

        $existingMaster = $this->cpModel->groupStart()
            ->where('subject_id', $subjectId)
            ->orWhere('subject_name', $subjectName)
            ->groupEnd()
            ->where('phase', $phase)
            ->first();

        if ($existingMaster) {
            $this->cpModel->update($existingMaster['id'], [
                'elements' => $elements
            ]);
        } else {
            $this->cpModel->insert([
                'academic_year_id' => $device['academic_year_id'],
                'user_id'          => $teacher['user_id'],
                'subject_id'       => $subjectId,
                'subject_name'     => $subjectName,
                'phase'            => $phase,
                'content'          => ' ',
                'elements'         => $elements,
            ]);
        }

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