<?php
declare(strict_types=1);

namespace App\Modules\AcademyContracts\Models;

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

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

    protected static array $fillable = [
        'contract_number',
        'academy_id',
        'contract_type',
        'start_date',
        'end_date',
        'minimum_revenue_guarantee',
        'club_commission_pct',
        'academy_share_pct',
        'fixed_monthly_rent',
        'deposit_amount',
        'deposit_status',
        'settlement_day',
        'grace_period_days',
        'penalty_rate_pct',
        'auto_renew',
        'renewal_notice_days',
        'status',
        'approved_by',
        'approved_at',
        'terminated_by',
        'terminated_at',
        'termination_reason',
        'terms_json',
        'notes',
    ];

    /**
     * Get all contract types with Arabic labels.
     */
    public static function getContractTypes(): array
    {
        return [
            'revenue_share' => 'مشاركة إيرادات',
            'fixed_rent'    => 'إيجار ثابت',
            'hybrid'        => 'نظام مختلط',
        ];
    }

    /**
     * Get all statuses with Arabic labels.
     */
    public static function getStatuses(): array
    {
        return [
            'draft'            => 'مسودة',
            'pending_approval' => 'في انتظار الموافقة',
            'active'           => 'نشط',
            'suspended'        => 'موقوف',
            'expired'          => 'منتهي',
            'terminated'       => 'ملغى',
        ];
    }

    /**
     * Get the Arabic label for a status.
     */
    public static function getStatusLabel(string $status): string
    {
        $statuses = self::getStatuses();
        return $statuses[$status] ?? $status;
    }

    /**
     * Get the badge color for a status.
     */
    public static function getStatusColor(string $status): string
    {
        $colors = [
            'draft'            => '#9CA3AF',
            'pending_approval' => '#D97706',
            'active'           => '#059669',
            'suspended'        => '#DC2626',
            'expired'          => '#6B7280',
            'terminated'       => '#991B1B',
        ];
        return $colors[$status] ?? '#6B7280';
    }

    /**
     * Get the Arabic label for a contract type.
     */
    public static function getContractTypeLabel(string $type): string
    {
        $types = self::getContractTypes();
        return $types[$type] ?? $type;
    }

    /**
     * Search contracts with filters and pagination.
     */
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query()
            ->leftJoin('academies', '`academy_contracts`.`academy_id` = `academies`.`id`')
            ->select('`academy_contracts`.*, `academies`.`name_ar` as academy_name');

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $query = $query->whereRaw(
                '(`academy_contracts`.`contract_number` LIKE ? OR `academies`.`name_ar` LIKE ?)',
                [$search, $search]
            );
        }

        if (!empty($filters['status'])) {
            $query = $query->where('academy_contracts.status', '=', $filters['status']);
        }

        if (!empty($filters['academy_id'])) {
            $query = $query->where('academy_contracts.academy_id', '=', (int) $filters['academy_id']);
        }

        if (!empty($filters['contract_type'])) {
            $query = $query->where('academy_contracts.contract_type', '=', $filters['contract_type']);
        }

        $query = $query->orderBy('academy_contracts.created_at', 'DESC');

        return $query->paginate($perPage, $page);
    }

    /**
     * Get the active contract for a specific academy.
     */
    public static function getActiveForAcademy(int $academyId): ?array
    {
        $result = static::query()
            ->where('academy_id', '=', $academyId)
            ->where('status', '=', 'active')
            ->orderBy('start_date', 'DESC')
            ->first();

        return $result ?: null;
    }
}
