<?php

namespace App\Models;

use CodeIgniter\Model;

class BuilderMatchModel extends Model
{
    protected $table = 'builder_matches';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'team1',
        'team2',
        'league',
        'match_time',
        'odds',
        'our_prediction',
        'status',
        'result_outcome',
        'is_archived',
        'created_at',
        'updated_at',
    ];

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

    public const TAB_UPCOMING = 'upcoming';
    public const TAB_SETTLED = 'settled';

    /**
     * Admin list: upcoming legs vs settled/void history.
     */
    public function forAdminTab(string $tab)
    {
        if ($tab === self::TAB_SETTLED) {
            return $this->whereIn('status', ['settled', 'void']);
        }

        return $this->where('status', 'upcoming');
    }

    /**
     * Count matches for an admin tab badge.
     */
    public function countForAdminTab(string $tab): int
    {
        return $this->forAdminTab($tab)->countAllResults();
    }

    /**
     * Upcoming, non-archived matches with kickoff in the future.
     * Returns an array of matches ordered by match_time ascending.
     */
    public function upcoming(): array
    {
        return $this->where('is_archived', 0)
            ->where('status', 'upcoming')
            ->groupStart()
                ->where('match_time IS NULL', null, false)
                ->orWhere('match_time >', date('Y-m-d H:i:s'))
            ->groupEnd()
            ->orderBy('match_time', 'ASC')
            ->findAll();
    }

    /**
     * Whether a builder match already exists for the same teams and kickoff.
     */
    public function existsDuplicate(string $team1, string $team2, ?string $matchTime): bool
    {
        $builder = $this->where('team1', $team1)->where('team2', $team2);

        if ($matchTime === null || $matchTime === '') {
            $builder->where('match_time IS NULL', null, false);
        } else {
            $builder->where('match_time', $matchTime);
        }

        return $builder->countAllResults() > 0;
    }

    /**
     * Normalize kickoff to Y-m-d H:i:s for storage and dedup.
     */
    public static function normalizeMatchTime(?string $raw): ?string
    {
        if ($raw === null || trim($raw) === '') {
            return null;
        }

        $ts = strtotime($raw);
        if ($ts === false) {
            return null;
        }

        return date('Y-m-d H:i:s', $ts);
    }

    /**
     * Public-facing projection that omits the hidden our_prediction field.
     */
    public function toPublicArray(array $match): array
    {
        return [
            'id' => (int) $match['id'],
            'team1' => $match['team1'] ?? '',
            'team2' => $match['team2'] ?? '',
            'league' => $match['league'] ?? '',
            'match_time' => $match['match_time'] ?? null,
            'status' => $match['status'] ?? 'upcoming',
        ];
    }
}
