<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PlatformFee extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_type',
        'order_id',
        'order_number',
        'service_provider_id',
        'service_provider_type',
        'order_total',
        'platform_fee',
        'fee_percentage',
        'status',
        'paid_at',
        'notes',
    ];

    protected $casts = [
        'order_total' => 'decimal:2',
        'platform_fee' => 'decimal:2',
        'fee_percentage' => 'decimal:4',
        'paid_at' => 'datetime',
    ];

    /**
     * Get the parent order (polymorphic relationship).
     */
    public function order()
    {
        return $this->morphTo('order', 'order_type', 'order_id');
    }

    /**
     * Get the service provider (Restaurant or GasOffice).
     */
    public function serviceProvider()
    {
        if ($this->service_provider_type === 'restaurant') {
            return $this->belongsTo(Restaurant::class, 'service_provider_id');
        } elseif ($this->service_provider_type === 'gas_office') {
            return $this->belongsTo(GasOffice::class, 'service_provider_id');
        }
        return null;
    }

    /**
     * Scope a query to only include fees for a specific service provider.
     */
    public function scopeByServiceProvider($query, $providerId, $providerType)
    {
        return $query->where('service_provider_id', $providerId)
                     ->where('service_provider_type', $providerType);
    }

    /**
     * Scope a query to only include fees with a specific status.
     */
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * Mark fee as paid.
     */
    public function markAsPaid()
    {
        $this->update([
            'status' => 'paid',
            'paid_at' => now(),
        ]);
    }

    /**
     * Mark fee as collected.
     */
    public function markAsCollected()
    {
        $this->update([
            'status' => 'collected',
        ]);
    }
}
