<?php
declare(strict_types=1);

namespace App\Modules\ActivitySubscriptions\Models;

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

class ActivityPricing extends Model
{
    protected static string $table = 'activity_pricing';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'pricing_type',
        'reference_id',
        'member_rate',
        'nonmember_rate',
        'member_rate_pm',
        'nonmember_rate_pm',
        'effective_from',
        'effective_to',
        'is_active',
        'created_by',
    ];

    /**
     * Get all pricing types with Arabic labels.
     */
    public static function getPricingTypes(): array
    {
        return [
            'academy'    => 'أكاديمية',
            'discipline' => 'نشاط',
            'facility'   => 'مرفق',
        ];
    }

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

    /**
     * Get the effective rate for a pricing type and reference.
     *
     * Finds the active pricing record where effective_from <= today
     * and (effective_to IS NULL OR effective_to >= today), then returns
     * the appropriate rate based on membership status and time tier.
     */
    public static function getEffectiveRate(
        string $type,
        int $refId,
        bool $isMember,
        ?string $timeTier = null
    ): float {
        $today = date('Y-m-d');

        $query = static::query()
            ->where('pricing_type', '=', $type)
            ->where('reference_id', '=', $refId)
            ->where('is_active', '=', 1)
            ->whereRaw('`effective_from` <= ?', [$today])
            ->whereRaw('(`effective_to` IS NULL OR `effective_to` >= ?)', [$today])
            ->orderBy('effective_from', 'DESC')
            ->limit(1);

        $rows = $query->get();
        $row = $rows[0] ?? null;

        if (!$row) {
            return 0.0;
        }

        if ($timeTier === 'PM') {
            return (float) ($isMember ? $row['member_rate_pm'] : $row['nonmember_rate_pm']);
        }

        return (float) ($isMember ? $row['member_rate'] : $row['nonmember_rate']);
    }

    /**
     * Search pricing records with filters and pagination.
     */
    public static function search(array $filters = [], int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

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

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $query = $query->where('is_active', '=', (int) $filters['is_active']);
        }

        $query = $query->orderBy('pricing_type', 'ASC')->orderBy('reference_id', 'ASC');

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