<?php

namespace App\Controllers\Guru;

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

class LearningDeviceSetupController extends BaseController
{
    use DeviceHelperTrait;

    protected $teacherModel;
    protected $teachingAssignmentModel;
    protected $periodModel;
    protected $gradeModel;
    protected $schoolSubjectModel;
    protected $cpModel;
    protected $deviceModel;

    public function __construct()
    {
        $this->teacherModel             = new TeacherModel();
        $this->teachingAssignmentModel  = new TeachingAssignmentModel();
        $this->periodModel              = new AcademicPeriodModel();
        $this->gradeModel               = new GradeModel();
        $this->schoolSubjectModel       = new SchoolSubjectModel();
        $this->cpModel                  = new AiKbCpModel();
        $this->deviceModel              = new LearningDeviceModel();
    }

    /**
     * Halaman List Dokumen Guru
     */
    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return redirect()->to('/dashboard')->with('error', 'Data guru tidak ditemukan!');
        }

        $activePeriod = $this->periodModel->getActive();
        $activeYearId = $activePeriod ? $activePeriod['academic_year_id'] : null;

        $selectedYearId = $this->request->getGet('academic_year_id');
        if ($selectedYearId === null) {
            $selectedYearId = $activeYearId;
        } else {
            $selectedYearId = intval($selectedYearId);
        }

        $devices = $this->deviceModel->getListByUser($teacher['user_id'], $selectedYearId);

        $db = \Config\Database::connect();
        $academicYears = $db->table('academic_years')->where('deleted_at', null)->orderBy('name', 'DESC')->get()->getResultArray();

        $selectedDeviceId = $this->request->getGet('device_id');
        if (!$selectedDeviceId) {
            $selectedDeviceId = session()->get('active_device_id');
        }

        $deviceExists = false;
        if ($selectedDeviceId) {
            foreach ($devices as $d) {
                if ($d['id'] == $selectedDeviceId) {
                    $deviceExists = true;
                    break;
                }
            }
        }

        if (!$deviceExists) {
            $selectedDeviceId = null;
        }

        if (!$selectedDeviceId && !empty($devices)) {
            $selectedDeviceId = $devices[0]['id'];
        }

        if ($selectedDeviceId) {
            session()->set('active_device_id', $selectedDeviceId);
        } else {
            session()->remove('active_device_id');
        }

        $selectedDevice = null;
        if ($selectedDeviceId) {
            foreach ($devices as $d) {
                if ($d['id'] == $selectedDeviceId) {
                    $selectedDevice = $d;
                    break;
                }
            }
        }

        $data = [
            'title'            => 'Perangkat Pembelajaran AI',
            'devices'          => $devices,
            'selectedDeviceId' => $selectedDeviceId,
            'selectedDevice'   => $selectedDevice,
            'academicYears'    => $academicYears,
            'selectedYearId'   => $selectedYearId,
            'teacher'          => $teacher,
        ];

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

    /**
     * Halaman Buat Dokumen Baru (Step 1)
     */
    public function create()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return redirect()->to('/dashboard')->with('error', 'Data guru tidak ditemukan!');
        }

        $activePeriod = $this->periodModel->getActive();
        if (!$activePeriod) {
            return redirect()->to('/guru/learning-devices')->with('error', 'Tidak ada periode akademik aktif!');
        }

        $assignedSubjects = $this->teachingAssignmentModel
            ->select('teaching_assignments.subject_id, school_subjects.name as subject_name')
            ->join('school_subjects', 'school_subjects.id = teaching_assignments.subject_id')
            ->where('teaching_assignments.teacher_id', $teacher['id'])
            ->where('teaching_assignments.academic_period_id', $activePeriod['id'])
            ->groupBy('teaching_assignments.subject_id')
            ->findAll() ?? [];

        $assignedGrades = $this->teachingAssignmentModel
            ->select('classrooms.grade_id, grades.name as grade_name')
            ->join('classrooms', 'classrooms.id = teaching_assignments.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('teaching_assignments.teacher_id', $teacher['id'])
            ->where('teaching_assignments.academic_period_id', $activePeriod['id'])
            ->groupBy('classrooms.grade_id')
            ->findAll() ?? [];

        $suggestedWeeks = $this->calculateEffectiveWeeks($activePeriod);

        $data = [
            'title'            => 'Setup Perangkat Pembelajaran',
            'assignedSubjects' => $assignedSubjects,
            'assignedGrades'   => $assignedGrades,
            'suggestedWeeks'   => $suggestedWeeks,
            'activePeriod'     => $activePeriod,
        ];

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

    /**
     * Aksi Simpan Setup Awal (POST dari Step 1)
     */
    public function storeSetup()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return redirect()->to('/dashboard')->with('error', 'Data guru tidak ditemukan!');
        }

        $activePeriod = $this->periodModel->getActive();
        if (!$activePeriod) {
            return redirect()->to('/guru/learning-devices')->with('error', 'Tidak ada periode akademik aktif!');
        }

        $rules = [
            'grade_id'          => 'required|numeric',
            'school_subject_id' => 'required|numeric',
            'school_type'       => 'required|in_list[umum,madrasah]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->with('errors', $this->validator->getErrors())->withInput();
        }

        $gradeId = $this->request->getPost('grade_id');
        $schoolSubjectId = $this->request->getPost('school_subject_id');
        $schoolType = $this->request->getPost('school_type');

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

        $schoolSubject = $this->schoolSubjectModel->find($schoolSubjectId);
        $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();

        $cpContent = $cp ? $cp['content'] : 'Teks Capaian Pembelajaran (CP) untuk mata pelajaran dan fase ini belum diisi oleh Admin di database master CP lokal. Silakan ketik atau salin teks CP resmi secara manual di sini.';

        $deviceId = $this->deviceModel->insert([
            'user_id'           => $teacher['user_id'],
            'academic_year_id'  => $activePeriod['academic_year_id'],
            'grade_id'          => $gradeId,
            'school_subject_id' => $schoolSubjectId,
            'phase'             => $phase,
            'school_type'       => $schoolType,
            'cp_content'        => ' ',
            'cp_elements'       => $cp ? $cp['elements'] : null,
        ]);

        return redirect()->to('/guru/learning-devices?device_id=' . $deviceId);
    }

    /**
     * POST: Hapus Perangkat Pembelajaran
     */
    public function delete($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->where('id', $id)->where('user_id', $teacher['user_id'])->first();
        if (!$device) {
            return redirect()->to('/guru/learning-devices')->with('error', 'Dokumen tidak ditemukan.');
        }

        $this->deviceModel->delete($id);

        if (session()->get('active_device_id') == $id) {
            session()->remove('active_device_id');
        }

        return redirect()->to('/guru/learning-devices')->with('success', 'Dokumen perangkat pembelajaran berhasil dihapus.');
    }

    /**
     * POST: Simpan API Key Gemini Pribadi milik Guru (AJAX)
     */
    public function savePersonalApiKey()
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir, silakan login kembali.']);
        }

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data guru tidak ditemukan.']);
        }

        $apiKey = $this->request->getPost('ai_api_key') ?? $this->request->getPost('gemini_api_key');
        $apiKey = trim($apiKey) !== '' ? trim($apiKey) : null;
        $aiProvider = $this->request->getPost('ai_provider') ?? 'gemini';

        $updated = $this->teacherModel->update($teacher['id'], [
            'ai_provider' => $aiProvider,
            'ai_api_key'  => $apiKey
        ]);

        if ($updated) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => $apiKey ? 'API Key mandiri berhasil disimpan!' : 'API Key mandiri dihapus, kembali menggunakan pengaturan global.'
            ]);
        }

        return $this->response->setJSON(['status' => 'error', 'message' => 'Gagal memperbarui API Key.']);
    }

    /**
     * POST: Update JP per minggu (AJAX)
     */
    public function updateJpPerWeek()
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir, silakan login kembali.']);
        }

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Data guru tidak ditemukan.']);
        }

        $id = intval($this->request->getPost('device_id'));
        $jpPerWeek = intval($this->request->getPost('jp_per_week'));

        if ($jpPerWeek <= 0) {
            $jpPerWeek = 4;
        }

        $deviceModel = new \App\Models\LearningDeviceModel();
        $device = $deviceModel->where('id', $id)->where('user_id', $teacher['user_id'])->first();
        if (!$device) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Perangkat pembelajaran tidak ditemukan.']);
        }

        $updated = $deviceModel->update($id, ['jp_per_week' => $jpPerWeek]);

        if ($updated) {
            return $this->response->setJSON([
                'status' => 'success',
                'message' => 'Beban belajar JP per minggu berhasil diperbarui!',
                'jp_per_week' => $jpPerWeek
            ]);
        }

        return $this->response->setJSON(['status' => 'error', 'message' => 'Gagal memperbarui beban JP.']);
    }
}
