<?php

namespace App\Models;

use CodeIgniter\Model;

class CertificateRecordModel extends Model
{
    protected $table         = 'certificate_records';
    protected $primaryKey    = 'id';
    protected $useTimestamps = true;

    protected $allowedFields = [
        'certificate_number',
        'verification_token',
        'student_id',
        'student_name',
        'grade',
        'cert_date',
        'school_year',
        'class_section_id',
        'issued_by',
        'issued_at',
    ];

    /**
     * Generates the next certificate number for a given school year.
     * Format: ARSS-{school_year}-{4-digit sequence}  e.g. ARSS-2025-2026-0003
     * Uses a transaction + row count to guarantee uniqueness within a request.
     * Academic Records and Student Services (ARSS)
     */
    public function nextNumber(string $schoolYear): string
    {
        $db = \Config\Database::connect();
        $db->transStart();

        $count = $db->table($this->table)
            ->where('school_year', $schoolYear)
            ->countAllResults();

        $seq = str_pad($count + 1, 4, '0', STR_PAD_LEFT);

        $db->transComplete();

        return 'ARSS-' . $schoolYear . '-' . $seq;
    }

    public function generateVerificationToken(): string
    {
        $db = \Config\Database::connect();

        do {
            $token = bin2hex(random_bytes(16));
            $exists = $db->table($this->table)
                ->select('id')
                ->where('verification_token', $token)
                ->limit(1)
                ->get()
                ->getRowArray();
        } while ($exists);

        return $token;
    }

    /** Returns paginated records with the issuing admin's name joined. */
    public function getAuditLog(?string $schoolYear = null, int $perPage = 50): array
    {
        $builder = $this->db->table($this->table . ' cr')
            ->select('cr.*, u.firstname AS admin_firstname, u.lastname AS admin_lastname')
            ->join('users u', 'u.id = cr.issued_by', 'left')
            ->orderBy('cr.issued_at', 'DESC');

        if ($schoolYear) {
            $builder->where('cr.school_year', $schoolYear);
        }

        return $builder->get()->getResultArray();
    }

    /** Total certificates issued per school year, ordered by year DESC. */
    public function yearSummary(): array
    {
        return $this->db->table($this->table)
            ->select('school_year, COUNT(*) AS total')
            ->groupBy('school_year')
            ->orderBy('school_year', 'DESC')
            ->get()->getResultArray();
    }
}
