<?php

namespace App\Models\Z_Website\Market;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\Models\Z_Website\User;

class MarketTransaction extends Model
{
    use HasFactory;

    protected $table = 'market_transactions';

    protected $fillable = [
        'transaction_id',
        'user_jid',
        'username',
        'transaction_type',
        'item_id',
        'item_name',
        'quantity',
        'unit_price',
        'total_price',
        'currency_type',
        'balance_before',
        'balance_after',
        'status',
        'error_message',
        'transaction_details',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'balance_before' => 'decimal:2',
        'balance_after' => 'decimal:2',
        'transaction_details' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // Constants for transaction types
    const TYPE_PACKAGE = 'package';
    const TYPE_ITEM = 'item';

    // Constants for status
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';
    const STATUS_PENDING = 'pending';

    // Currency types
    const CURRENCY_BALANCE = 'balance';
    const CURRENCY_GIFT_BALANCE = 'gift_balance';
    const CURRENCY_SILK = 'silk';
    const CURRENCY_DONATE = 'donate';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($transaction) {
            if (empty($transaction->transaction_id)) {
                $transaction->transaction_id = self::generateTransactionId();
            }
        });
    }

    // Generate unique transaction ID
    public static function generateTransactionId()
    {
        do {
            $id = 'TXN' . date('Ymd') . strtoupper(Str::random(6));
        } while (self::where('transaction_id', $id)->exists());

        return $id;
    }

    // Create a new transaction log
    public static function createLog($data)
    {
        return self::create([
            'user_jid' => $data['user_jid'],
            'username' => $data['username'] ?? null,
            'transaction_type' => $data['transaction_type'],
            'item_id' => $data['item_id'] ?? null,
            'item_name' => $data['item_name'],
            'quantity' => $data['quantity'] ?? 1,
            'unit_price' => $data['unit_price'],
            'total_price' => $data['total_price'],
            'currency_type' => $data['currency_type'],
            'balance_before' => $data['balance_before'],
            'balance_after' => $data['balance_after'],
            'status' => $data['status'] ?? self::STATUS_PENDING,
            'error_message' => $data['error_message'] ?? null,
            'transaction_details' => $data['transaction_details'] ?? null,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);
    }

    // Relationship with User
    public function user()
    {
        return $this->belongsTo(User::class, 'user_jid', 'JID');
    }

    // Scopes
    public function scopeSuccess($query)
    {
        return $query->where('status', self::STATUS_SUCCESS);
    }

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

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

    public function scopeByUser($query, $userJid)
    {
        return $query->where('user_jid', $userJid);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('transaction_type', $type);
    }

    public function scopeByCurrency($query, $currency)
    {
        return $query->where('currency_type', $currency);
    }

    public function scopeToday($query)
    {
        return $query->whereDate('created_at', today());
    }

    public function scopeThisWeek($query)
    {
        return $query->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
    }

    public function scopeThisMonth($query)
    {
        return $query->whereMonth('created_at', now()->month)
                    ->whereYear('created_at', now()->year);
    }

    // Accessors
    public function getCurrencySymbolAttribute()
    {
        $symbols = [
            self::CURRENCY_BALANCE => '💎',
            self::CURRENCY_GIFT_BALANCE => '⭐',
            self::CURRENCY_SILK => '✨',
            self::CURRENCY_DONATE => '💖'
        ];

        return $symbols[$this->currency_type] ?? '💎';
    }

    public function getStatusColorAttribute()
    {
        $colors = [
            self::STATUS_SUCCESS => 'text-green-400',
            self::STATUS_FAILED => 'text-red-400',
            self::STATUS_PENDING => 'text-yellow-400'
        ];

        return $colors[$this->status] ?? 'text-gray-400';
    }

    public function getStatusBadgeAttribute()
    {
        $badges = [
            self::STATUS_SUCCESS => 'bg-green-600',
            self::STATUS_FAILED => 'bg-red-600',
            self::STATUS_PENDING => 'bg-yellow-600'
        ];

        return $badges[$this->status] ?? 'bg-gray-600';
    }

    // Create Transaction Log by JID and transaction_type and item_id and status
    public static function logTransaction($userJid, $transactionType, $itemId, $status, $additionalData = [])
    {
        $user = User::where('JID', $userJid)->first();

        if (!$user) {
            throw new \Exception("User with JID {$userJid} not found.");
        }

        // Get Item Info from MarketItem or MarketPackage
        if ($transactionType === self::TYPE_ITEM) {
            $item = MarketItem::find($itemId);
            $itemName = $item->name ?? 'Unknown Item';
        } elseif ($transactionType === self::TYPE_PACKAGE) {
            $item = MarketPackage::find($itemId);
            $itemName = $item->package_name ?? 'Unknown Package'; // تصحيح: package_name بدلاً من name
        } else {
            throw new \Exception("Invalid transaction type: {$transactionType}");
        }

        if (!$item) {
            throw new \Exception("Item/Package with ID {$itemId} not found.");
        }

        $unitPrice = $item->price ?? 0;
        $quantity = $additionalData['quantity'] ?? 1;
        $totalPrice = $unitPrice * $quantity;
        $currencyType = $item->balance_type ?? self::CURRENCY_BALANCE;

        // الحصول على الرصيد الحالي بناءً على نوع العملة
        $balanceBefore = 0;
        switch($currencyType) {
            case self::CURRENCY_BALANCE:
                $balanceBefore = $user->webUser->balance ?? 0;
                break;
            case self::CURRENCY_GIFT_BALANCE:
                $balanceBefore = $user->webUser->gift_balance ?? 0;
                break;
            case self::CURRENCY_SILK:
                $balanceBefore = $user->skSilk->silk_own ?? 0;
                break;
            case self::CURRENCY_DONATE:
                $balanceBefore = $user->skSilk->silk_gift ?? 0;
                break;
        }

        $balanceAfter = $balanceBefore;

        // إذا كانت المعاملة ناجحة، قم بخصم الرصيد
        if ($status === self::STATUS_SUCCESS) {
            switch($currencyType) {
                case self::CURRENCY_BALANCE:
                    $user->webUser->balance -= $totalPrice;
                    $balanceAfter = $user->webUser->balance;
                    break;
                case self::CURRENCY_GIFT_BALANCE:
                    $user->webUser->gift_balance -= $totalPrice;
                    $balanceAfter = $user->webUser->gift_balance;
                    break;
                case self::CURRENCY_SILK:
                    $user->skSilk->silk_own -= $totalPrice;
                    $balanceAfter = $user->skSilk->silk_own;
                    break;
                case self::CURRENCY_DONATE:
                    $user->skSilk->silk_gift -= $totalPrice;
                    $balanceAfter = $user->skSilk->silk_gift;
                    break;
            }
        }

        // إنشاء log المعاملة
        $logData = [
            'user_jid' => $userJid,
            'username' => $user->username ?? $user->UserID ?? 'Unknown',
            'transaction_type' => $transactionType,
            'item_id' => $itemId,
            'item_name' => $itemName,
            'quantity' => $quantity,
            'unit_price' => $unitPrice,
            'total_price' => $totalPrice,
            'currency_type' => $currencyType,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'status' => $status,
            'error_message' => $additionalData['error_message'] ?? null,
            'transaction_details' => $additionalData['transaction_details'] ?? null,
        ];

        return self::createLog($logData);
    }
}
