<?php

namespace App\Models;

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

class Order extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'product_id',
        'game_user_id',
        'game_zone_id',
        'game_nickname',
        'quantity',
        'price',
        'total_price',
        'status',
        'provider',
        'provider_trx_id',
        'sn',
        'error_message',
        'completed_at',
        'review_requested',
        'review_requested_at',
        'guest_name',
        'guest_email',
        'guest_phone',
        'review_token',
        'reviewed_at',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'completed_at' => 'datetime',
        'review_requested' => 'boolean',
        'review_requested_at' => 'datetime',
        'reviewed_at' => 'datetime',
    ];

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

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function transaction()
    {
        return $this->hasOne(Transaction::class);
    }

    public function review()
    {
        return $this->hasOne(Review::class);
    }

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

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

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

    /**
     * Check if order can be reviewed
     */
    public function canBeReviewed()
    {
        return $this->status === 'completed' 
            && !$this->review 
            && !$this->reviewed_at; // Check if not already reviewed
    }

    /**
     * Check if already reviewed
     */
    public function hasBeenReviewed()
    {
        return $this->reviewed_at !== null || $this->review !== null;
    }

    /**
     * Generate review token
     */
    public function generateReviewToken()
    {
        $this->update([
            'review_token' => \Illuminate\Support\Str::random(64),
        ]);
        
        return $this->review_token;
    }

    /**
     * Get reviewer info (user or guest)
     */
    public function getReviewerName()
    {
        return $this->user ? $this->user->name : $this->guest_name;
    }

    public function getReviewerEmail()
    {
        return $this->user ? $this->user->email : $this->guest_email;
    }

    /**
     * Check if this is a guest order
     */
    public function isGuestOrder()
    {
        return $this->user_id === null;
    }

    /**
     * Check if review has been requested
     */
    public function hasReviewRequested()
    {
        return $this->review_requested;
    }

    /**
     * Mark as review requested
     */
    public function markReviewRequested()
    {
        $this->update([
            'review_requested' => true,
            'review_requested_at' => now(),
        ]);
    }

    /**
     * Check if order is completed
     */
    public function isCompleted()
    {
        return $this->status === 'completed';
    }

    /**
     * Check if order is pending
     */
    public function isPending()
    {
        return $this->status === 'pending';
    }

    /**
     * Check if order is failed
     */
    public function isFailed()
    {
        return $this->status === 'failed';
    }
    public function isReviewTokenValid()
{
    if (!$this->review_token) return false;
    
    // Check if token expired (30 days)
    $expiresAt = $this->completed_at->addDays(30);
    
    return now()->lessThan($expiresAt) && !$this->hasBeenReviewed();
}
}
