<?php namespace App\Models;

use CodeIgniter\Model;

class WhatsappGroupLinkModel extends Model
{
    protected $table         = 'whatsapp_group_links';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $allowedFields = [
        'class_section_id',
        'class_section_name',
        'school_year',
        'invite_link',
        'active',
    ];
    protected $useTimestamps = true; // requires created_at / updated_at columns

    private ?bool $hasSchoolYearColumn = null;

    private function hasSchoolYearColumn(): bool
    {
        if ($this->hasSchoolYearColumn === null) {
            $this->hasSchoolYearColumn = $this->db->fieldExists('school_year', $this->table);
        }

        return $this->hasSchoolYearColumn;
    }

    /**
     * Get the link for a specific section in a specific term.
     *
     * @param int    $sectionId          Class/section code (not PK).
     * @param string $year               School year, e.g. "2025-2026".
     * @param string $sem                Deprecated/ignored; links are scoped by school year.
     * @param bool   $onlyActive         If true, require active=1.
     * @param bool   $allowNullSemester  Deprecated/ignored.
     */
    public function getLinkForSection(
        int $sectionId,
        string $year,
        string $sem,
        bool $onlyActive = true,
        bool $allowNullSemester = false
    ): ?array {
        $year = trim($year);
        $sem  = trim($sem);

        $b = $this->asArray()
            ->where('class_section_id', $sectionId);

        if ($this->hasSchoolYearColumn()) {
            $b = $b->where('school_year', $year);
        }

        if ($onlyActive) {
            $b = $b->where('active', 1);
        }

        // If you also want to ignore blank links:
        $b = $b->where('invite_link IS NOT NULL', null, false)
               ->where('invite_link !=', '');

        return $b->orderBy('updated_at', 'DESC')
                 ->orderBy('id', 'DESC')
                 ->first() ?: null;
    }

    /**
     * Get all links for a term.
     *
     * @param string   $year
     * @param string   $sem
     * @param bool|null $onlyActive  true: active only, false: inactive only, null: both
     * @param bool     $allowNullSemester  Deprecated/ignored.
     */
    public function getAllForTerm(
        string $year,
        string $sem,
        ?bool $onlyActive = null,
        bool $allowNullSemester = false
    ): array {
        $year = trim($year);
        $sem  = trim($sem);

        $b = $this->asArray();

        if ($this->hasSchoolYearColumn()) {
            $b = $b->where('school_year', $year);
        }

        if ($onlyActive === true) {
            $b = $b->where('active', 1);
        } elseif ($onlyActive === false) {
            $b = $b->where('active', 0);
        }

        return $b->orderBy('updated_at', 'DESC')
                 ->orderBy('id', 'DESC')
                 ->findAll();
    }

    /**
     * Convenience: upsert a link row for a section/term.
     * Returns the row (array) after save.
     */
    public function upsertLinkForSection(
        int $sectionId,
        string $sectionName,
        string $year,
        string $sem,
        string $inviteLink,
        bool $active = true
    ): array {
        $payload = [
            'class_section_id'   => $sectionId,
            'class_section_name' => $sectionName,
            'invite_link'        => trim($inviteLink),
            'active'             => $active ? 1 : 0,
        ];

        if ($this->hasSchoolYearColumn()) {
            $payload['school_year'] = trim($year);
        }

        // Try to find existing row (exact term)
        $existing = $this->asArray()
            ->where('class_section_id', $sectionId);

        if ($this->hasSchoolYearColumn()) {
            $existing = $existing->where('school_year', $payload['school_year']);
        }

        $existing = $existing->first();

        if ($existing) {
            $this->update((int)$existing['id'], $payload);
            $id = (int) $existing['id'];
        } else {
            $id = $this->insert($payload, true);
        }

        return $this->find($id) ?? $payload;
    }
}
