<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\CheckIn;
use App\Models\Prize;
use App\Models\Recipients;
use App\Models\Activity;

class DrawController extends Controller
{
    public function draw_user_by_region(Request $request)
    {
        return CheckIn::where('is_checked_in', 'true')
            ->whereTime('check_ins.updated_at', '<=', $request->deadline)
            ->whereIn('region', $request->region)
            ->get()
            ->random($request->number);
    }

    public function draw(Request $request)
    {
        $prize = Prize::where('id', $request->prize_id)->first();
        $activity = Activity::where('id', $request->activity_id)->first();
        $users = CheckIn::where('activity_id', $request->activity_id)
            ->where('is_checked_in', 'true')
            ->where('is_awarded', 'false')
            ->whereTime('check_ins.updated_at', '<=', $activity->deadline)
            ->whereIn('region', $request->region)
            ->inRandomOrder()
            ->get();
        if ($prize->count >= $request->number && count($users) >= $request->number) {
            $output = [];
            $draw_user = $users->random($request->number);
            foreach ($draw_user as $user) {
                array_push($output, [
                    'user_id' => $user->user_id,
                    'user_name' => $user->name,
                    'department_id' => $user->department_id,
                ]);
            }
            return $output;
        }
        return false;
    }

    public function store(Request $request)
    {
        $prize = Prize::where('id', $request->prize_id)->first();
        if ($prize->count >= $request->number) {
            $prize->update([
                'count' => $prize->count - $request->number,
                'updated_at' => now(),
            ]);

            CheckIn::whereIn('user_id', $request->users)->update(['is_awarded' => true]);
            $recipientsData = [];
            foreach ($request->users as $user_id) {
                array_push($recipientsData, [
                    'prize_id' => $request->prize_id,
                    'user_id' => $user_id,
                    'is_claimed' => false,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
            Recipients::insert($recipientsData);
            return true;
        }
        return false;
    }

    public function donate(Request $request)
    {
        CheckIn::whereIn('user_id', $request->users)->update(['is_awarded' => true]);
        return 'success';
    }

    public function test(Request $request)
    {
        return 'success';
    }
}
