<?php

namespace App\Models;

use CodeIgniter\Model;

class AcademicPeriodModel extends Model
{
    protected $table            = 'academic_periods';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'academic_year_id', 'semester', 'is_active', 'start_date', 'end_date'
    ];

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

    public function getActive()
    {
        return $this->select('academic_periods.*, academic_years.name as year_name')
                    ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
                    ->where('academic_periods.is_active', 1)
                    ->where('academic_periods.deleted_at', null)
                    ->first();
    }

    public function getByYear($academic_year_id)
    {
        return $this->select('academic_periods.*, academic_years.name as year_name')
                    ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
                    ->where('academic_periods.academic_year_id', $academic_year_id)
                    ->where('academic_periods.deleted_at', null)
                    ->orderBy('academic_periods.semester', 'ASC')
                    ->findAll();
    }

    public function getAllWithYear()
    {
        return $this->select('academic_periods.*, academic_years.name as year_name')
                    ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
                    ->where('academic_periods.deleted_at', null)
                    ->orderBy('academic_years.name', 'DESC')
                    ->orderBy('academic_periods.semester', 'ASC')
                    ->findAll();
    }

    public function setActive($id)
    {
        // Nonaktifkan semua dulu
        $this->db->table('academic_periods')
                 ->where('deleted_at', null)
                 ->update(['is_active' => 0]);

        // Aktifkan yang dipilih
        return $this->db->table('academic_periods')
                        ->where('id', $id)
                        ->update(['is_active' => 1]);
    }
}