<?php

namespace App\Models\Z_Website\Quests;

use App\Models\Z_Website\User;
use Illuminate\Database\Eloquent\Model;
use App\Models\SRO_VT_SHARD\CharQuest;
use Illuminate\Support\Facades\Auth;

class TaskUserDailyTask extends Model
{
    protected $table = 'tasks_user_daily_tasks';

    protected $primaryKey = 'id';

    protected $fillable = [
        'user_id',
        'task_id',
        'is_completed',
        'created_at',
    ];
    protected $casts = [
        'is_completed' => 'boolean',
        'created_at' => 'datetime',
    ];
    public function task()
    {
        return $this->belongsTo(TaskDailyTask::class, 'task_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    //check if user have a task return full task info
    public static function usertask($userId)
    {
        return self::where('user_id', $userId)->with('task')->first();
    }

    //Clean task_user_daily_tasks and CharQuest Any Quest not in Current Quest By QuestID And CharID
    public static function cleanOldTasksAndQuests($userId = null, $currentTaskID = null)
    {
    if (!$userId) {
        $userId = Auth::id();
    }
    if (!$currentTaskID) {
        $currentTaskID = self::where('user_id', $userId)->value('task_id');
    }
    if (!$currentTaskID) {
        $currentTaskID = 0;
    }

    $systemQuests = TaskDailyTask::where('QuestID', '!=', 0)->pluck('QuestID')->toArray();
    if (empty($systemQuests)) {
        return; // No system quests to compare against
    }
    $CharID = TaskUserVipStatus::where('user_id', $userId)->value('CharID');
    if (!$CharID) {
        return; // No CharID found for the user
    }

    //Get current task
    $currentQuestId = TaskDailyTask::where('id', $currentTaskID)->value('QuestID');

        // Delete old tasks from tasks_user_daily_tasks by userId and not in currentTaskID
        self::where('user_id', $userId)
            ->where('task_id', '!=', $currentTaskID)
            ->delete();

        // Delete old quests from CharQuest
        CharQuest::where('CharID', $CharID)
            ->where('QuestID', '!=', $currentQuestId)
            ->whereIn('QuestID', $systemQuests)
            ->delete();

    }

}
