<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\Z_Website\User;

class FastEventsTreasure extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'fast_events_treasure';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'link',
        'like',
        'comment',
        'share',
        'total_points',
        'status',
        'collected',
        'collected_at',
        'accepted',
        'accepted_by',
        'accepted_at',
        'rejection_reason',
        'reviewed_at'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'like' => 'boolean',
        'comment' => 'boolean',
        'share' => 'boolean',
        'total_points' => 'integer',
        'collected' => 'boolean',
        'accepted' => 'boolean',
        'accepted_by' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'collected_at' => 'datetime',
        'accepted_at' => 'datetime',
        'reviewed_at' => 'datetime'
    ];

    /**
     * Status constants
     */
    const STATUS_PENDING = 'pending';
    const STATUS_APPROVED = 'approved';
    const STATUS_REJECTED = 'rejected';
    const STATUS_COLLECTED = 'collected';    /**
     * العلاقة مع المستخدم
     *
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'JID');
    }

    /**
     * العلاقة مع المستخدم الذي قبل المشاركة
     *
     * @return BelongsTo
     */
    public function acceptedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'accepted_by', 'JID');
    }

    /**
     * حساب إجمالي النقاط بناءً على الأنشطة
     *
     * @return int
     */
    public function calculatePoints(): int
    {
        $points = 0;

        if ($this->like) {
            $points += 5;
        }

        if ($this->comment) {
            $points += 7;
        }

        if ($this->share) {
            $points += 13;
        }

        return $points;
    }

    /**
     * تحديث النقاط تلقائياً عند الحفظ
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            $model->total_points = $model->calculatePoints();

            // تحديث الحالة تلقائياً إذا لم تكن محددة
            if (empty($model->status)) {
                $model->status = self::STATUS_PENDING;
            }
        });
    }

    /**
     * Get status label
     *
     * @return string
     */
    public function getStatusLabel(): string
    {
        return match($this->status) {
            self::STATUS_PENDING => 'Pending Review',
            self::STATUS_APPROVED => 'Approved',
            self::STATUS_REJECTED => 'Rejected',
            self::STATUS_COLLECTED => 'Collected',
            default => 'Unknown'
        };
    }

    /**
     * Get status color class
     *
     * @return string
     */
    public function getStatusColor(): string
    {
        return match($this->status) {
            self::STATUS_PENDING => 'pending',
            self::STATUS_APPROVED => 'approved',
            self::STATUS_REJECTED => 'rejected',
            self::STATUS_COLLECTED => 'collected',
            default => 'unknown'
        };
    }

    /**
     * Check if treasure can be collected
     *
     * @return bool
     */
    public function canBeCollected(): bool
    {
        return $this->status === self::STATUS_APPROVED && !$this->collected;
    }

    /**
     * Check if treasure can be approved
     *
     * @return bool
     */
    public function canBeApproved(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * Check if treasure can be rejected
     *
     * @return bool
     */
    public function canBeRejected(): bool
    {
        return in_array($this->status, [self::STATUS_PENDING, self::STATUS_APPROVED]);
    }

    /**
     * Scope للحصول على بيانات مستخدم معين
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $userId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope للحصول على المشاركات مع نقاط معينة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param int $minPoints
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWithMinPoints($query, $minPoints = 1)
    {
        return $query->where('total_points', '>=', $minPoints);
    }

    /**
     * Scope للحصول على المشاركات المجمعة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCollected($query)
    {
        return $query->where('status', self::STATUS_COLLECTED);
    }

    /**
     * Scope للحصول على المشاركات غير المجمعة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeUncollected($query)
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    /**
     * Scope للحصول على المشاركات المقبولة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeAccepted($query)
    {
        return $query->whereIn('status', [self::STATUS_APPROVED, self::STATUS_COLLECTED]);
    }

    /**
     * Scope للحصول على المشاركات المعلقة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePending($query)
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    /**
     * Scope للحصول على المشاركات المرفوضة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeRejected($query)
    {
        return $query->where('status', self::STATUS_REJECTED);
    }

    /**
     * Scope بناءً على الحالة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $status
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * الحصول على إجمالي النقاط لمستخدم معين
     *
     * @param int $userId
     * @return int
     */
    public static function getTotalPointsForUser($userId): int
    {
        return static::forUser($userId)->sum('total_points');
    }

    /**
     * الحصول على إجمالي النقاط المجمعة لمستخدم معين
     *
     * @param int $userId
     * @return int
     */
    public static function getCollectedPointsForUser($userId): int
    {
        return static::forUser($userId)->collected()->sum('total_points');
    }

    /**
     * الحصول على إجمالي النقاط غير المجمعة لمستخدم معين
     *
     * @param int $userId
     * @return int
     */
    public static function getUncollectedPointsForUser($userId): int
    {
        return static::forUser($userId)->uncollected()->sum('total_points');
    }

    /**
     * الحصول على إحصائيات شاملة لمستخدم معين
     *
     * @param int $userId
     * @return array
     */
    public static function getUserStats($userId): array
    {
        $user = static::forUser($userId);

        return [
            'total_posts' => $user->count(),
            'pending_posts' => $user->pending()->count(),
            'approved_posts' => $user->where('status', self::STATUS_APPROVED)->count(),
            'rejected_posts' => $user->rejected()->count(),
            'collected_posts' => $user->collected()->count(),
            'uncollected_posts' => $user->uncollected()->count(),
            'total_points' => $user->sum('total_points'),
            'pending_points' => $user->pending()->sum('total_points'),
            'approved_points' => $user->where('status', self::STATUS_APPROVED)->sum('total_points'),
            'collected_points' => $user->collected()->sum('total_points'),
            'uncollected_points' => $user->uncollected()->sum('total_points'),
        ];
    }

    /**
     * تحديد المشاركة كمجمعة
     *
     * @return bool
     */
    public function markAsCollected(): bool
    {
        if (!$this->canBeCollected()) {
            return false;
        }

        $this->status = self::STATUS_COLLECTED;
        $this->collected = true;
        $this->collected_at = now();
        return $this->save();
    }

    /**
     * قبول المشاركة
     *
     * @param int $acceptedByUserId
     * @return bool
     */
    public function markAsAccepted($acceptedByUserId): bool
    {
        if (!$this->canBeApproved()) {
            return false;
        }

        $this->status = self::STATUS_APPROVED;
        $this->accepted = true;
        $this->accepted_by = $acceptedByUserId;
        $this->accepted_at = now();
        $this->reviewed_at = now();
        $this->rejection_reason = null;
        return $this->save();
    }

    /**
     * رفض المشاركة
     *
     * @param string|null $reason
     * @param int|null $rejectedBy
     * @return bool
     */
    public function markAsRejected($reason = null, $rejectedBy = null): bool
    {
        if (!$this->canBeRejected()) {
            return false;
        }

        $this->status = self::STATUS_REJECTED;
        $this->accepted = false;
        $this->accepted_by = $rejectedBy;
        $this->accepted_at = null;
        $this->reviewed_at = now();
        $this->rejection_reason = $reason;
        $this->collected = false;
        $this->collected_at = null;
        return $this->save();
    }

    /**
     * إعادة تعيين المشاركة إلى حالة الانتظار
     *
     * @return bool
     */
    public function resetToPending(): bool
    {
        $this->status = self::STATUS_PENDING;
        $this->accepted = false;
        $this->accepted_by = null;
        $this->accepted_at = null;
        $this->reviewed_at = null;
        $this->rejection_reason = null;
        $this->collected = false;
        $this->collected_at = null;
        return $this->save();
    }

    /**
     * التحقق من وجود رابط مسبقاً
     *
     * @param string $link
     * @param int|null $excludeId
     * @return bool
     */
    public static function linkExists($link, $excludeId = null): bool
    {
        $query = static::where('link', $link);

        if ($excludeId) {
            $query->where('id', '!=', $excludeId);
        }

        return $query->exists();
    }
}
