<?php

namespace App\Http\Controllers;

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

class CashierController 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 User';
            $this->param['btnText'] = 'Tambah';
            $this->param['btnLink'] = route('cashier.create');
    
            if ($request->ajax()) {
                $data = User::select('users.id', 'users.email', 'branch.cabang','users.name', \DB::raw('CASE WHEN users.level = "0" THEN "Admin" ELSE "Kasir" END AS level'))
                    ->leftJoin('branch', 'branch.id', 'users.id_branch')
                    // ->where('level', '1')
                    ->get();
                return Datatables::of($data)->addIndexColumn()
                    ->addColumn('action', function ($row) {
    
                        $btn = '<div class="form-inline btn-action">
                        <a href="cashier/' . $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('cashier.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('cashier.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 Kasir';
            $this->param['btnText'] = 'List Kasir';
            $this->param['btnLink'] = route('cashier.index');
            $this->param['branch'] = Branch::get();
    
            return \view('cashier.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(CashierRequest $request)
    {
        if(Auth::user()->level == 0){
            $validated = $request->validated();
            try {
                $cashier = new User;
                $cashier->name = $validated['name'];
                $cashier->email = $validated['email'];
                $cashier->password = Hash::make('beatyesterday');
                $cashier->level = $validated['level'];
                $cashier->id_branch = $request->branch;
                $cashier->save();
            } catch (Exception $e) {
                return back()->withError('Terjadi kesalahan.' . $e);
            } catch (QueryException $e) {
                return back()->withError('Terjadi kesalahan pada database.');
            }
    
            return redirect()->route('cashier.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 Kasir';
            $this->param['data'] = User::find($id);
            $this->param['branch'] = Branch::get();
            $this->param['btnText'] = 'List Kasir';
            $this->param['btnLink'] = route('branch.index');
    
            return view('cashier.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(CashierRequest $request, $id)
    {
        if(Auth::user()->level == 0){
            $data = User::findOrFail($id);
    
            $validated = $request->validated();
    
            try {
                $data->name = $validated['name'];
                $data->email = $validated['email'];
                $data->id_branch = $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('cashier.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 = User::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('cashier.index')->withStatus('Data berhasil dihapus.');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    public function changePassword()
    {
        if(Auth::user()->level == 0){
            $this->param['pageTitle'] = 'Edit Password';
            $this->param['user'] = User::find(auth()->user()->id);
            return view('user.change-password', $this->param);
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    public function updatePassword(Request $request, $id)
    {
        if(Auth::user()->level == 0){
            $user = User::findOrFail($id);;
            $old = $request->old_pass;
            $new = $request->password;
    
            if (!Hash::check($old, $user->password))
                return back()->withError('Password lama tidak cocok.');
    
            if (Hash::check($new, $user->password))
                return back()->withError('Password baru tidak boleh sama dengan password lama.');
    
            $validatedData = $request->validate(
                [
                    'old_pass' => 'required',
                    'password' => 'required',
                    'confirmation' => 'required|same:password'
                ],
                [
                    'required' => ':attribute harus diisi.',
                    'password.unique' => 'Password baru tidak boleh sama dengan password lama.',
                    'same' => 'Konfirmasi password harus sesuai.'
                ],
                [
                    'old_pass' => 'Password lama',
                    'password' => 'Password baru',
                    'confirmation' => 'Konfirmasi password baru',
                ]
            );
    
            try {
                $user->password = Hash::make($request->get('password'));
                $user->save();
            } catch (\Exception $e) {
                return redirect()->back()->withError('Terjadi kesalahan.');
            } catch (\Illuminate\Database\QueryException $e) {
                return redirect()->back()->withError('Terjadi kesalahan.');
            }
    
            return back()->withStatus('Password berhasil diperbarui.');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }
}
