<?php

namespace App\Controllers\Guru;

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

class RpeController extends BaseController
{
    use DeviceHelperTrait;

    protected $deviceModel;
    protected $pekanEfektifModel;

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

    /**
     * Halaman RPE (Rincian Pekan Efektif)
     */
    public function rpe($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.');
        }

        $sync = $this->request->getGet('sync');
        $rpeRecord = $this->pekanEfektifModel->where('learning_device_id', $id)->first();

        if ($sync === 'kaldik' || !$rpeRecord) {
            $rpeData = $this->calculateRpeFromKaldik($id);
            if ($sync === 'kaldik') {
                session()->setFlashdata('success', 'Rincian Pekan Efektif berhasil disinkronkan dengan Kalender Akademik admin. Silakan periksa kembali dan klik Simpan.');
            }
        } else {
            $rpeData = json_decode($rpeRecord['content_json'], true);
        }

        $db = Database::connect();
        $liburEvents = $db->table('calendar_events ce')
            ->select('ce.title, ce.start_date, ce.end_date, cc.name as category_name')
            ->join('calendar_categories cc', 'cc.id = ce.category_id')
            ->where('ce.academic_year_id', $device['academic_year_id'])
            ->where('cc.is_libur', 1)
            ->where('ce.deleted_at', null)
            ->orderBy('ce.start_date', 'ASC')
            ->get()->getResultArray();

        $data = [
            'title'       => 'Rincian Pekan Efektif (RPE)',
            'device'      => $device,
            'rpeData'     => $rpeData,
            'liburEvents' => $liburEvents
        ];

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

    /**
     * POST: Simpan Pekan Efektif
     */
    public function saveRpeAction($id)
    {
        if ($redirect = $this->checkLogin()) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Sesi berakhir.']);
        }

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

        $existing = $this->pekanEfektifModel->where('learning_device_id', $id)->first();
        $saveData = [
            'learning_device_id' => $id,
            'content_json'       => json_encode($payload)
        ];

        if ($existing) {
            $this->pekanEfektifModel->update($existing['id'], $saveData);
        } else {
            $this->pekanEfektifModel->insert($saveData);
        }

        return $this->response->setJSON(['status' => 'success', 'message' => 'Rincian Pekan Efektif berhasil disimpan.']);
    }
}
