<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentClassModel extends Model
{
    protected $table      = 'student_class';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'student_id',
        'school_id',
        'class_section_id',
        'school_year',
        'is_event_only',
        'description',
        'updated_by',
        'updated_at',
        'created_at'
    ];

    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    /**
     * Scope: only students active for classes/attendance.
     */
    public function active(): self
    {
        return $this->select('student_class.*')
            ->join('students', 'students.id = student_class.student_id', 'inner')
            ->where('students.is_active', 1);
    }

    public function getClassSectionNameByStudentId(int $studentId): ?string
    {
        return $this->db->table($this->table)
            ->select('cs.class_section_name')
            ->join('classSection cs', 'cs.class_section_id = student_class.class_section_id')
            ->where('student_class.student_id', $studentId)
            ->get()
            ->getRow('class_section_name');
    }


    // Custom findAll() method
    public function findAll($limit = 0, $offset = 0)
    {
        // Optional: Add custom logic before fetching all records

        // Then call the parent findAll method to fetch the records
        return parent::findAll($limit, $offset);
    }

    // Method to get all students in a specific class section (optionally scoped to term)
    public function getClassStudents($classSectionId, ?string $schoolYear = null)
    {
        $qb = $this->active()->where('student_class.class_section_id', $classSectionId);
        if ($schoolYear !== null && $schoolYear !== '') {
            $qb->where('student_class.school_year', $schoolYear);
        }
        return $qb->findAll();
    }

    /**
     * Return class section names for a student in a given school year.
     *
     * @param int|string $studentId
     * @param string $schoolYear
     * @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
     * @return array|string
     */
    public function getClassSectionsByStudentId($studentId, string $schoolYear, bool $asArray = false)
    {
        $rows = $this->db->table('student_class')
            ->select('cs.class_section_name')
            ->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
            ->where('student_class.student_id', $studentId)
            ->where('student_class.class_section_id IS NOT NULL', null, false)
            ->where('student_class.school_year', $schoolYear)
            ->orderBy('cs.class_section_name', 'ASC')
            ->get()
            ->getResultArray();

        $names = array_values(array_unique(array_filter(array_map(static function ($row) {
            return $row['class_section_name'] ?? null;
        }, $rows))));

        if ($asArray) {
            return $names;
        }

        return !empty($names) ? implode(', ', $names) : '';
    }

    /**
     * Return class section names for a student in a given school year, with optional event flag.
     *
     * @param int|string $studentId
     * @param string $schoolYear
     * @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
     * @return array|string
     */
    public function getClassSectionsByStudentIdWithFlags($studentId, string $schoolYear, bool $asArray = false)
    {
        $rows = $this->db->table('student_class')
            ->select('cs.class_section_name, student_class.is_event_only')
            ->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
            ->where('student_class.student_id', $studentId)
            ->where('student_class.class_section_id IS NOT NULL', null, false)
            ->where('student_class.school_year', $schoolYear)
            ->orderBy('cs.class_section_name', 'ASC')
            ->get()
            ->getResultArray();

        $names = array_values(array_unique(array_filter(array_map(static function ($row) {
            $name = $row['class_section_name'] ?? null;
            if (!$name) return null;
            $isEvent = (int)($row['is_event_only'] ?? 0) === 1;
            return $isEvent ? ($name . ' (Event)') : $name;
        }, $rows))));

        if ($asArray) {
            return $names;
        }

        return !empty($names) ? implode(', ', $names) : '';
    }

    /**
     * Return class_section_id values for a student/year.
     *
     * @param int|string $studentId
     * @param string $schoolYear
     * @return int[]
     */
    public function getClassSectionIdsByStudentId($studentId, string $schoolYear): array
    {
        $rows = $this->db->table('student_class')
            ->select('class_section_id')
            ->where('student_id', $studentId)
            ->where('class_section_id IS NOT NULL', null, false)
            ->where('school_year', $schoolYear)
            ->get()
            ->getResultArray();

        $ids = array_map(static fn($r) => (int)($r['class_section_id'] ?? 0), $rows);
        return array_values(array_filter(array_unique($ids), static fn($v) => $v > 0));
    }


    public function getStudentsByClassSectionIds(array $classSectionIds)
    {
        return $this->select('students.id as student_id, students.firstname, students.lastname, students.school_id, students.is_new,students.photo_consent ,students.age, student_class.school_year, student_class.class_section_id')
            ->join('students', 'students.id = student_class.student_id')
            ->whereIn('student_class.class_section_id', $classSectionIds)
            ->where('students.is_active', 1)
            ->get()
            ->getResultArray();
    }

    /**
     * Get the class ID (grade) for a specific student.
     *
     * @param int $studentId
     * @return string class_id or 'N/A'
     */
    public function getStudentGrade(int $studentId): string
    {
        $studentClass = $this->where('student_id', $studentId)
            ->where('is_event_only', 0)
            ->orderBy('created_at', 'DESC') // in case of multiple entries, get latest
            ->first();

        if ($studentClass && isset($studentClass['class_section_id'])) {
            $classSection = $this->db->table('classSection')
                ->where('class_section_id', $studentClass['class_section_id'])
                ->get()
                ->getRowArray();

            return $classSection['class_id'] ?? 'N/A';
        }

        log_message('error', "Student class or section not found for student ID: $studentId");
        return 'N/A';
    }

    /**
     * Return true if the student has at least one non-event class assignment for the year.
     */
    public function hasNonEventAssignment(int $studentId, string $schoolYear): bool
    {
        return (bool) $this->where('student_id', $studentId)
            ->where('school_year', $schoolYear)
            ->where('is_event_only', 0)
            ->first();
    }

    /**
     * Return student counts per class_section_id, optionally scoped to a school year.
     *
     * @param string|null $schoolYear
     * @return array<int|string,int> Map of class_section_id => count
     */
    public function getStudentCountsBySection(?string $schoolYear = null): array
    {
        $qb = $this->db->table($this->table)
            ->select('class_section_id, COUNT(*) AS total')
            ->join('students', 'students.id = student_class.student_id', 'inner')
            ->where('students.is_active', 1)
            ->where('student_class.class_section_id IS NOT NULL', null, false)
            ->groupBy('student_class.class_section_id');

        if ($schoolYear !== null && $schoolYear !== '') {
            $qb->where('student_class.school_year', $schoolYear);
        }

        $rows = $qb->get()->getResultArray();
        $out = [];
        foreach ($rows as $r) {
            $cid = $r['class_section_id'] ?? null;
            if ($cid === null || $cid === '') continue;
            $out[$cid] = (int)($r['total'] ?? 0);
        }
        return $out;
    }
}
