<?php

namespace App\Models;

use CodeIgniter\Model;

class EducationModel extends Model
{
    protected $table            = 'educations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'institution', 'major', 'degree', 'start_year', 'end_year',
        'gpa', 'description', 'status'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules = [
        'institution' => 'required|min_length[3]|max_length[200]',
        'major'       => 'required|min_length[2]|max_length[150]',
        'degree'      => 'required|max_length[50]',
        'start_year'  => 'required|numeric|exact_length[4]',
        'end_year'    => 'permit_empty|numeric|exact_length[4]',
        'gpa'         => 'permit_empty|decimal',
        'status'      => 'required|in_list[ongoing,completed]',
    ];

    protected $skipValidation = false;

    /**
     * Get educations with search, filter, and pagination (public)
     */
    public function getPublicEducations(?string $search = null, ?string $degree = null, int $perPage = 6)
    {
        $builder = $this;

        if (!empty($search)) {
            $builder->groupStart()
                    ->like('institution', $search)
                    ->orLike('major', $search)
                    ->orLike('description', $search)
                    ->groupEnd();
        }

        if (!empty($degree)) {
            $builder->where('degree', $degree);
        }

        return $builder->orderBy('start_year', 'DESC')
                       ->orderBy('status', 'ASC')
                       ->paginate($perPage);
    }

    /**
     * Get educations for admin with search, filter, and pagination
     */
    public function getAdminEducations(?string $search = null, ?string $status = null, string $sort = 'latest', int $perPage = 10)
    {
        $builder = $this;

        if (!empty($search)) {
            $builder->groupStart()
                    ->like('institution', $search)
                    ->orLike('major', $search)
                    ->groupEnd();
        }

        if (!empty($status)) {
            $builder->where('status', $status);
        }

        // Sorting
        switch ($sort) {
            case 'title_asc':
                $builder->orderBy('institution', 'ASC');
                break;
            case 'oldest':
                $builder->orderBy('start_year', 'ASC');
                break;
            default: // latest
                $builder->orderBy('start_year', 'DESC');
        }

        return $builder->paginate($perPage);
    }

    /**
     * Get distinct degrees
     */
    public function getDegrees(): array
    {
        return $this->distinct()
                    ->select('degree')
                    ->findAll();
    }

    /**
     * Count by status
     */
    public function countByStatus(string $status): int
    {
        return $this->where('status', $status)->countAllResults();
    }

    /**
     * Get ongoing educations
     */
    public function getOngoing(): array
    {
        return $this->where('status', 'ongoing')
                    ->orderBy('start_year', 'DESC')
                    ->findAll();
    }
}
