<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\SRO_VT_PROXY\_Players;
use App\Models\SRO_VT_SHARD\Char;
use App\Models\SRO_VT_SHARD\_User;
use App\Models\SRO_VT_ACCOUNT\TbUser;
use Carbon\Carbon;

class FastEventsWelcome extends Model
{
    use HasFactory;

    protected $fillable = [
        'JID',
        'HWID',
        'player_type',
        'CharID',
        'old_character_name',
        'donation_amount',
        'currency',
        'reward_amount',
        'old_character_proofs',
        'donation_proofs',
        'old_character_images',
        'status',
        'rejection_reason',
        'submitted_at',
        'reviewed_at',
        'reviewer_id',
        'claimed_at'
    ];

    protected $casts = [
        'old_character_proofs' => 'array',
        'donation_proofs' => 'array',
        'old_character_images' => 'array',
        'submitted_at' => 'datetime',
        'reviewed_at' => 'datetime',
        'claimed_at' => 'datetime',
        'donation_amount' => 'decimal:2'
    ];

    /**
     * Relationship with character
     */
    public function character()
    {
        return $this->belongsTo(Char::class, 'CharID', 'CharID');
    }

    /**
     * Relationship with user from Account database
     */
    public function user()
    {
        return $this->belongsTo(\App\Models\SRO_VT_ACCOUNT\TbUser::class, 'JID', 'JID');
    }

    /**
     * Check if user exists in welcome event
     */
    public static function existsByHwid($hwid)
    {
        return self::where('hwid', $hwid)->exists();
    }

    /**
     * Get user's welcome event record
     */
    public static function getByHwid($hwid)
    {
        return self::where('hwid', $hwid)->first();
    }

    /**
     * Get available characters for user
     */
    public static function getAvailableCharacters($userJID)
    {
        // Get characters that belong to the user and are online
        $userChars = _User::where('UserJID', $userJID)->get();
        $availableChars = [];

        foreach ($userChars as $userChar) {
            $char = Char::where('CharID', $userChar->CharID)->first();
            if ($char) {
                // Check if user has HWID (is online/has played)
                $hwid = _Players::getSerialByCharID($userChar->CharID);
                if ($hwid) {
                    $availableChars[] = [
                        'CharID' => $char->CharID,
                        'char_name' => $char->CharName16,
                        'avatar' => Char::getCharAvatarGifByCharname($char->CharName16),
                        'hwid' => $hwid
                    ];
                }
            }
        }

        return $availableChars;
    }

    /**
     * Calculate balance based on donation and currency
     */
    public static function calculateBalance($amount, $currency)
    {
        $rate = $currency === 'USD' ? 40 : 1; // 1 USD = 40 balance, 1 EGP = 1 balance
        $totalBalance = $amount * $rate;
        return (int) ($totalBalance * 0.5); // 50% of total
    }

    /**
     * Get reward amount based on player type
     */
    public function getRewardAmount()
    {
        switch ($this->player_type) {
            case 'new':
                return 10;
            case 'old':
                return 40;
            case 'donate':
                return $this->calculated_balance;
            default:
                return 0;
        }
    }

    /**
     * Check if can be claimed
     */
    public function canBeClaimed()
    {
        return $this->status === 'approved' && is_null($this->claimed_at);
    }

    /**
     * Get review deadline (24 hours from submission)
     */
    public function getReviewDeadline()
    {
        return $this->submitted_at ? $this->submitted_at->addHours(24) : null;
    }

    /**
     * Check if is pending and within 24 hours
     */
    public function isPendingWithin24Hours()
    {
        if ($this->status !== 'pending') {
            return false;
        }

        return $this->submitted_at && $this->submitted_at->diffInHours(Carbon::now()) <= 24;
    }

    /**
     * Mark as claimed
     */
    public function markAsClaimed()
    {
        $this->update([
            'claimed_at' => Carbon::now()
        ]);
    }

    /**
     * Approve the request
     */
    public function approve($reviewerId = null)
    {
        $this->update([
            'status' => 'approved',
            'reviewed_at' => Carbon::now(),
            'reviewer_id' => $reviewerId,
            'rejection_reason' => null
        ]);
    }

    /**
     * Reject the request
     */
    public function reject($reason, $reviewerId = null)
    {
        $this->update([
            'status' => 'rejected',
            'reviewed_at' => Carbon::now(),
            'reviewer_id' => $reviewerId,
            'rejection_reason' => $reason
        ]);
    }

    // update all Hwid rows in FastEventsWWelcome
    public static function updateAllHwid()
    {
        $characters = Self::get();
        foreach ($characters as $char) {
            $hwid = _Players::getSerialByCharID($char->CharID);
            if ($hwid) {
                self::updateOrCreate(
                    ['CharID' => $char->CharID],
                    ['hwid' => $hwid]
                );
            }
        }
    }

    //Get Exists Chars Info By Hwid();
    public static function getExistsCharsInfoByHwid($hwid)
    {
        $charInfo = self::where('hwid', $hwid)->first();
        if ($charInfo) {
            return [
                'CharID' => $charInfo->CharID,
                'char_name' => Char::where('CharID', $charInfo->CharID)->value('CharName16'),
                'avatar' => Char::getCharAvatarGifByCharname(Char::where('CharID', $charInfo->CharID)->value('CharName16')),
                'hwid' => $charInfo->hwid
            ];
        }
        return null;
    }

}
