<?php

namespace App\Http\Controllers;

use Session;
use App\Menu;
use App\Toko;
use Illuminate\Http\Request;
use Yajra\Datatables\Html\Builder;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\File;
use App\Http\Requests\StoreMenuRequest;
use App\Http\Requests\UpdateMenuRequest;
use Illuminate\Database\Eloquent\ModelNotFoundExecption;
use App\BeliLog;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\MenuException;


class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
     public function index(Request $request,Builder $htmlBuilder)
     {
       if ($request->ajax()) {
        $menus = Menu::with('tokos')->selectRaw('menus.*');
        return Datatables::of($menus)
            ->addColumn('action', function($menu){
                return view('datatable._action', [
                    'model'           => $menu,
                    'form_url'        => route('menu.destroy', $menu->id),
                    'edit_url'        => route('menu.edit', $menu->id),
                    'confirm_message' => 'Yakin mau menghapus ' . $menu->title . '?'
                ]);
            })->make(true);
    }

    $html = $htmlBuilder
    ->addColumn(['data' => 'toko_id', 'name'=>'toko_id', 'title'=>'ID Toko'])
        ->addColumn(['data' => 'title', 'name'=>'title', 'title'=>'Menu'])
        ->addColumn(['data' => 'amount', 'name'=>'amount', 'title'=>'Jumlah'])
        ->addColumn(['data' => 'price', 'name'=>'price', 'title'=>'Harga'])
        ->addColumn(['data' => 'action', 'name'=>'action', 'title'=>'', 'orderable'=>false, 'searchable'=>false]);

    return view('menu.index')->with(compact('html'));
     }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('menu.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreMenuRequest $request)
    {

        $menu  = Menu::create($request->except('description'));

        if($request->hasFile('description')){
          $uploaded_description = $request->file('description');
          $extension  = $uploaded_description->getClientOriginalExtension();
          $filename = md5(time()).'.'.$extension;
          $destinationPath  = public_path().DIRECTORY_SEPARATOR.'img';
          $uploaded_description->move($destinationPath,$filename);

          $menu->description=$filename;
          $menu->save();
        }

        Session::flash("flash_notification",[
          "level"=>"success",
          "message"=>"Berhasil menambah $menu->title"
        ]);

        return redirect()->route('menu.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
      $menu = Menu::find($id);
      return view('menu.edit')->with(compact('menu'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateMenuRequest $request, $id)
    {

      $menu  = Menu::find($id);
      $menu->update($request->all());

      if($request->hasFile('description')){
        $filename = null;
        $uploaded_description = $request->file('description');
        $extension  = $uploaded_description->getClientOriginalExtension();
        $filename = md5(time()).'.'.$extension;
        $destinationPath  = public_path().DIRECTORY_SEPARATOR.'img';
        $uploaded_description->move($destinationPath,$filename);

        if($menu->description){
          $old_cover = $menu->description;
          $filepath = public_path().DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.$menu->description;

        try{
          File::delete($filepath);
        }catch(FileNotFoundException  $e){

        }
      }

        $menu->description=$filename;
        $menu->save();
      }

      Session::flash("flash_notification",[
        "level"=>"success",
        "message"=>"Berhasil menambah $menu->title"
      ]);

      return redirect()->route('menu.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
          $menu = Menu::find($id);

          if($menu->description){
            $old_cover = $menu->description;
            $filepath = public_path().DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.$menu->description;

          try{
            File::delete($filepath);
          }catch(FileNotFoundException  $e){

          }
        }

        $menu->delete();

        Session::flash("flash_notification",[
          "level"=>"success",
          "message"=>"Berhasil menghapus $menu->title"
        ]);
        return redirect()->route('menu.index');
    }

    public function beli($id)
      {
        try {
              $menu = Menu::findOrFail($id);
              Auth::user()->beli($menu);
              Session::flash("flash_notification", [
                "level"=>"success",
                "message"=>"Berhasil memesan menu $menu->title"
              ]);
            } catch(MenuException $e){
              Session::flash("flash_notification",[
                "level" =>"danger",
                "message"=>$e->getMessage()
              ]);
            }catch (ModelNotFoundException $e) {
              Session::flash("flash_notification", [
                "level"=>"danger",
                "message"=>"Makanan tidak ditemukan."
              ]);
            }
            return redirect('/');
          }

    public function diBatalkan($menu_id)
          {
          $beliLog = BeliLog::where('user_id', Auth::user()->id)
          ->where('menu_id', $menu_id)
          ->where('dibatalkan', 0)
          ->first();
          if ($beliLog) {
          $beliLog->dibatalkan = true;
          $beliLog->save();
          Session::flash("flash_notification", [
          "level" => "success",
          "message" => "Berhasil membatalkan " . $beliLog->menu->title
          ]);
          }
          return redirect('/home');
        }

}
