<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DMS;
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 DMSController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:dms-create', ['only' => ['create']]);
            $this->middleware('permission:dms-edit', ['only' => ['edit']]);
            $this->middleware('permission:dms-view', ['only' => ['view']]);
            $this->middleware('permission:dms-delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
    
    public function index(Request $request){
            if($request->ajax()){
                $data = DMS::orderBy('id' ,'desc');
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';
                            if(auth()->user()->can('dms-view')){
                                $return .= '<a href="'.route('dms.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('dms.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('date',false)) {
                                $date = \Carbon\Carbon::parse(request()->get("date"))->format('Y-m-d');
                                $query->where('dms.date', "like", "%".$date."%");
                            }
                            if (request()->get('dms_invoice_no',false)) {
                                $query->where('dms.dms_invoice_no', "like", "%".request()->get("dms_invoice_no")."%");
                            }
                            if (request()->get('vin_number',false)) {
                                $query->where('dms.vin_number', "like", "%".request()->get("vin_number")."%");
                            }
                            if (request()->get('basic_amount',false)) {
                                $query->where('dms.basic_amount', "like", "%".request()->get("basic_amount")."%");
                            }
                            if (request()->get('gst_amount',false)) {
                                $query->where('dms.gst_amount', "like", "%".request()->get("gst_amount")."%");
                            }
                            if (request()->get('total_amount',false)) {
                                $query->where('dms.total_amount', "like", "%".request()->get("total_amount")."%");
                            }
                            if (request()->get('getpass_closing_date',false)) {
                                $query->where('dms.getpass_closing_date', "like", "%".request()->get("getpass_closing_date")."%");
                            }
                            if (request()->get('scheme',false)) {
                                $query->where('dms.scheme', "like", "%".request()->get("scheme")."%");
                            }
                            if (request()->get('remark',false)) {
                                $query->where('dms.remark', "like", "%".request()->get("remark")."%");
                            }
                        })    
                        ->make(true);
            }
            return view('dms.index');
        }
        
        /** create */
            public function create(Request $request){
                return view('dms.create');
            }
        /** create */
        
        /** insert */
        public function insert(Request $request){
            if($request->ajax()){
                return true;
            }
            $crud = [
                'date' => ucfirst($request->date),
                'dms_invoice_no' => $request->dms_invoice_no,
                'vin_number' => $request->vin_number,
                'basic_amount' => $request->basic_amount,
                'gst_amount' => $request->gst_amount,
                'total_amount' => $request->total_amount,
                'getpass_closing_date' => $request->getpass_closing_date,
                'scheme' => $request->scheme,
                '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 = DMS::insertGetId($crud);
                if ($last_id) {
                    
                    DB::commit();
                    return redirect()->route('dms')->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 = DMS::where(['id' => $id])->first();
            return view('dms.edit')->with(['data' => $data]);
        }
        
        
          /** update */
        public function update(Request $request){
            if($request->ajax()){ return true ; }
           $crud = [
                'date' => ucfirst($request->date),
                'dms_invoice_no' => $request->dms_invoice_no,
                'vin_number' => $request->vin_number,
                'basic_amount' => $request->basic_amount,
                'gst_amount' => $request->gst_amount,
                'total_amount' => $request->total_amount,
                'getpass_closing_date' => $request->getpass_closing_date,
                'scheme' => $request->scheme,
                '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 = DMS::where(['id' => $request->id])->update($crud);
                if ($update){
                    
                    DB::commit();
                    return redirect()->route('dms')->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){
            
            if(Excel::import(new ImportDMS, $request->file('file')->store('file'))){
                return redirect()->route('dms')->with('sucess' ,'File Imported Sucessfully');
            }else{
                return redirect()->route('dms')->with('error' ,'Faild To Import File!');
            }
        }
    /** Import */
}