<?php

namespace App\Http\Controllers;

use App\Http\Requests\BranchRequest;
use App\Models\Branch;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Auth;
use DataTables;

class BranchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if(Auth::user()->level == 0){
            $this->param['pageTitle'] = 'List Cabang';
            $this->param['btnText'] = 'Tambah';
            $this->param['btnLink'] = route('branch.create');
    
            if ($request->ajax()) {
                $data = Branch::get();
                return Datatables::of($data)->addIndexColumn()
                    ->addColumn('action', function ($row) {
    
                        $btn = '<div class="form-inline btn-action">
                        <a href="branch/' . $row->id . '/edit" class="mr-2">
                                    <button type="button" id="PopoverCustomT-1" class="btn btn-rgb-primary btn-sm"
                                        data-toggle="tooltip" title="Edit" data-placement="top"><span
                                            class="fa fa-edit fa-sm"></span></button>
                                </a>
                                <form action="' . route('branch.destroy', $row->id) . '" method="post">
                                    ' . csrf_field() . '
                                    ' . method_field("DELETE") . '
                                    <button type="submit" class="btn btn-rgb-danger btn-sm" data-toggle="tooltip"
                                        title="Hapus" data-placement="top"
                                        onclick="return confirm(\'Apakah anda yakin ingin menghapus ?\')">
                                        <span class="fa fa-trash fa-sm"></span>
                                    </button>
                                </form>
                                </div>';
                        return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
            }
    
            return \view('branch.index', $this->param);
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if(Auth::user()->level == 0){
            $this->param['pageTitle'] = 'Tambah Cabang';
            $this->param['btnText'] = 'List Cabang';
            $this->param['btnLink'] = route('branch.index');
    
            return \view('branch.create', $this->param);
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BranchRequest $request)
    {
        if(Auth::user()->level == 0){
            $validated = $request->validated();
            try {
                $branch = new Branch;
                $branch->code = $validated['code'];
                $branch->cabang = $validated['branch'];
                $branch->save();
            } catch (Exception $e) {
                return back()->withError('Terjadi kesalahan.'.$e);
            } catch (QueryException $e) {
                return back()->withError('Terjadi kesalahan pada database.');
            }
    
            return redirect()->route('branch.index')->withStatus('Data berhasil disimpan.');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * 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)
    {
        if(Auth::user()->level == 0){
            $this->param['pageTitle'] = 'Edit Cabang';
            $this->param['data'] = Branch::find($id);
            $this->param['btnText'] = 'List Cabang';
            $this->param['btnLink'] = route('branch.index');
    
            return view('branch.edit', $this->param);
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if(Auth::user()->level == 0){
            $data = Branch::findOrFail($id);
    
            $request->validate([
                'code' => 'required|unique:branch,code,'.$id,
                'branch' => 'required',
            ]);
    
            try {
                $data->code = $request->code;
                $data->cabang = $request->branch;
    
                $data->save();
            } catch (\Exception $e) {
                return redirect()->back()->withError('Terjadi kesalahan.');
            } catch (\Illuminate\Database\QueryException $e) {
                return redirect()->back()->withError('Terjadi kesalahan pada database.');
            }
    
            return redirect()->route('branch.index')->withStatus('Data berhasil diperbarui.');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Auth::user()->level == 0){
            try {
                $data = Branch::findOrFail($id);
                $data->delete();
            } catch (Exception $e) {
                return back()->withError('Terjadi kesalahan.');
            } catch (QueryException $e) {
                return back()->withError('Terjadi kesalahan pada database.');
            }
    
            return redirect()->route('branch.index')->withStatus('Data berhasil dihapus.');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }
}
