<?php

namespace App\Http\Controllers;

use App\Exports\ExportMcp;
use App\Imports\ImportMcp;
use App\Models\Carmodel;
use App\Models\Fuletype;
use App\Models\Mcp;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

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

    /** index */
        public function index(Request $request){
            if($request->ajax()){
                
                $data = Mcp::select('mcp.*','car_model.name as car_name')
                    ->leftJoin('car_model','car_model.id','=','mcp.car_model')
                    ->where('mcp.status', 'active')
                    ->orderBy('mcp.id' , 'desc');
                
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

                            // if(auth()->user()->can('mcp-view')){
                                /*$return .= '<a href="'.route('mcp.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-eye"></i>
                                            </a> &nbsp;';*/
                            // }   
                            
                             if(auth()->user()->can('mcp-edit')){
                                $return .= '<a href="'.route('mcp.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-pencil"></i>
                                            </a> &nbsp;';
                            }   

                            if (auth()->user()->can('mcp-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="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Deleted</a></li>
                                                </ul>';
                            }

                            $return .= '</div>';

                            return $return;
                        })

                        /*->editColumn('percentage', function ($data) {
                            return $data->percentage."%";
                        })*/
                        ->editColumn('status', function ($data) {
                            if ($data->status == 'active') {
                                return '<span class="badge badge-pill badge-success">Active</span>';
                            } else if ($data->status == 'inactive') {
                                return '<span class="badge badge-pill badge-warning">Inactive</span>';
                            } else if ($data->status == 'deleted') {
                                return '<span class="badge badge-pill badge-danger">Deleted</span>';
                            }
                        })

                        ->rawColumns(['action' ,'percentage' ,'status'])
                        ->filter(function ($query) {
                                if (request()->filled('mcp_name')) {
                                    $query->where('mcp.name', 'like', '%' . request()->get('mcp_name') . '%');
                                }
                                if (request()->filled('car_model')) {
                                    $query->where('car_model.name', 'like', '%' . request()->get('car_model') . '%');
                                }
                                if (request()->filled('amount')) {
                                    $query->where('mcp.amount', request()->get('amount'));
                                }
                                if (request()->filled('profit')) {
                                    $query->where('mcp.profit', request()->get('profit'));
                                }
                                if (request()->filled('gst_percentage')) {
                                    $query->where('mcp.gst_percentage', request()->get('gst_percentage'));
                                }
                                if (request()->filled('gst')) {
                                    $query->where('mcp.gst', request()->get('gst'));
                                }
                                if (request()->filled('total_profit')) {
                                    $query->where('mcp.total_profit', request()->get('total_profit'));
                                }
                            })
                        ->make(true);
            }
            return view('mcp.index');
        }
    /** index */

    /** create */
        public function create(Request $request){
            
            $Carmodel = Carmodel::where(['status' => 'active'])->get();
            $fualtype = Fuletype::where(['status' => 'active'])->get();
            return view('mcp.create')->with(['Carmodel'=>$Carmodel,'fualtype'=>$fualtype]);
        }
    /** create */

    /** insert */
        public function insert(Request $request){
            if($request->ajax()) { return true; }

            if(!empty($request->name)){
                $crud['name'] = $request->name;
            }else{
                $crud['name'] = '';
            }

            $crud = [
                'name' => $request->name,
                'car_model' => $request->car_model,
                'fual_type_id' => $request->fual_type,
                'amount' => $request->amount,
                'profit' => $request->profit,
                'gst_percentage' => $request->gst_percentage,
                'gst' => $request->gst,
                'total_profit' => $request->total_profit,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
            ];

            $last_id = Mcp::insertGetId($crud);

            if ($last_id)
            return redirect()->route('mcp')->with('success', 'Record inserted successfully');
            else
                return redirect()->back()->with('error', 'Failed to insert record')->withInput();
            
            }
    /** insert */

    /** view */
        /*public function view(Request $request){
            $id = base64_decode($request->id);
            $data = Carvarient::where(['id' => $id])->first();
            
            // return view('mcp.view')->with(['data'=>$data]);

            $Carmodel = Carmodel::where(['status' => 'active'])->get();
            $Colortone = Colortone::where(['status' => 'active'])->get();
            $Fuletype = Fuletype::where(['status' => 'active'])->get();
            $Transmission = Transmission::where(['status' => 'active'])->get();
            $Interiorcolor = Interiorcolor::where(['status' => 'active'])->get();
            $Exteriorcolor = Exteriorcolor::where(['status' => 'active'])->get();
            return view('mcp.view')->with(['data'=>$data,'Carmodel' => $Carmodel ,'Colortone' => $Colortone,'Fuletype'=>$Fuletype,'Transmission' => $Transmission,'Interiorcolor' => $Interiorcolor,'Exteriorcolor' => $Exteriorcolor]);
        }*/
    /** view */
    
    /** edit */
        public function edit(Request $request){
            $id = base64_decode($request->id);
            $data = Mcp::where(['id' => $id])->first();
            $Carmodel = Carmodel::where(['status' => 'active'])->get();
            $fualtype = Fuletype::where(['status' => 'active'])->get();

            return view('mcp.edit')->with(['data'=>$data, 'Carmodel'=>$Carmodel,'fualtype'=>$fualtype]);
        }
    /** edit */

    /** update */
        public function update(Request $request){
            if($request->ajax()){ return true; }
            $id = $request->id;
            
            if(!empty($request->name)){
                $crud['name'] = $request->name;
            }else{
                $crud['name'] = '';
            }

            $crud = [
                'name' => $request->name,
                'car_model' => $request->car_model,
                'fual_type_id' => $request->fual_type,
                'amount' => $request->amount,
                'profit' => $request->profit,
                'gst_percentage' => $request->gst_percentage,
                'gst' => $request->gst,
                'total_profit' => $request->total_profit,
            ];

            DB::enableQueryLog();
            $update = Mcp::where(['id' => $id])->update($crud);
            

            if ($update)
            return redirect()->route('mcp')->with('success', 'Record updated successfully');
            else
                return redirect()->back()->with('error', 'Failed to updated record')->withInput();
            
            }
        
    /** update */

    /** change-status */
        public function change_status(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
            $id = base64_decode($request->id);
            
            $data = Mcp::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = Mcp::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);
                if ($update) {
                    return response()->json(['code' => 200]);
                } else {
                    return response()->json(['code' => 201]);
                }
            } else {
                return response()->json(['code' => 201]);
            }
  
        }
    /** change-status */

      /** Import */
        public function import(Request $request){
            $import = Excel::import(new ImportMcp(), $request->file('file'));    
            if($import){
                Excel::store(new ImportMcp(), 'Mcp_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('mcp')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

    /** Export */
        public function export(Request $request){
            $slug = $request->slug;
            $name = 'Mcp_'.Date('YmdHis').'.xlsx';
    
            try {
                return Excel::download(new ExportMcp($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error', $e->getMessage());
            }
        }
    /** Export */

   
}
