<?php

namespace App\Models\SRO_VT_SHARD;

use Illuminate\Database\Eloquent\Model;
use App\Models\SRO_VT_ACCOUNT\TbUser;

class AccountJID extends Model
{
    /**
     * The Database connection name for the model.
     *
     * @var string
     */
    protected $connection = 'sqlsrv_shard';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'dbo._AccountJID';

    /**
     * The table primary Key (composite key)
     *
     * @var array
     */
    protected $primaryKey = ['AccountID', 'JID'];

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * The data type of the primary key ID.
     *
     * @var string
     */
    protected $keyType = 'string';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'AccountID',
        'JID',
        'Gold'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'JID' => 'integer',
        'Gold' => 'integer',
    ];

    // ==============================================
    // RELATIONSHIPS
    // ==============================================

    /**
     * علاقة مع TbUser في قاعدة بيانات الحسابات
     * كل سجل في _AccountJID يرتبط بمستخدم واحد في TbUser
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function tbUser()
    {
        return $this->belongsTo(TbUser::class, 'JID', 'JID');
    }

    /**
     * علاقة مع TbUser عبر AccountID (StrUserID)
     * علاقة بديلة للربط عبر اسم المستخدم
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function tbUserByAccountID()
    {
        return $this->belongsTo(TbUser::class, 'AccountID', 'StrUserID');
    }

    /**
     * علاقة مع _User في نفس قاعدة البيانات
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function shardUser()
    {
        return $this->belongsTo(_User::class, 'JID', 'UserJID');
    }

    // ==============================================
    // ACCESSORS & MUTATORS
    // ==============================================

    /**
     * Get formatted gold amount
     *
     * @return string
     */
    public function getFormattedGoldAttribute(): string
    {
        return number_format($this->Gold);
    }

    /**
     * Get gold amount in K format (1000 = 1K)
     *
     * @return string
     */
    public function getGoldKFormatAttribute(): string
    {
        if ($this->Gold >= 1000000000) {
            return round($this->Gold / 1000000000, 1) . 'B';
        } elseif ($this->Gold >= 1000000) {
            return round($this->Gold / 1000000, 1) . 'M';
        } elseif ($this->Gold >= 1000) {
            return round($this->Gold / 1000, 1) . 'K';
        }

        return (string) $this->Gold;
    }

    // ==============================================
    // HELPER METHODS
    // ==============================================

    /**
     * تحديد ما إذا كان لدى الحساب ذهب كافي
     *
     * @param int $amount
     * @return bool
     */
    public function hasEnoughGold(int $amount): bool
    {
        return $this->Gold >= $amount;
    }

    /**
     * إضافة ذهب للحساب
     *
     * @param int $amount
     * @return bool
     */
    public function addGold(int $amount): bool
    {
        $this->Gold += $amount;
        return $this->save();
    }

    /**
     * خصم ذهب من الحساب
     *
     * @param int $amount
     * @return bool
     */
    public function deductGold(int $amount): bool
    {
        if (!$this->hasEnoughGold($amount)) {
            return false;
        }

        $this->Gold -= $amount;
        return $this->save();
    }

    /**
     * تعيين كمية ذهب معينة
     *
     * @param int $amount
     * @return bool
     */
    public function setGold(int $amount): bool
    {
        $this->Gold = max(0, $amount); // تأكد من عدم وجود قيم سالبة
        return $this->save();
    }

    // ==============================================
    // SCOPES
    // ==============================================

    /**
     * Scope للحسابات التي لديها ذهب أكثر من قيمة معينة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $amount
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWithGoldGreaterThan($query, int $amount)
    {
        return $query->where('Gold', '>', $amount);
    }

    /**
     * Scope للحسابات التي لديها ذهب أقل من قيمة معينة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $amount
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWithGoldLessThan($query, int $amount)
    {
        return $query->where('Gold', '<', $amount);
    }

    /**
     * Scope للحسابات التي لديها ذهب بين قيمتين
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $min
     * @param int $max
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWithGoldBetween($query, int $min, int $max)
    {
        return $query->whereBetween('Gold', [$min, $max]);
    }

    /**
     * Scope لترتيب الحسابات حسب الذهب (من الأعلى للأقل)
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeRichest($query)
    {
        return $query->orderBy('Gold', 'desc');
    }

    /**
     * Scope لترتيب الحسابات حسب الذهب (من الأقل للأعلى)
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePoorest($query)
    {
        return $query->orderBy('Gold', 'asc');
    }
}
