<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'product_id',
        'flash_sale_id',
        'game_user_id',
        'game_server_id',
        'whatsapp',
        'email',
        'original_price',
        'final_price',
        'discount_amount',
        'status',
        'payment_method',
        'payment_proof',
        'paid_at',
        'completed_at',
        'expired_at',
        'admin_notes',
        'customer_notes',
    ];

    protected $casts = [
        'original_price' => 'decimal:2',
        'final_price' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'paid_at' => 'datetime',
        'completed_at' => 'datetime',
        'expired_at' => 'datetime',
    ];

    /**
     * Boot method to generate order_id
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($order) {
            if (empty($order->order_id)) {
                $order->order_id = self::generateOrderId();
            }

            // Set expiration time (24 hours from now)
            if (empty($order->expired_at)) {
                $order->expired_at = Carbon::now()->addHours(24);
            }
        });
    }

    /**
     * Generate unique order ID
     */
    public static function generateOrderId()
    {
        do {
            $orderId = 'RIS-' . strtoupper(Str::random(8));
        } while (self::where('order_id', $orderId)->exists());

        return $orderId;
    }

    /**
     * Get the product for this order
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Get the flash sale if applicable
     */
    public function flashSale()
    {
        return $this->belongsTo(FlashSale::class);
    }

    /**
     * Check if order is from flash sale
     */
    public function isFlashSaleOrder()
    {
        return !is_null($this->flash_sale_id);
    }

    /**
     * Check if order is expired
     */
    public function isExpired()
    {
        return $this->status === 'pending' &&
            $this->expired_at &&
            Carbon::now()->gt($this->expired_at);
    }

    /**
     * Check if order can be paid
     */
    public function canBePaid()
    {
        return $this->status === 'pending' && !$this->isExpired();
    }

    /**
     * Get time remaining for payment in seconds
     */
    public function getPaymentTimeRemaining()
    {
        if (!$this->canBePaid() || !$this->expired_at) {
            return 0;
        }

        return max(0, $this->expired_at->diffInSeconds(Carbon::now()));
    }

    /**
     * Mark order as paid
     */
    public function markAsPaid($paymentMethod = 'manual', $paymentProof = null)
    {
        $this->update([
            'status' => 'paid',
            'payment_method' => $paymentMethod,
            'payment_proof' => $paymentProof,
            'paid_at' => Carbon::now(),
        ]);
    }

    /**
     * Mark order as processing
     */
    public function markAsProcessing()
    {
        $this->update(['status' => 'processing']);
    }

    /**
     * Mark order as completed
     */
    public function markAsCompleted()
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => Carbon::now(),
        ]);
    }

    /**
     * Mark order as failed
     */
    public function markAsFailed($reason = null)
    {
        $this->update([
            'status' => 'failed',
            'admin_notes' => $reason,
        ]);
    }

    /**
     * Get status label in Indonesian
     */
    public function getStatusLabel()
    {
        $labels = [
            'pending' => 'Menunggu Pembayaran',
            'paid' => 'Sudah Dibayar',
            'processing' => 'Sedang Diproses',
            'completed' => 'Selesai',
            'failed' => 'Gagal',
            'refunded' => 'Dikembalikan',
            'expired' => 'Kadaluarsa',
        ];

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

    /**
     * Get status color class
     */
    public function getStatusClass()
    {
        $classes = [
            'pending' => 'warning',
            'paid' => 'info',
            'processing' => 'info',
            'completed' => 'success',
            'failed' => 'danger',
            'refunded' => 'secondary',
            'expired' => 'secondary',
        ];

        return $classes[$this->status] ?? 'secondary';
    }

    /**
     * Get formatted WhatsApp number
     */
    public function getFormattedWhatsApp()
    {
        $number = preg_replace('/[^0-9]/', '', $this->whatsapp);

        // Convert 08xx to 628xx
        if (str_starts_with($number, '0')) {
            $number = '62' . substr($number, 1);
        }

        return $number;
    }

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

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

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

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