<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CouponController extends Controller
{
    public function index(Request $request, $id = '')
    {
        if ($id > 0) {
            $arr = Coupon::where(['id' => $id])->get();

            $result['title'] = $arr['0']->title;
            $result['code'] = $arr['0']->code;
            $result['value'] = $arr['0']->value;
            $result['id']=$arr['0']->id;
        } else {
            $result['title'] = '';
            $result['code'] = '';
            $result['value'] = '';
            $result['id']=0;
        }
        $Coupons = Coupon::all();
        return view('admin/Coupon', compact('Coupons'),$result);
    }

    public function create(Request $request)
    {
        $validatedData = $request->validate([
            "title" => 'required',
            "value" => 'required',
            "code" => 'required|unique:coupons,code,'.$request->input('id'),

        ]);
        if($request->input('id')>0){
            $Coupons=Coupon::find($request->input('id'));
            $msg="Coupon updated";
        }else{
            $Coupons = new Coupon;
            $msg="Coupon inserted";
        }
        $Coupons->title = $request->input('title');
        $Coupons->code = $request->input('code');
        $Coupons->value = $request->input('value');
        $Coupons->status=1;
        $Coupons->save();
        Session::flash('message', $msg);
        return redirect('admin/coupon');
    }


    public function store(Request $request)
    {
    }

    public function show(Coupon $Coupon)
    {
    }

    public function edit(Coupon $Coupon)
    {
    }

    public function status(Request $request,$status,$id){
        $model=Coupon::find($id);
        $model->status=$status;
        $model->save();
        Session::flash('message','Coupon status updated');
        return redirect('admin/coupon');
    }

    public function delete(Request $request, $id)
    {
        $model = Coupon::find($id);
        $model->delete();
        Session::flash('message', 'Coupon deleted');
        return redirect('admin/coupon');
    }
}
