<?php

namespace App\Models;

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

class RechargeTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'transaction_id',
        'user_id',
        'user_name',
        'user_email',
        'user_phone',
        'payment_method',
        'amount',
        'fee',
        'total_amount',
        'currency',
        'diamonds_purchased',
        'status',
        'note',
        'payment_details',
        'payment_date',
        'processed_at'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'fee' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'diamonds_purchased' => 'integer',
        'payment_details' => 'array',
        'payment_date' => 'datetime',
        'processed_at' => 'datetime'
    ];

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

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

    /**
     * Scope for failed transactions
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Scope for specific payment method
     */
    public function scopeByPaymentMethod($query, string $method)
    {
        return $query->where('payment_method', $method);
    }

    /**
     * Mark transaction as completed
     */
    public function markAsCompleted(): bool
    {
        $this->status = 'completed';
        $this->processed_at = Carbon::now();
        return $this->save();
    }

    /**
     * Mark transaction as failed
     */
    public function markAsFailed(): bool
    {
        $this->status = 'failed';
        $this->processed_at = Carbon::now();
        return $this->save();
    }

    /**
     * Get rewards associated with this transaction
     */
    public function rewards()
    {
        return $this->hasMany(RechargeReward::class, 'recharge_transaction_id');
    }

    /**
     * Get user's transaction history
     */
    public static function getUserHistory(int $userId, int $limit = 10)
    {
        return static::where('user_id', $userId)
                    ->orderBy('created_at', 'desc')
                    ->limit($limit)
                    ->get();
    }

    /**
     * Get recent transactions for admin
     */
    public static function getRecentTransactions(int $limit = 20)
    {
        return static::with('user')
                    ->orderBy('created_at', 'desc')
                    ->limit($limit)
                    ->get();
    }
}
