<?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)
    {
        $activity = Activity::where('id', $request->activity_id)->first();
        $users = CheckIn::where('check_ins.activity_id', $request->activity_id)
            ->where('is_checked_in', 'true')
            ->whereTime('check_ins.updated_at', '<=', $activity->deadline)
            ->whereIn('region', $request->region)
            ->inRandomOrder()
            ->get()
            ->random($request->number);

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

            $data = [];
            $output = [];
            foreach ($users as $user) {
                array_push($data, [
                    'prize_id' => $request->prize_id,
                    'user_id' => $user->user_id,
                    'is_claimed' => false,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                array_push($output, [
                    'user_id' => $user->user_id,
                    'user_name' => $user->name,
                    'department_id' => $user->department_id,
                ]);
            }

            Recipients::insert($data);
            return $output;
        }
        return false;
    }
}
