<?php
namespace Controllers\Admin;

use Core\Controller;

class CompetencyController extends Controller {

    public function index(): void {
        $this->requireRole('super-admin', 'admin');
        $sid    = $this->schoolId();
        $termId = (int)$this->request->get('term_id', 0);
        if (!$termId) {
            $cur = $this->db->fetch(
                "SELECT t.id FROM terms t JOIN academic_years ay ON ay.id=t.academic_year_id
                 WHERE ay.school_id=? AND t.is_current=1 LIMIT 1", [$sid]
            );
            $termId = $cur['id'] ?? 0;
        }
        $terms        = $this->db->fetchAll(
            "SELECT t.*, ay.name as year_name FROM terms t
             JOIN academic_years ay ON ay.id=t.academic_year_id
             WHERE ay.school_id=? ORDER BY t.id DESC", [$sid]
        );
        $competencies = $this->db->fetchAll("SELECT * FROM competencies ORDER BY name");
        $streams      = $this->db->fetchAll(
            "SELECT st.*, cl.name as class_name, 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]
        );
        $streamId = (int)$this->request->get('stream_id', 0);
        $students = [];
        $ratings  = [];
        if ($streamId && $termId) {
            $students = $this->db->fetchAll(
                "SELECT s.*, u.name FROM students s JOIN users u ON u.id=s.user_id
                 WHERE s.stream_id=? AND s.status='active' ORDER BY u.name", [$streamId]
            );
            $rows = $this->db->fetchAll(
                "SELECT cr.* FROM competency_ratings cr
                 JOIN students s ON s.id=cr.student_id
                 WHERE s.stream_id=? AND cr.term_id=?", [$streamId, $termId]
            );
            foreach ($rows as $r) $ratings[$r['student_id']][$r['competency_id']] = $r['rating'];
        }
        $this->view('admin/competency/index', compact('terms','termId','competencies','streams','streamId','students','ratings'));
    }

    public function save(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $termId   = (int)$this->request->post('term_id', 0);
        $streamId = (int)$this->request->post('stream_id', 0);
        $data     = $this->request->post('ratings', []);
        $userId   = $this->currentUser()['id'];
        $saved    = 0;
        foreach ($data as $studentId => $comps) {
            foreach ($comps as $compId => $rating) {
                if (!in_array($rating, ['EE','ME','AE','BE'])) continue;
                $existing = $this->db->fetch(
                    "SELECT id FROM competency_ratings WHERE student_id=? AND competency_id=? AND term_id=?",
                    [(int)$studentId, (int)$compId, $termId]
                );
                if ($existing) {
                    $this->db->update('competency_ratings',
                        ['rating'=>$rating,'rated_by'=>$userId,'updated_at'=>date('Y-m-d H:i:s')],
                        'id=?', [$existing['id']]
                    );
                } else {
                    $this->db->insert('competency_ratings', [
                        'student_id'    => (int)$studentId,
                        'competency_id' => (int)$compId,
                        'term_id'       => $termId,
                        'rating'        => $rating,
                        'rated_by'      => $userId,
                        'created_at'    => date('Y-m-d H:i:s'),
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ]);
                }
                $saved++;
            }
        }
        $this->withSuccess("$saved competency ratings saved.");
        $this->redirect("admin/competency?stream_id=$streamId&term_id=$termId");
    }
}
