<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Reward;
use App\Models\Spin;
use App\Models\Ticket;
use App\Models\WebConfiguration;

use Haruncpi\LaravelIdGenerator\IdGenerator;
use DB;
use Gatcha;
use Carbon\Carbon;

class SpinnerController extends Controller
{
    public function index()
    {
        
        $maintenance = WebConfiguration::where(['meta_key' => 'maintenance'])->first();

        if($maintenance->meta_value == "on"){
            return view('pages.spinner.maintenance');
        }

        $history = Spin::join('rewards', 'rewards.idreward', '=', 'spins.idreward')
        ->join('tickets', 'tickets.idticket', '=', 'spins.idtiket')
        ->join('members', 'members.idmember', '=', 'tickets.idmember')
        ->orderByDesc('spins.idspin')
        ->limit(10)
        ->get();
        
        $historyRandom = Spin::join('rewards', 'rewards.idreward', '=', 'spins.idreward')
        ->join('tickets', 'tickets.idticket', '=', 'spins.idtiket')
        ->join('members', 'members.idmember', '=', 'tickets.idmember')
        ->inRandomOrder()
        ->limit(10)
        ->get();

        $reward = Reward::where('public_number', '!=', '')->orderBy('public_number', 'asc')->take(10)->get();
        
        return view('pages.spinner.index', compact('reward', 'history', 'historyRandom'));
    }

    public function spin($username, $code)
    {
        $registered = DB::table('tickets')
        ->where('number_ticket', $code)
        ->where('status', 'used')
        ->first();
        if($registered){
            return response()->json(array(
                'code'      => "error",
                'message'   => "Maaf Kode Tiket Anda Telah Digunakan"
            ));
        }
        $sitelandingusername = WebConfiguration::where(['meta_key' => 'landing-username'])->first();
        if($username == "NotFound" && $sitelandingusername->meta_value == null){
            $result = DB::table('tickets')
            ->join('members', 'tickets.idmember', '=', 'members.idmember')
            ->where('tickets.number_ticket', $code)
            ->first();
        }else{
            $result = DB::table('tickets')
            ->join('members', 'tickets.idmember', '=', 'members.idmember')
            ->where('members.username', $username)
            ->where('tickets.number_ticket', $code)
            ->first();
        }

        $allRewards = Reward::where('public_number', '!=', '')->orderBy('public_number', 'asc')->get();

        $rewards = [];

        $startDay = Carbon::now()->startOfDay();
        $endDay   = $startDay->copy()->endOfDay();
        

        foreach($allRewards as $rw){
            $occurance_type = "";

            if($rw->occurance_type == "Daily"){
                $occurance_type = Spin::where('idreward', $rw->idreward)->whereDate('created_at', '=', date('Y-m-d'))->count();
            }else if($rw->occurance_type == "Weekly"){
                $occurance_type = Spin::where('idreward', $rw->idreward)->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->count();
            }else if($rw->occurance_type == "Monthly"){
                $occurance_type = Spin::where('idreward', $rw->idreward)->whereMonth('created_at', date('m'))->count();
            }

            if($occurance_type < $rw->max_occurance || $rw->max_occurance == 0){
                if($rw->persentase > 0){
                    $rewards[$rw->idreward] = $rw->persentase;
                }
            }
        }
        
        
        if($result){
            if($result->fixed_reward){
                $pick = Reward::where('public_number','=', $result->fixed_reward)->first()->idreward;
            }else{
                if((count($rewards) < 2)){
                    $pick = array_key_first($rewards);
                }else{
                    $pick = Gatcha::put($rewards)->spin();
                }
            }
    
            $numberReward = Reward::where('idreward','=', $pick)->first()->public_number;
    
            $degreeCalculate = Reward::where('public_number', '!=', '')->orderBy('public_number', 'desc')->first();
            
            $degree = (($numberReward - 1) * (360 / $degreeCalculate->public_number)) + random_int(10,((360 / $degreeCalculate->public_number) - 5));
            
            $id = IdGenerator::generate(['table' => 'spins', 'field' => 'idspin', 'length' => 13, 'prefix' => 'SPN' . date('ym')]);
            Spin::create([
                'idspin' => $id,
                'idreward' => $pick,
                'idtiket' => $result->idticket,
            ]);

            Ticket::find($result->idticket)
            ->update([
                'status' => 'used',
                'spin_date' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            return response()->json($degree);
        } else {
            return response()->json(array(
                'code'      => "error",
                'message'   => "Maaf Kode Tiket dan Username Tidak Cocok"
            ));
        }

    }
}