<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Dealer;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportDMS;
use Auth, DB, Mail, Validator, File, DataTables, Exception;

class DealerController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:dealer_create', ['only' => ['create']]);
            $this->middleware('permission:dealer_edit', ['only' => ['edit']]);
            $this->middleware('permission:dealer_view', ['only' => ['view']]);
            $this->middleware('permission:dealer_delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
    
    public function index(Request $request){
            if($request->ajax()){
                $data = Dealer::orderBy('id' ,'desc')->where('status','pending');
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';
                            if(auth()->user()->can('dms-view')){
                                $return .= '<a href="'.route('dealer.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-eye"></i>
                                            </a> &nbsp;';
                            }   
                            
                            if(auth()->user()->can('dms-edit')){
                                $return .= '<a href="'.route('dealer.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-pencil"></i>
                                            </a> &nbsp;';
                            }   

                            if (auth()->user()->can('dms-delete')) {
                                $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">
                                                    
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                                </ul>';
                            }

                            $return .= '</div>';

                            return $return;
                        })
                        ->rawColumns([ 'action' ])
                        ->filter(function ($query){
                            if (request()->get('dealer_name',false)) {
                                $query->where('dealer_management.dealer_name', "like", "%".request()->get("dealer_name")."%");
                            }
                            if (request()->get('dealer_email',false)) {
                                $query->where('dealer_management.dealer_email', "like", "%".request()->get("dealer_email")."%");
                            }
                            if (request()->get('dealer_mobile_no',false)) {
                                $query->where('dealer_management.dealer_mobile_no', "like", "%".request()->get("dealer_mobile_no")."%");
                            }
                            if (request()->get('dealer_address',false)) {
                                $query->where('dealer_management.dealer_address', "like", "%".request()->get("dealer_address")."%");
                            }
                            if (request()->get('state',false)) {
                                $query->where('dealer_management.state', "like", "%".request()->get("state")."%");
                            }
                            if (request()->get('city',false)) {
                                $query->where('dealer_management.city', "like", "%".request()->get("city")."%");
                            }
                            if (request()->get('gst',false)) {
                                $query->where('dealer_management.gst', "like", "%".request()->get("gst")."%");
                            }
                            if (request()->get('gst_no',false)) {
                                $query->where('dealer_management.gst_no', "like", "%".request()->get("gst_no")."%");
                            }
                            if (request()->get('remark',false)) {
                                $query->where('dealer_management.remark', "like", "%".request()->get("remark")."%");
                            }
                        })    
                        ->make(true);
            }
            return view('dealer.index');
        }
        
        /** create */
            public function create(Request $request){
                $state_name = DB::table('common_state')->get();
                view()->share('states',$state_name);
                return view('dealer.create');
            }
        /** create */
        
        /** insert */
        public function insert(Request $request){
            if($request->ajax()){
                return true;
            }
            $crud = [
                'dealer_name' => ucfirst($request->dealer_name),
                'dealer_email' => $request->dealer_email,
                'dealer_mobile_no' => $request->dealer_mobile_no,
                'dealer_address' => $request->dealer_address,
                'state' => $request->state,
                'city' => $request->city,
                'gst' => $request->gst,
                'gst_no' => $request->gst_no,
                'remark' => $request->remark,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            DB::beginTransaction();
            try {
                DB::enableQueryLog();
                $last_id = Dealer::insertGetId($crud);
                if ($last_id) {
                    
                    DB::commit();
                    return redirect()->route('dealer')->with('success', 'Record inserted successfully');
                } else {
                    DB::rollback();
                    return redirect()->back()->with('error', 'Failed to insert record')->withInput();
                }
            } catch (\Throwable $th) {
                DB::rollback();
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
           
        }
    /** insert */
    
    // /** view */
    //     public function view(Request $request){
    //         $id = base64_decode($request->id);
    //         $data1 = DMS::where('dms.id', $id)->first();
    //         return view('dms.view')->with(['data1' => $data1]);
    //     }
    // /** view */
    
    
     public function edit(Request $request){
            $id = base64_decode($request->id);
            $data = Dealer::where(['id' => $id])->first();
            $state_name = DB::table('common_state')->get();
            view()->share('states',$state_name);
            return view('dealer.edit')->with(['data' => $data]);
        }
        
        
          /** update */
        public function update(Request $request){
            if($request->ajax()){ return true ; }
            $crud = [
                    'dealer_name' => ucfirst($request->dealer_name),
                    'dealer_email' => $request->dealer_email,
                    'dealer_mobile_no' => $request->dealer_mobile_no,
                    'dealer_address' => $request->dealer_address,
                    'state' => $request->state,
                    'city' => $request->city,
                    'gst' => $request->gst,
                    'gst_no' => $request->gst_no,
                    'remark' => $request->remark,
                    'created_at' => date('Y-m-d H:i:s'),
                    'created_by' => auth()->user()->id,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            DB::beginTransaction();
            try {
                DB::enableQueryLog();
                $update = Dealer::where(['id' => $request->id])->update($crud);
                if ($update){
                    
                    DB::commit();
                    return redirect()->route('dealer')->with('success', 'Record inserted successfully');
                } else {
                    DB::rollback();
                    return redirect()->back()->with('error', 'Failed to insert record')->withInput();
                }
            } catch (\Throwable $th) {
                DB::rollback();
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
        }
    /** update */
    
    
    //  /** Import */
        public function import(Request $request){

            $import = Excel::import(new ImportDMS(), $request->file('file'));    
            if($import){
                Excel::store(new ImportDMS(), 'RSA_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('dms')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    // /** Import */
    
    /* Change Status */
    public function change_status(Request $request)
    {
        if (!$request->ajax()) {
            exit('No direct script access allowed');
        }

        $id = base64_decode($request->id);

        $data = Dealer::where(['id' => $id])->first();

        if (!empty($data)) {
            $update = Dealer::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s')]);

            if ($update)
                return response()->json(['code' => 200]);
            else
                return response()->json(['code' => 201]);
        } else {
            return response()->json(['code' => 201]);
        }
    }
}