<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class PartnerWallet extends Model
{
    use HasFactory;

    const OWNER_TYPE_RESTAURANT = 'restaurant';
    const OWNER_TYPE_GAS_OFFICE = 'gas_office';
    const OWNER_TYPE_DRIVER = 'driver';

    protected $fillable = [
        'owner_type',
        'owner_id',
        'balance',
        'currency',
        'is_active',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    /**
     * المالك (مطعم أو مكتب غاز) - علاقة متعددة الأشكال لتفادي null مع التحميل المبكر
     */
    public function owner(): MorphTo
    {
        return $this->morphTo();
    }

    /**
     * إعدادات المحفظة
     */
    public function settings(): HasOne
    {
        return $this->hasOne(PartnerWalletSetting::class);
    }

    /**
     * معاملات المحفظة
     */
    public function transactions(): HasMany
    {
        return $this->hasMany(PartnerWalletTransaction::class)->orderBy('created_at', 'desc');
    }

    /**
     * الحصول على محفظة الشريك أو إنشاؤها
     */
    public static function getOrCreateFor(string $ownerType, int $ownerId): self
    {
        $wallet = self::where('owner_type', $ownerType)
            ->where('owner_id', $ownerId)
            ->first();

        if ($wallet) {
            return $wallet;
        }

        $wallet = self::create([
            'owner_type' => $ownerType,
            'owner_id' => $ownerId,
            'balance' => 0.00,
            'currency' => 'IQD',
            'is_active' => true,
        ]);

        // إنشاء إعدادات افتراضية
        PartnerWalletSetting::create([
            'partner_wallet_id' => $wallet->id,
            'payment_methods' => ['zain_cash', 'mastercard'],
            'min_topup_amount' => 1000,
            'max_topup_amount' => 5000000,
            'allow_negative_balance' => true,
        ]);

        return $wallet;
    }

    /**
     * هل الرصيد سالب (ماينص)؟
     */
    public function hasNegativeBalance(): bool
    {
        return (float) $this->balance < 0;
    }
}
