<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ClassroomModel;
use App\Models\GradeModel;
use App\Models\MajorModel;
use App\Models\AcademicYearModel;

class Classroom extends BaseController
{
    protected $model;
    protected $gradeModel;
    protected $majorModel;
    protected $yearModel;

    public function __construct()
    {
        $this->model     = new ClassroomModel();
        $this->gradeModel = new GradeModel();
        $this->majorModel = new MajorModel();
        $this->yearModel  = new AcademicYearModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $activeYear = $this->yearModel->getActive();
        $allYears   = $this->yearModel->where('deleted_at', null)->orderBy('name', 'DESC')->findAll();

        // Filter: bisa pilih TA tertentu, default ke TA aktif
        $filterYearId = $this->request->getGet('year_id') ?: ($activeYear['id'] ?? null);

        // Nama TA yang sedang dilihat
        $viewingYear = null;
        foreach ($allYears as $yr) {
            if ((int)$yr['id'] === (int)$filterYearId) {
                $viewingYear = $yr;
                break;
            }
        }

        $data = [
            'title'           => 'Master Kelas',
            'classrooms'      => $this->model->getAllWithRelations($filterYearId),
            'grades'          => $this->gradeModel->orderBy('order', 'ASC')->findAll(),
            'majors'          => $this->majorModel->orderBy('name', 'ASC')->findAll(),
            'allYears'        => $allYears,
            'activeYear'      => $activeYear,
            'filterYearId'    => $filterYearId,
            'viewingYearName' => $viewingYear['name'] ?? '',
        ];

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

    public function store()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'name'     => 'required|max_length[50]',
            'grade_id' => 'required|integer',
            'capacity' => 'required|integer|greater_than[0]',
        ];

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

        // Gunakan year_id dari form (TA yang sedang dilihat), fallback ke TA aktif
        $yearId = $this->request->getPost('year_id');
        if ($yearId) {
            $targetYear = $this->yearModel->find($yearId);
        } else {
            $targetYear = $this->yearModel->getActive();
        }

        if (!$targetYear) {
            return redirect()->back()->with('error', 'Tahun ajaran tidak ditemukan!');
        }

        $this->model->insert([
            'name'             => $this->request->getPost('name'),
            'grade_id'         => $this->request->getPost('grade_id'),
            'major_id'         => $this->request->getPost('major_id') ?: null,
            'capacity'         => $this->request->getPost('capacity'),
            'academic_year_id' => $targetYear['id'],
        ]);

        $classroomId = $this->model->getInsertID();
        $this->saveWaGroupId($classroomId);

        return redirect()->to('/classroom?year_id=' . $targetYear['id'])
            ->with('success', 'Kelas berhasil ditambahkan untuk TA ' . $targetYear['name'] . '!');
    }

    public function update($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'name'     => 'required|max_length[50]',
            'grade_id' => 'required|integer',
            'capacity' => 'required|integer|greater_than[0]',
        ];

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

        $this->model->update($id, [
            'name'     => $this->request->getPost('name'),
            'grade_id' => $this->request->getPost('grade_id'),
            'major_id' => $this->request->getPost('major_id') ?: null,
            'capacity' => $this->request->getPost('capacity'),
        ]);

        $this->saveWaGroupId($id);

        return redirect()->to('/classroom')
            ->with('success', 'Kelas berhasil diupdate!');
    }

    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $db = \Config\Database::connect();
        
        // Cari periode akademik aktif
        $activePeriod = $db->table('academic_periods')
            ->select('id')
            ->where('is_active', 1)
            ->get()
            ->getRowArray();

        if ($activePeriod) {
            $studentCount = $db->table('student_academic_histories')
                ->where('classroom_id', $id)
                ->where('academic_period_id', $activePeriod['id'])
                ->countAllResults();

            if ($studentCount > 0) {
                return redirect()->to('/classroom')
                    ->with('error', "Tidak dapat menghapus kelas ini karena masih ada {$studentCount} siswa terdaftar di kelas ini pada periode akademik aktif!");
            }
        }

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

        return redirect()->to('/classroom')
            ->with('success', 'Kelas berhasil dihapus!');
    }

    /**
     * Copy semua kelas dari tahun ajaran tertentu ke tahun ajaran aktif.
     */
    public function copyFromYear()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $fromYearId = $this->request->getPost('from_year_id');
        $toYearId   = $this->request->getPost('to_year_id'); // TA tujuan dari view

        if (!$fromYearId) {
            return redirect()->back()->with('error', 'Pilih tahun ajaran sumber terlebih dahulu!');
        }

        // Jika to_year_id tidak dikirim, fallback ke TA aktif
        if ($toYearId) {
            $toYear = $this->yearModel->find($toYearId);
        } else {
            $toYear = $this->yearModel->getActive();
        }

        if (!$toYear) {
            return redirect()->back()->with('error', 'Tahun ajaran tujuan tidak ditemukan!');
        }

        if ((int)$fromYearId === (int)$toYear['id']) {
            return redirect()->to('/classroom?year_id=' . $toYear['id'])
                ->with('error', 'Tahun ajaran sumber tidak boleh sama dengan tahun ajaran tujuan!');
        }

        $fromYear = $this->yearModel->find($fromYearId);
        if (!$fromYear) {
            return redirect()->back()->with('error', 'Tahun ajaran sumber tidak ditemukan!');
        }

        $copied = $this->model->copyFromYear((int)$fromYearId, (int)$toYear['id']);

        if ($copied === 0) {
            return redirect()->to('/classroom?year_id=' . $toYear['id'])
                ->with('error', 'Tidak ada kelas yang bisa dicopy (mungkin sudah ada semua, atau TA sumber tidak punya kelas).');
        }

        return redirect()->to('/classroom?year_id=' . $toYear['id'])
            ->with('success', "Berhasil copy {$copied} kelas dari TA {$fromYear['name']} ke TA {$toYear['name']}!");
    }

    private function saveWaGroupId($classroomId)
    {
        $waGroupId = trim($this->request->getPost('wa_group_id') ?? '');
        $db = \Config\Database::connect();
        $key = 'wa_group_id_classroom_' . $classroomId;

        $exists = $db->table('settings')->where('setting_key', $key)->countAllResults();
        if ($exists) {
            $db->table('settings')->where('setting_key', $key)->update(['setting_value' => $waGroupId]);
        } else {
            $db->table('settings')->insert([
                'setting_key'   => $key,
                'setting_value' => $waGroupId,
                'setting_group' => 'whatsapp',
            ]);
        }
    }

    public function getWaGroup($classroomId)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $db = \Config\Database::connect();
        $row = $db->table('settings')
            ->where('setting_key', 'wa_group_id_classroom_' . $classroomId)
            ->get()->getRowArray();

        return $this->response->setJSON([
            'wa_group_id' => $row['setting_value'] ?? '',
        ]);
    }
}