<?php

namespace App\Models\Z_Website\Quests;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use App\Models\SRO_VT_SHARD\Char;
use App\Models\SRO_VT_PROXY_Helper\_InstantItemDelivery_3s;
use App\Models\SRO_VT_PROXY\_AutoNotice;

class TaskReward extends Model
{
    protected $table = 'tasks_rewards';

    protected $primaryKey = 'id';
    /**
     * الأعمدة القابلة للتعبئة
     */
    protected $fillable = [
        'reward_type',
        'reward_count',
        'reward_codename',
        'reward_name',
        'reward_icon',
        'random_id',
        'package_id',
    ];

    /**
     * تحويل القيم للأنواع المناسبة
     */
    protected $casts = [
        'reward_type' => 'string',
        'reward_count' => 'integer',
        'reward_codename' => 'string',
        'reward_name' => 'string',
        'reward_icon' => 'string',
        'random_id' => 'integer',
        'package_id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * العلاقة مع جدول TaskRewardChain كـ normal_reward
     */
    public function normalRewardChains()
    {
        return $this->hasMany(TaskRewardChain::class, 'normal_reward');
    }

    /**
     * العلاقة مع جدول TaskRewardChain كـ vip_reward
     */
    public function vipRewardChains()
    {
        return $this->hasMany(TaskRewardChain::class, 'vip_reward');
    }


    //Send Reward by reward_id and CharID
    public static function sendReward($rewardId)
    {
        $user = Auth::user();
        if (!$user) {
            return false; // User not authenticated
        }
        $ownchar = TaskUserVipStatus::where('user_id', $user->JID)->value('CharID');
        if (!$ownchar) {
            return false; // No character associated with user
        }
        $charname = Char::where('CharID', $ownchar)->value('CharName16');
        if (!$charname) {
            return false; // Character not found
        }
        $reward = self::find($rewardId);
        if (!$reward) {
            return false; // Reward not found
        }
        
        //check reward_type if balance or gift_balance or 4TDonate or Silk or item
        if (in_array($reward->reward_type, ['balance', 'gift_balance', '4TDonate', 'Silk'])) {
            if ($reward->reward_type === 'balance') {
                //add balance to User webUser->balance + reward_count
                $user->webUser->balance += $reward->reward_count;
                $user->webUser->save();
            } elseif ($reward->reward_type === 'gift_balance') {
                //add gift balance to User webUser->gift_balance + reward_count
                $user->webUser->gift_balance += $reward->reward_count;
                $user->webUser->save();
            } elseif ($reward->reward_type === '4TDonate') {
                $user->skSilk->silk_gift += $reward->reward_count;
                $user->skSilk->save();
            } elseif ($reward->reward_type === 'Silk') {
                $user->skSilk->silk_gift += $reward->reward_count;
                $user->skSilk->save();
            }
            //send notice
            _AutoNotice::sendnotice([
                'NoticeType' => 4,
                'Message' => 'Congratulations! You have received a quest reward: ' . $reward->reward_count . 'x [' . $reward->reward_name . ']',
                'CHARNAME16' => $charname,
            ]);
        } elseif ($reward->reward_type === 'item') {
            if ($reward->reward_codename == 'Package' && $reward->package_id > 0) {
                //Get Record package from TasksRewardsPackage by package_id
                $items = TasksRewardsPackage::where('package_id', $reward->package_id)->get();
                foreach ($items as $item) {
                    //createDelivery
                    _InstantItemDelivery_3s::createDelivery([
                        'CharID' => $ownchar,
                        'StorageType' => 0,
                        'CodeName' => $item->reward_codename,
                        'Count' => $item->reward_count,
                        'Plus' => 0,
                        'message_type' => 0,
                        'message' => null,
                    ]);
                }
                //send notice
                _AutoNotice::sendnotice([
                    'NoticeType' => 4,
                    'Message' => 'Congratulations! You have received a quest reward package ' . $reward->reward_count . 'x [' . $reward->reward_name . ']',
                    'CHARNAME16' => $charname,
                ]);

            } elseif ($reward->reward_codename == 'Random' && $reward->random_id > 0) {
                //Get Random Item from TasksRewardsRandom by random_id
                $item = TasksRewardsRandom::where('random_id', $reward->random_id)->inRandomOrder()->first();
                if ($item) {
                    //createDelivery
                    _InstantItemDelivery_3s::createDelivery([
                        'CharID' => $ownchar,
                        'StorageType' => 0,
                        'CodeName' => $item->reward_codename,
                        'Count' => $item->reward_count,
                        'Plus' => 0,
                        'message_type' => 4,
                        'message' => 'Congratulations! You have received a quest reward: ' . $item->reward_count . 'x [' . $item->reward_name . ']',
                    ]);
                }

            } elseif ($reward->reward_codename) {
                //createDelivery
                _InstantItemDelivery_3s::createDelivery([
                    'CharID' => $ownchar,
                    'StorageType' => 0, 
                    'CodeName' => $reward->reward_codename,
                    'Count' => $reward->reward_count,
                    'Plus' => 0,
                    'message_type' => 4,
                    'message' => 'Congratulations! You have received a quest reward: ' . $reward->reward_count . 'x [' . $reward->reward_name . ']',
                ]);

            } else {
                return false; // Invalid item reward
            }
        } else {
            return false; // Unknown reward type
        }

        return true; // Indicate success
    }
}
