<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

class ClassSection extends BaseModel
{
    use HasFactory;
    // CI table name is "classSection"
    protected $table = 'classSection';

    // ✅ CI: useTimestamps = true
    public $timestamps = true;

    protected $fillable = [
        'class_id',
        'class_section_id',
        'class_section_name',
        'created_at',
        'updated_at',
        'semester',
        'school_year',
    ];

    protected $casts = [
        'class_id'         => 'integer',
        'class_section_id' => 'integer',
    ];

    public function getSectionNameAttribute(): ?string
    {
        return $this->attributes['class_section_name'] ?? null;
    }

    public function setSectionNameAttribute($value): void
    {
        $this->attributes['class_section_name'] = $value;
    }

    /* =========================
     * Relationships (optional)
     * ========================= */
    public function schoolClass()
    {
        // If you used SchoolClass for classes model name
        return $this->belongsTo(SchoolClass::class, 'class_id');
    }

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Get class sections with class name (like CI join result).
     * Returns array of rows: class_section_id, class_section_name, class_name
     */
    public static function getClassSections(): array
    {
        return DB::table('classSection')
            ->leftJoin('classes', 'classSection.class_id', '=', 'classes.id')
            ->select('classSection.class_section_id', 'classSection.class_section_name', 'classes.class_name')
            ->orderBy('classSection.class_section_name', 'ASC')
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();
    }

    /**
     * Get the parent class_id for a given class_section_id.
     */
    public static function getClassId($classSectionId): ?int
    {
        if ($classSectionId === null || $classSectionId === '') {
            return null;
        }

        $row = static::query()
            ->select('class_id')
            ->where('class_section_id', $classSectionId)
            ->orderByDesc('id') // in case of duplicates, take latest
            ->first();

        return $row ? (int) $row->class_id : null;
    }

    /**
     * Get the class_section_name for a given section_id.
     */
    public static function getClassSectionNameBySectionId($sectionId): ?string
    {
        $row = static::query()
            ->select('class_section_name')
            ->where('class_section_id', $sectionId)
            ->first();

        return $row?->class_section_name;
    }

    public static function getClassSectionNameByClassId($classId): ?string
    {
        $row = static::query()
            ->select('class_section_name')
            ->where('class_id', $classId)
            ->first();

        return $row?->class_section_name;
    }

    /**
     * Get section ID from class section name.
     */
    public static function getSectionIDFromClassSectionName(string $classSectionName): ?int
    {
        $row = static::query()
            ->select('class_section_id')
            ->where('class_section_name', $classSectionName)
            ->first();

        return $row ? (int) $row->class_section_id : null;
    }

    /**
     * Return the base (non-letter) section row for a given class_id. E.g., '3' vs '3-A'.
     */
    public static function getBaseSectionByClassId(int $classId): ?array
    {
        $row = static::query()
            ->where('class_id', $classId)
            ->whereRaw("class_section_name NOT LIKE '%-%'")
            ->orderBy('id', 'ASC')
            ->first();

        return $row ? $row->toArray() : null;
    }

    /**
     * Return lettered sections for a class (e.g., '3-A','3-B',...). Ordered by name asc.
     */
    public static function getLetterSectionsByClassId(int $classId): array
    {
        return static::query()
            ->where('class_id', $classId)
            ->where('class_section_name', 'like', '%-%')
            ->orderBy('class_section_name', 'ASC')
            ->get()
            ->toArray();
    }
}
