<?php

namespace App\Models\Marketplace;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'total_amount',
        'status', // pending, processing, shipped, delivered, completed, canceled, refunded
        'payment_method',
        'payment_status',
        'payment_id',
        'shipping_address',
        'billing_address',
        'shipping_method',
        'shipping_cost',
        'tax_amount',
        'discount_amount',
        'tracking_number',
        'notes',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'total_amount' => 'float',
        'shipping_cost' => 'float',
        'tax_amount' => 'float',
        'discount_amount' => 'float',
        'shipping_address' => 'json',
        'billing_address' => 'json',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'order_products')
                    ->withPivot('quantity', 'price', 'store_id');
    }

    public function orderProducts()
    {
        return $this->hasMany(OrderProduct::class);
    }

    // Get all stores involved in this order
    public function stores()
    {
        return Store::whereIn('id', $this->orderProducts()->distinct('store_id')->pluck('store_id'));
    }

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

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

    // Scope for canceled orders
    public function scopeCanceled($query)
    {
        return $query->where('status', 'canceled');
    }

    // Scope for orders created today
    public function scopeToday($query)
    {
        return $query->whereDate('created_at', Carbon::today());
    }

    // Scope for orders created this week
    public function scopeThisWeek($query)
    {
        return $query->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()]);
    }

    // Scope for orders created this month
    public function scopeThisMonth($query)
    {
        return $query->whereMonth('created_at', Carbon::now()->month)
                    ->whereYear('created_at', Carbon::now()->year);
    }

    // Calculate subtotal (without shipping, tax, discount)
    public function getSubtotalAttribute()
    {
        return $this->orderProducts->sum(function($item) {
            return $item->price * $item->quantity;
        });
    }
}