<?php

namespace App\Domain\Inventory\Models;

use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ProductInstallmentPlan extends Model
{
    use BelongsToAcademy, HasUuid;

    protected $fillable = [
        'academy_id',
        'product_id',
        'membership_tier',
        'label_ar',
        'installments',
        'frequency',
        'down_payment_pct',
        'is_active',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'installments' => 'integer',
            'down_payment_pct' => 'integer',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeForTier(Builder $query, string $tier): Builder
    {
        return $query->where(fn ($q) =>
            $q->where('membership_tier', $tier)->orWhere('membership_tier', 'any')
        );
    }

    /** Calculate down payment amount in piasters */
    public function downPaymentAmount(int $totalPiasters): int
    {
        if ($this->down_payment_pct <= 0) {
            return (int) ceil($totalPiasters / $this->installments);
        }
        return (int) ceil($totalPiasters * $this->down_payment_pct / 100);
    }

    /** Calculate per-installment amount (after down payment) in piasters */
    public function regularInstallmentAmount(int $totalPiasters): int
    {
        $remaining = $this->installments - 1;
        if ($remaining <= 0) {
            return 0;
        }
        $afterDown = $totalPiasters - $this->downPaymentAmount($totalPiasters);
        return (int) ceil($afterDown / $remaining);
    }

    public function frequencyLabel(): string
    {
        return match ($this->frequency) {
            'weekly' => 'أسبوعي',
            'biweekly' => 'نصف شهري',
            'monthly' => 'شهري',
            'quarterly' => 'ربع سنوي',
            default => $this->frequency,
        };
    }

    public function tierLabel(): string
    {
        return match ($this->membership_tier) {
            'member' => 'أعضاء',
            'non_member' => 'غير أعضاء',
            default => 'الجميع',
        };
    }
}
