<?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\MorphTo;

class Payment extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'paymentable_type',
        'paymentable_id',
        'amount',
        'subscription_fee',
        'total_amount',
        'payment_method',
        'status',
        'transaction_id',
        'notes',
        'completed_at',
        'cancelled_at',
        'refund_amount',
        'refund_reason',
        'refund_requested_at',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'subscription_fee' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'refund_amount' => 'decimal:2',
        'completed_at' => 'datetime',
        'cancelled_at' => 'datetime',
        'refund_requested_at' => 'datetime',
    ];

    // العلاقات
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function paymentable(): MorphTo
    {
        return $this->morphTo();
    }

    // العلاقات القديمة للتوافق مع النظام السابق
    public function trip(): BelongsTo
    {
        return $this->belongsTo(Trip::class);
    }

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

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

    // Scopes
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeProcessing($query)
    {
        return $query->where('status', 'processing');
    }

    public function scopeCancelled($query)
    {
        return $query->where('status', 'cancelled');
    }

    public function scopeRefundRequested($query)
    {
        return $query->where('status', 'refund_requested');
    }

    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    // Accessors
    public function getFormattedAmountAttribute()
    {
        return number_format($this->amount, 2) . ' ريال';
    }

    public function getFormattedTotalAmountAttribute()
    {
        return number_format($this->total_amount, 2) . ' ريال';
    }

    public function getFormattedSubscriptionFeeAttribute()
    {
        return number_format($this->subscription_fee, 2) . ' ريال';
    }

    public function getStatusTextAttribute()
    {
        $statuses = [
            'pending' => 'في الانتظار',
            'processing' => 'قيد المعالجة',
            'completed' => 'مكتمل',
            'failed' => 'فشل',
            'cancelled' => 'ملغي',
            'refund_requested' => 'طلب استرداد',
            'refunded' => 'مسترد',
        ];

        return $statuses[$this->status] ?? $this->status;
    }

    public function getPaymentMethodTextAttribute()
    {
        $methods = [
            'cash' => 'نقداً',
            'card' => 'بطاقة ائتمان',
            'online' => 'دفع إلكتروني',
            'wallet' => 'المحفظة الإلكترونية',
        ];

        return $methods[$this->payment_method] ?? $this->payment_method;
    }

    // Methods
    public function isCompleted(): bool
    {
        return $this->status === 'completed';
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isProcessing(): bool
    {
        return $this->status === 'processing';
    }

    public function isCancelled(): bool
    {
        return $this->status === 'cancelled';
    }

    public function isFailed(): bool
    {
        return $this->status === 'failed';
    }

    public function canBeCancelled(): bool
    {
        return in_array($this->status, ['pending', 'processing']);
    }

    public function canBeRefunded(): bool
    {
        return $this->status === 'completed';
    }

    public function markAsCompleted(): void
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);
    }

    public function markAsCancelled(): void
    {
        $this->update([
            'status' => 'cancelled',
            'cancelled_at' => now()
        ]);
    }

    public function markAsFailed(): void
    {
        $this->update([
            'status' => 'failed'
        ]);
    }

    public function requestRefund(string $reason, ?float $amount = null): void
    {
        $this->update([
            'status' => 'refund_requested',
            'refund_amount' => $amount ?? $this->total_amount,
            'refund_reason' => $reason,
            'refund_requested_at' => now()
        ]);
    }
}
