<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Voucher;
use DataTables;
use App\Models\Branch;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;

class VoucherController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->param['pageTitle'] = 'List Voucher';
        $this->param['btnText'] = 'Tambah';
        $this->param['btnLink'] = route('voucher.create');
        
        if ($request->ajax()) {
            $data = Voucher::select("voucher.*","branch.cabang","nama")->leftJoin('customer','customer.id','voucher.id_customer')->leftJoin('branch','voucher.id_branch','branch.id')->where('type','payment')->orderBy('voucher.id','desc')->get();
            return Datatables::of($data)->addIndexColumn()
                ->addColumn('branch_name',function($row){
                    return $row->id_branch != '0' ? $row->cabang : 'Semua Cabang'; 
                })
                ->addColumn('action', function ($row) {
                    $cekTransaction = \DB::table('transaction')->where('voucher_code',$row->voucher_code)->count();
                    $btn = '<div class="form-inline btn-action">
                    <a href="voucher/' . $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>';
                    if($cekTransaction==0){
                        $btn.='<form action="' . route('voucher.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('voucher.index', $this->param);
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $this->param['pageTitle'] = 'Tambah Voucher';
        $this->param['btnText'] = 'List Voucher';
        $this->param['btnLink'] = route('voucher.index');
        // $this->param['member'] = Customer::orderBy('id','desc')->limit(10)->get();
        $this->param['branch'] = Branch::orderBy('cabang','asc')->get();
        if($request->member){
            $voucher = \DB::table('voucher')->where('id_customer',$request->member)->where('type','payment')->sum('price_item');
            $this->param['data'] = \DB::select("SELECT phone,nama, poin - $voucher poin from customer WHERE id='".$request->member."'");
            
        }
        return view('voucher.create-payment', $this->param);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storeItem(Request $request)
    {
        $validate = [
            'item_code'   => 'required',
            'item_name'   => 'required',
            'price_item'   => 'required',
        ];
        $request->validate($validate);
        
        try {
            $voucher = new Voucher;
            $voucher->id_branch = $request->id_branch;
            // $voucher->voucher_code = $code;
            $voucher->item_code = $request->item_code;
            $voucher->item_name = $request->item_name;
            $voucher->price_item = $request->price_item;
            $voucher->save();

            $code = "V".sprintf("%05s", $voucher->id);;
            $v = Voucher::find($voucher->id);
            $v->voucher_code = $code;
            $v->save();

        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('voucher.index')->withStatus('Data berhasil disimpan');

    }
    public function store(Request $request)
    {
        $voucherMember = \DB::table('voucher')->where('id_customer',$request->id_customer)->where('type','payment')->sum('price_item');
        
        $maxPoint = $request->poin;
        $validate = [
            'id_customer'   => 'required',
            'price_item'   => 'required|numeric|max:'.$maxPoint,
        ];
        $request->validate($validate);
        
        try {
            $voucher = new Voucher;
            // $voucher->voucher_code = $code;
            $voucher->id_branch = $request->id_branch;
            $voucher->id_customer = $request->id_customer;
            $voucher->item_name = $request->item_name;
            $voucher->price_item = $request->price_item;
            $voucher->type = 'payment';
            $voucher->save();
            
            $code = "V".sprintf("%05s", $voucher->id);;
            $v = Voucher::find($voucher->id);
            $v->voucher_code = $code;
            $v->save();


        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('voucher.index')->withStatus('Data berhasil disimpan');

    }

    /**
     * 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)
    {
        $this->param['pageTitle'] = 'Edit Voucher';
        $this->param['btnText'] = 'List Voucher';
        $this->param['btnLink'] = route('voucher.index');
        $this->param['voucher'] = Voucher::select('voucher.*','customer.poin','customer.nama','customer.phone')->join('customer','voucher.id_customer','customer.id')->where('voucher.id',$id)->firstOrFail($id);
        $this->param['getVoucher'] = \DB::table('voucher')->where('id_customer',$this->param['voucher']->id_customer)->where('type','payment')->sum('price_item');
        
        $this->param['branch'] = Branch::orderBy('cabang','asc')->get();
        // $this->param['member'] = Customer::orderBy('id','desc')->limit(10)->get();

        return view('voucher.edit-payment', $this->param);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $voucher = Voucher::findOrFail($id);
        
        $voucherMember = \DB::table('voucher')->where('id_customer',$request->id_customer)->where('type','payment')->sum('price_item');
        
        // $maxPoint = $request->poin - $voucherMember + $voucher->price_item;
        $maxPoint = $request->poin;        
        
        $validate = [
            'id_customer'   => 'required',
            'price_item'   => 'required|numeric|max:'.$request->poin,
        ];
        $request->validate($validate);
        
        try {
            $voucher->id_branch = $request->id_branch;
            $voucher->id_customer = $request->id_customer;
            $voucher->item_name = $request->item_name;
            $voucher->price_item = $request->price_item;
            $voucher->save();


        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('voucher.index')->withStatus('Data berhasil diperbarui');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            Voucher::findOrFail($id)->delete();
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('voucher.index')->withStatus('Data berhasil dihapus');
    }

    public function settings()
    {
        if(Auth::user()->level == 0){
            $this->param['pageTitle'] = 'Settings';
            $this->param['btnText'] = 'Settings';
            $this->param['btnLink'] = '';
            $this->param['settings'] = \DB::table('master')->first();
            $this->param['categories'] = \DB::table('member_categories')->get();        
            return view('voucher.persentase', $this->param);
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }

    public function updateSettings(Request $request)
    {
        if(Auth::user()->level == 0){
            try {
                // $percent = $request->percent ? $request->percent : 0;
                $point = $request->point ? $request->point : 0;
                \DB::table('master')->update(['default_point' => $point]);
                $categories = \DB::table('member_categories')->get();
                
                foreach($categories as $i => $item){
                    $percent = $request->get('percent')[$i] ? $request->get('percent')[$i] : 0;
                    \DB::table('member_categories')->where('id',$item->id)->update(['percent' => $percent]);
                }
                
            } catch (Exception $e) {
                return back()->withError('Terjadi kesalahan.');
            } catch (QueryException $e) {
                return back()->withError('Terjadi kesalahan pada database.');
            }
    
            return redirect('settings')->withStatus('Data berhasil diperbarui');
        } else {
             return back()->withError('Akses dilarang!!');
        }
    }
    public function getMember(Request $request){
        try {
            if($request->poin){
                $voucher = \DB::table('voucher')->where('id_customer',$_GET['id'])->where('type','payment')->sum('price_item');
                $getData = \DB::select("SELECT poin - $voucher poin from customer WHERE id='$_GET[id]'");
            }
            else{
                $getData = \DB::select("SELECT id,poin, concat(phone,' ',nama) phoneNama FROM `customer` WHERE concat(phone,' ',nama) LIKE '%$_GET[term]%'");
            }
            echo json_encode($getData);
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }
    }
}
