<?php

namespace App\Models;

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


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

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'role',
        'partner_referrer_id',
        'partner_user_id',
        'facebook_link_1',
        'facebook_link_2',
        'facebook_link_3',
        'facebook_link_4',
        'facebook_link_5',
        'link1_like',
        'link1_comment',
        'link1_share',
        'link2_like',
        'link2_comment',
        'link2_share',
        'link3_like',
        'link3_comment',
        'link3_share',
        'link4_like',
        'link4_comment',
        'link4_share',
        'link5_like',
        'link5_comment',
        'link5_share',
        'status',
        'reviewed_by',
        'reviewed_at',
        'collected',
        'collected_at',
        'total_points',
        'reward_amount',
        'rejection_reason'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'link1_like' => 'boolean',
        'link1_comment' => 'boolean',
        'link1_share' => 'boolean',
        'link2_like' => 'boolean',
        'link2_comment' => 'boolean',
        'link2_share' => 'boolean',
        'link3_like' => 'boolean',
        'link3_comment' => 'boolean',
        'link3_share' => 'boolean',
        'link4_like' => 'boolean',
        'link4_comment' => 'boolean',
        'link4_share' => 'boolean',
        'link5_like' => 'boolean',
        'link5_comment' => 'boolean',
        'link5_share' => 'boolean',
        'collected' => 'boolean',
        'total_points' => 'integer',
        'reward_amount' => 'integer',
        'user_id' => 'integer',
        'partner_user_id' => 'integer',
        'reviewed_by' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'collected_at' => 'datetime',
        'reviewed_at' => 'datetime'
    ];

    /**
     * العلاقة مع المستخدم الرئيسي
     *
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'JID');
    }

    /**
     * العلاقة مع الشريك
     *
     * @return BelongsTo
     */
    public function partner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'partner_user_id', 'JID');
    }

    /**
     * العلاقة مع المراجع
     *
     * @return BelongsTo
     */
    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewed_by', 'JID');
    }

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

        // حساب نقاط كل رابط (like=5, comment=7, share=13)
        for ($i = 1; $i <= 5; $i++) {
            $likeField = "link{$i}_like";
            $commentField = "link{$i}_comment";
            $shareField = "link{$i}_share";

            if ($this->$likeField) $points += 5;
            if ($this->$commentField) $points += 7;
            if ($this->$shareField) $points += 13;
        }

        return $points;
    }

    /**
     * حساب مقدار المكافأة بناءً على الدور
     *
     * @return int
     */
    public function calculateReward(): int
    {
        return $this->role === 'sender' ? 50 : 20;
    }

    /**
     * التحقق من اكتمال جميع الأنشطة للروابط الخمسة
     *
     * @return bool
     */
    public function areAllActivitiesComplete(): bool
    {
        for ($i = 1; $i <= 5; $i++) {
            $likeField = "link{$i}_like";
            $commentField = "link{$i}_comment";
            $shareField = "link{$i}_share";
            $linkField = "facebook_link_{$i}";

            // التحقق من وجود الرابط وجميع الأنشطة
            if (empty($this->$linkField) || !$this->$likeField || !$this->$commentField || !$this->$shareField) {
                return false;
            }
        }

        return true;
    }

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

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

    /**
     * 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
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope للحصول على الطلبات المقبولة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeAccepted($query)
    {
        return $query->where('status', 'accepted');
    }

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

    /**
     * Scope للحصول على الطلبات المجمعة
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCollected($query)
    {
        return $query->where('collected', true);
    }

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

    /**
     * Scope للحصول على الداعين
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeSenders($query)
    {
        return $query->where('role', 'sender');
    }

    /**
     * Scope للحصول على المدعوين
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeReceivers($query)
    {
        return $query->where('role', 'receiver');
    }

    /**
     * البحث عن شريك محتمل
     *
     * @param string $username
     * @return User|null
     */
    public static function findPartnerByUsername($username)
    {
        return User::where('StrUserID', $username)->first();
    }

    /**
     * تحديد الطلب كمقبول
     *
     * @param int $reviewerId
     * @return bool
     */
    public function markAsAccepted($reviewerId): bool
    {
        $this->status = 'accepted';
        $this->reviewed_by = $reviewerId;
        $this->reviewed_at = now();
        return $this->save();
    }

    /**
     * تحديد الطلب كمرفوض
     *
     * @param int $reviewerId
     * @return bool
     */
    public function markAsRejected($reviewerId): bool
    {
        $this->status = 'rejected';
        $this->reviewed_by = $reviewerId;
        $this->reviewed_at = now();
        return $this->save();
    }

    /**
     * تحديد الطلب كمجمع
     *
     * @return bool
     */
    public function markAsCollected(): bool
    {
        $this->collected = true;
        $this->collected_at = now();
        return $this->save();
    }

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

        return [
            'total_requests' => $userRequests->count(),
            'pending_requests' => $userRequests->pending()->count(),
            'accepted_requests' => $userRequests->accepted()->count(),
            'rejected_requests' => $userRequests->rejected()->count(),
            'collected_requests' => $userRequests->collected()->count(),
            'uncollected_requests' => $userRequests->uncollected()->count(),
            'total_rewards' => $userRequests->accepted()->sum('reward_amount'),
            'collected_rewards' => $userRequests->collected()->sum('reward_amount'),
            'uncollected_rewards' => $userRequests->accepted()->uncollected()->sum('reward_amount'),
            'sender_requests' => $userRequests->senders()->count(),
            'receiver_requests' => $userRequests->receivers()->count(),
        ];
    }
}
