<?php

namespace App\Http\Controllers\front;

use App\Http\Controllers\Controller;
use App\Models\Promocode;
use Auth;
use Exception;
use Illuminate\Http\Request;

class PromoCodeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {

        $user_id = Auth::guard('member')->user()->id;
        $count   = Promocode::where('used_count', $user_id)->count();
        $give_to = $request->input('give_to');
        $from    = $request->input('from');
        $row     = Promocode::where('used_count', 0)
            ->where('from', $from)
            ->first();



        if (!$row) {
            return response()->json(['status' => 'error', 'msg' => '目前無可用的優惠碼']);
        }

        $row->used_count = $user_id;
        $row->give_to    = $give_to;
        $row->save();
        return response()->json(['status' => 'success', 'msg' => '已成功取得', 'promocode' => $row->code, 'give_to' => $row->give_to]);
    }
    /**
     * Summary of morePromocode
     * @throws \Exception
     * @return mixed|\Illuminate\Http\JsonResponse
     */
    public function morePromocode()
    {
        $user = Auth::guard('member')->user();
        try {
            if ($user->level != 9) {
                throw new Exception("Error Processing Request", 401);
            } else {
                $row             = Promocode::where('used_count', 0)->first();
                $row->used_count = $user->id;
                $row->save();
                return response()->json(['status' => 'success', 'msg' => '已成功取得', 'promocode' => $row->code]);
            }
        } catch (Exception $th) {
            //throw $th;
            return response()->json(['status' => 'error', 'msg' => $th->getMessage(), 'code' => $th->getCode()]);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {

        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Promocode $promocode)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Promocode $promocode)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Promocode $promocode)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Promocode $promocode)
    {
        //
    }
}
