<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PrizeDistribution extends Model
{
    use HasFactory;

    protected $table = 'prize_distribution';

    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'prize_id',
        'player_id',
        'selected_day',
        'created_at'
    ];

    function prize()
    {
        return $this->belongsTo(Prize::class);
    }

    public static function findTotalPrizeDistributedPerDay($prize_id, $selected_day)
    {
        //return total count of prize distributed
        return PrizeDistribution::where('prize_id', $prize_id)
            ->where('selected_day', $selected_day)->count();
    }

    public static function findTotalPrizeDistributedThisHourAndDay($prize_id, $selected_day)
    {
        $current_hour = Carbon::now()->hour;
        // if (Carbon::now()->minute < 30)
        //     $current_hour--;

        $startTime = Carbon::create(null, null, null, $current_hour, 0, 0);
        $endTime = Carbon::create(null, null, null, $current_hour, 0, 0)->addHour(1);

        //return total count of prize distributed
        return PrizeDistribution::where('prize_id', $prize_id)->where('selected_day', $selected_day)->whereBetween('created_at', [$startTime, $endTime])->count();

        // Safer way to create Carbon instances
        //$startTime = Carbon::now()->setHour($current_hour)->setMinute(0)->setSecond(0);
        //$endTime = $startTime->copy()->addHour();
        //return PrizeDistribution::where('prize_id', $prize_id)->where('selected_day', $selected_day)->count();
    }

    public static function findPrizeLastDistributed($prize_id)
    {
        //return total count of prize distributed
        return PrizeDistribution::where('prize_id', $prize_id)
            ->orderBy('created_at', 'DESC')->first();
    }
}