<?php
namespace Controllers\Admin;

use Core\Controller;
use Models\AcademicYear;
use Models\Term;
use Models\Stream;
use Models\Department;

class AcademicController extends Controller {

    public function index(): void {
        $this->requireRole('super-admin', 'admin');
        $sid   = $this->schoolId();
        $years = (new AcademicYear())->getBySchool($sid);
        $terms = (new Term())->getBySchool($sid);
        $depts = (new Department())->getBySchool($sid);

        // Grades grouped by CBC band
        $allGrades  = $this->db->fetchAll("SELECT * FROM classes WHERE school_id=? ORDER BY level", [$sid]);
        $gradeBands = [
            'pre-primary'      => ['label'=>'Pre-Primary (PP1–PP2)',        'color'=>'#8b5cf6', 'grades'=>[]],
            'lower-primary'    => ['label'=>'Lower Primary (Grade 1–3)',     'color'=>'#3b82f6', 'grades'=>[]],
            'upper-primary'    => ['label'=>'Upper Primary (Grade 4–6)',     'color'=>'#10b981', 'grades'=>[]],
            'junior-secondary' => ['label'=>'Junior Secondary (Grade 7–9)', 'color'=>'#f59e0b', 'grades'=>[]],
            'senior-secondary' => ['label'=>'Senior Secondary (Grade 10–12)','color'=>'#ef4444','grades'=>[]],
        ];
        foreach ($allGrades as $g) {
            $band = $g['grade_band'] ?? 'lower-primary';
            if (isset($gradeBands[$band])) $gradeBands[$band]['grades'][] = $g;
        }

        // Streams
        $streams = $this->db->fetchAll(
            "SELECT st.*, cl.name as class_name,
                    IFNULL(cl.grade_band,'lower-primary') as grade_band,
                    CONCAT(cl.name,' - ',st.name) as full_name
             FROM streams st JOIN classes cl ON cl.id=st.class_id
             WHERE cl.school_id=? ORDER BY cl.level, st.name", [$sid]
        );

        // Subjects grouped by grade_band
        $allSubjects    = $this->db->fetchAll("SELECT * FROM subjects WHERE school_id=? ORDER BY grade_band, name", [$sid]);
        $subjectsByBand = [];
        foreach ($allSubjects as $s) $subjectsByBand[$s['grade_band'] ?? 'lower-primary'][] = $s;

        $this->view('admin/academic/index', compact('years','terms','depts','gradeBands','subjectsByBand','allGrades','streams'));
    }

    public function storeYear(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $id   = $this->db->insert('academic_years', [
            'school_id'  => $this->schoolId(),
            'name'       => htmlspecialchars($data['name'], ENT_QUOTES),
            'start_date' => $data['start_date'] ?: null,
            'end_date'   => $data['end_date'] ?: null,
            'is_current' => isset($data['is_current']) ? 1 : 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        if (isset($data['is_current']))
            $this->db->query("UPDATE academic_years SET is_current=0 WHERE school_id=? AND id!=?", [$this->schoolId(), $id]);
        $this->withSuccess('Academic year added.');
        $this->redirect('admin/academic');
    }

    public function storeTerm(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $id   = $this->db->insert('terms', [
            'academic_year_id' => (int)$data['academic_year_id'],
            'name'       => htmlspecialchars($data['name'], ENT_QUOTES),
            'start_date' => $data['start_date'] ?: null,
            'end_date'   => $data['end_date'] ?: null,
            'is_current' => isset($data['is_current']) ? 1 : 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        if (isset($data['is_current']))
            $this->db->query("UPDATE terms t JOIN academic_years ay ON ay.id=t.academic_year_id SET t.is_current=0 WHERE ay.school_id=? AND t.id!=?", [$this->schoolId(), $id]);
        $this->withSuccess('Term added.');
        $this->redirect('admin/academic');
    }

    public function storeGrade(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->insert('classes', [
            'school_id'  => $this->schoolId(),
            'name'       => htmlspecialchars($data['name'], ENT_QUOTES),
            'level'      => (int)$data['level'],
            'grade_band' => $data['grade_band'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $this->withSuccess('Grade added.');
        $this->redirect('admin/academic');
    }

    public function updateGrade(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->query(
            "UPDATE classes SET name=?, grade_band=?, level=?, updated_at=? WHERE id=? AND school_id=?",
            [htmlspecialchars($data['name'], ENT_QUOTES), $data['grade_band'], (int)$data['level'], date('Y-m-d H:i:s'), (int)$id, $this->schoolId()]
        );
        $this->withSuccess('Grade updated.');
        $this->redirect('admin/academic');
    }

    public function deleteGrade(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $this->db->query("DELETE FROM classes WHERE id=? AND school_id=?", [(int)$id, $this->schoolId()]);
        $this->withSuccess('Grade deleted.');
        $this->redirect('admin/academic');
    }

    public function storeStream(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->insert('streams', [
            'class_id'   => (int)$data['class_id'],
            'name'       => htmlspecialchars($data['name'], ENT_QUOTES),
            'capacity'   => (int)($data['capacity'] ?? 45),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        $this->withSuccess('Stream added.');
        $this->redirect('admin/academic');
    }

    public function updateStream(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->query(
            "UPDATE streams SET class_id=?, name=?, capacity=?, updated_at=? WHERE id=?",
            [(int)$data['class_id'], htmlspecialchars($data['name'], ENT_QUOTES), (int)($data['capacity'] ?? 45), date('Y-m-d H:i:s'), (int)$id]
        );
        $this->withSuccess('Stream updated.');
        $this->redirect('admin/academic');
    }

    public function deleteStream(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $this->db->query("DELETE FROM streams WHERE id=?", [(int)$id]);
        $this->withSuccess('Stream deleted.');
        $this->redirect('admin/academic');
    }

    public function storeSubject(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->insert('subjects', [
            'school_id'     => $this->schoolId(),
            'department_id' => $data['department_id'] ?: null,
            'name'          => htmlspecialchars($data['name'], ENT_QUOTES),
            'code'          => strtoupper(htmlspecialchars($data['code'] ?? '', ENT_QUOTES)),
            'grade_band'    => $data['grade_band'],
            'is_compulsory' => isset($data['is_compulsory']) ? 1 : 0,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ]);
        $this->withSuccess('Learning area added.');
        $this->redirect('admin/academic');
    }

    public function updateSubject(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $data = $this->request->all();
        $this->db->query(
            "UPDATE subjects SET name=?, code=?, grade_band=?, is_compulsory=?, updated_at=? WHERE id=? AND school_id=?",
            [htmlspecialchars($data['name'], ENT_QUOTES), strtoupper(htmlspecialchars($data['code'] ?? '', ENT_QUOTES)), $data['grade_band'], isset($data['is_compulsory']) ? 1 : 0, date('Y-m-d H:i:s'), (int)$id, $this->schoolId()]
        );
        $this->withSuccess('Subject updated.');
        $this->redirect('admin/academic');
    }

    public function deleteSubject(string $id): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $this->db->query("DELETE FROM subjects WHERE id=? AND school_id=?", [(int)$id, $this->schoolId()]);
        $this->withSuccess('Subject deleted.');
        $this->redirect('admin/academic');
    }
}
