<?php

namespace App\Models\Wheel;

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

class SpinVoucher extends Model
{
    use HasFactory;
    protected $table = 'spin_voucher';

    protected $fillable = [
        'id',
        'member_id',
        'voucher',
        'status',
    ];

    public function getIncrementing()
    {
        return false;
    }

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

    public static function listData(){
        $data = SpinVoucher::leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                ->select('spin_voucher.*','spin_member.username as member')
                ->orderBy('spin_voucher.created_at','desc')
                ->get();

        return $data;
    }

    public static function listDataNotUsed(){
        $data = SpinVoucher::leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                    ->select('spin_voucher.*','spin_member.username as member')
                    ->where('spin_voucher.status','not used')
                    ->orderBy('spin_voucher.created_at','desc')->get();

        return $data;
    }

    public static function insertData($request){
        $data = SpinVoucher::create([
            'id' => (string) Str::uuid(),
            'member_id' => $request->member_id,
            'voucher' => Str::random(6),
            'status' => 'not used',
        ]);

        return $data;
    }

    public static function updateData($request){
        $data = SpinVoucher::where('id',$request->id)->update([
            'member_id' => $request->member_id,
            'voucher' => $request->voucher,
            'status' => $request->status,
        ]);

        return $data;
    }

    public static function detailData($id){
        $data = SpinVoucher::leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                ->where('spin_voucher.id',$id)
                ->select('spin_voucher.*','spin_member.username as member')
                ->first();

        return $data;
    }

    public static function confirmData($member_id){
        $data = SpinVoucher::leftJoin('spin_member','spin_voucher.member_id','=','spin_member.id')
                ->where('spin_voucher.member_id',$member_id)
                ->whereDate('spin_voucher.created_at',date('Y-m-d'))
                ->select('spin_voucher.*','spin_member.username as member')
                ->first();

        return $data;
    }
}
