<?php

namespace App\Models\Wheel;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class SpinDraw extends Model
{
    use HasFactory;
    protected $table = 'spin_draw';

    protected $fillable = [
        'id',
        'voucher_id',
        'prize_id',
        'type',
        'status',
        'rotation',
        'expired_date',
    ];

    public function getIncrementing()
    {
        return false;
    }

    /**
     * Get the auto-incrementing key type.
     *
     * @return string
     */
    public function getKeyType()
    {
        return 'string';
    }

    public static function listData(){
        $data = SpinDraw::leftJoin('spin_voucher','spin_draw.voucher_id','=','spin_voucher.id')
                ->leftJoin('spin_prize','spin_draw.prize_id','=','spin_prize.id')
                ->leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                ->select('spin_draw.*','spin_voucher.voucher','spin_prize.label as prize','spin_member.username as member','spin_prize.status as prize_status')
                ->orderBy('spin_draw.created_at','desc')
                ->get();

        return $data;
    }

    public static function insertData($request){

        if(is_null($request->expired_date)){
            $expired = date('Y-m-d');
        }else{
            $expired = $request->expired_date;
        }
        
        $data = SpinDraw::create([
            'id'            => (string) Str::uuid(),
            'voucher_id'    => $request->voucher_id,
            'prize_id'      => $request->prize_id,
            'status'        => 'not used',
            'rotation'      => 10,
            'type'          => $request->type,
            'expired_date'  => $expired,
        ]);

        return $data;
    }

    public static function updateData($request){
        $data = SpinDraw::where('id',$request->id)->update([
            'voucher_id'    => $request->voucher_id,
            'prize_id'      => $request->prize_id,
            'status'        => $request->status,
            'type'          => $request->type,
            'rotation'      => 10,
            'expired_date'  => $request->expired_date,
        ]);

        return $data;
    }

    public static function detailData($id){
        $data = SpinDraw::leftJoin('spin_voucher','spin_draw.voucher_id','=','spin_voucher.id')
                ->leftJoin('spin_prize','spin_draw.prize_id','=','spin_prize.id')
                ->leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                ->where('spin_draw.id',$id)
                ->select('spin_draw.*','spin_voucher.voucher','spin_prize.label as prize','spin_member.username as member','spin_prize.status as prize_status')
                ->first();

        return $data;
    }
}
