<?php
declare(strict_types=1);

namespace App\Modules\TrainingGroups\Models;

use App\Core\Model;
use App\Core\App;

class TrainingGroup extends Model
{
    protected static string $table = 'training_groups';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'code',
        'name_ar',
        'name_en',
        'academy_id',
        'level_id',
        'coach_id',
        'facility_id',
        'group_type',
        'min_capacity',
        'max_capacity',
        'current_count',
        'age_from',
        'age_to',
        'gender_restriction',
        'day_of_week',
        'start_time',
        'end_time',
        'pricing_tier',
        'is_full',
        'is_active',
    ];

    public static function getGroupTypes(): array
    {
        return [
            'private'     => 'خاص (فردي)',
            'small_group' => 'مجموعة صغيرة (2-5)',
            'group'       => 'مجموعة (6-15)',
            'team'        => 'فريق (16+)',
        ];
    }

    public static function getPricingTiers(): array
    {
        return [
            'premium'  => 'بريميوم',
            'standard' => 'عادي',
            'economy'  => 'اقتصادي',
        ];
    }

    public function getMembers(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT gm.*, p.full_name_ar AS player_name, p.date_of_birth, p.gender, p.phone
             FROM group_memberships gm
             LEFT JOIN players p ON p.id = gm.player_id
             WHERE gm.group_id = ? AND gm.status = 'active'
             ORDER BY gm.joined_at ASC",
            [(int) $this->id]
        );
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();

        $where = ['tg.is_archived = 0'];
        $params = [];

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where[] = '(tg.name_ar LIKE ? OR tg.name_en LIKE ? OR tg.code LIKE ?)';
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
        }

        if (!empty($filters['academy_id'])) {
            $where[] = 'tg.academy_id = ?';
            $params[] = (int) $filters['academy_id'];
        }

        if (!empty($filters['level_id'])) {
            $where[] = 'tg.level_id = ?';
            $params[] = (int) $filters['level_id'];
        }

        if (!empty($filters['group_type'])) {
            $where[] = 'tg.group_type = ?';
            $params[] = $filters['group_type'];
        }

        if (!empty($filters['coach_id'])) {
            $where[] = 'tg.coach_id = ?';
            $params[] = (int) $filters['coach_id'];
        }

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $where[] = 'tg.is_active = ?';
            $params[] = (int) $filters['is_active'];
        }

        $whereClause = implode(' AND ', $where);

        $countSql = "SELECT COUNT(*) AS total FROM training_groups tg WHERE {$whereClause}";
        $countResult = $db->selectOne($countSql, $params);
        $total = (int) ($countResult['total'] ?? 0);

        $lastPage = max(1, (int) ceil($total / $perPage));
        $page = min($page, $lastPage);
        $offset = ($page - 1) * $perPage;

        $sql = "SELECT tg.*, a.name_ar AS academy_name, al.name_ar AS level_name, c.full_name_ar AS coach_name
                FROM training_groups tg
                LEFT JOIN academies a ON a.id = tg.academy_id
                LEFT JOIN academy_levels al ON al.id = tg.level_id
                LEFT JOIN coaches c ON c.id = tg.coach_id
                WHERE {$whereClause}
                ORDER BY tg.name_ar ASC
                LIMIT {$perPage} OFFSET {$offset}";

        $data = $db->select($sql, $params);

        return [
            'data' => $data,
            'pagination' => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => $lastPage,
            ],
        ];
    }

    public static function getAvailableForDiscipline(int $disciplineId, int $levelId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tg.*, a.name_ar AS academy_name, al.name_ar AS level_name, c.full_name_ar AS coach_name
             FROM training_groups tg
             INNER JOIN academies a ON a.id = tg.academy_id
             LEFT JOIN academy_levels al ON al.id = tg.level_id
             LEFT JOIN coaches c ON c.id = tg.coach_id
             WHERE a.discipline_id = ?
               AND tg.level_id = ?
               AND tg.is_active = 1
               AND tg.is_full = 0
               AND tg.is_archived = 0
             ORDER BY tg.current_count ASC",
            [$disciplineId, $levelId]
        );
    }
}
