<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\CNGKit;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportCNGKit;
use App\Exports\ExportCNGKit;
use Auth, DB, Mail, Validator, File, DataTables, Exception;


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

    /** index */
    public function index(Request $request){

        if($request->ajax()){
            
            $data = CNGKit::whereIn('cng_kit.status', ['active', 'inactive'])->orderBy('id' , 'desc');

            return Datatables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function($data){
                $return = '<div class="btn-group">';

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

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

                $return .= '</div>';

                return $return;
            })

            ->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','status'])
            ->filter(function ($query) {
                if (request()->get('name', false)) {
                    $query->where('cng_kit.name', 'like', "%" . request()->get("name") . "%");
                }
                if (request()->get('amount', false)) {
                    $query->where('cng_kit.amount', 'like', "%" . request()->get("amount") . "%");
                }
                if (request()->get('company', false)) {
                    $query->where('cng_kit.company', 'like', "%" . request()->get("company") . "%");
                }
                if (request()->get('kg', false)) {
                    $query->where('cng_kit.kg', 'like', "%" . request()->get("kg") . "%");
                }
            })
            ->make(true);
        }
        
        return view('cng_kit.index'); 
    }

    /** create */
    public function create(Request $request){
        return view('cng_kit.create');
    }

    /** insert */
    public function insert(Request $request){
        if($request->ajax()) { return true; }
        $crud = [
            'name' => $request->name,
            'amount' => $request->amount,
            'company' => $request->company,
            'kg' => $request->kg,
            'status' => 'active',
            'created_by' => auth()->user()->id,
            'created_at' => date('Y-m-d H:i:s')
        ];

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

        if ($last_id) {
            return redirect()->route('cng_kit')->with(['success' => 'Record inserted successfully']);
        } else {
            return redirect()->back()->with(['error'=>'Faild to insert Record!'])->withInput();
        }
    
    }

    /** view */
    public function view(Request $request){
        $id = base64_decode($request->id);
        $data = CNGKit::where('cng_kit.id', $id)->first();
                
        return view('cng_kit.view')->with(['data'=>$data]);
    }
    
    /** edit */
    public function edit(Request $request){
        $id = base64_decode($request->id);
        $data = CNGKit::where(['id' => $id])->first();

        return view('cng_kit.edit')->with(['data'=>$data]);
    }

    /** update */
    public function update(Request $request){
        if($request->ajax()){ return true; }
        $id = $request->id;
        
        $crud = [
            'name' => $request->name,
            'amount' => $request->amount,
            'company' => $request->company,
            'kg' => $request->kg,
            'status' => 'active',
            'updated_by' => auth()->user()->id,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        DB::enableQueryLog();

        $update = CNGKit::where(['id' => $id])->update($crud);

        if ($update){
            return redirect()->route('cng_kit')->with(['success' => 'Record updated successfully']);
        }else{
            return redirect()->back()->with(['error'=>'Faild to update Record!'])->withInput();
        }
    }

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

        if (!empty($data)) {
            $update = CNGKit::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]);
        }
       
    }

     /** Import */
    public function import(Request $request){

        $import = Excel::import(new ImportCNGKit(), $request->file('file'));    
        if($import){
            Excel::store(new ImportCNGKit(), 'CNGKit'.Date('YmdHis').'.xlsx' ,'excel_import');
            return redirect()->route('cng_kit')->with('sucess' ,'File Imported Sucessfully');
        }
    }

    /** Export */
    public function export(Request $request){
        $slug = $request->slug;
        $name = 'CNGKit'.Date('YmdHis').'.xlsx';

        try {
            return Excel::download(new ExportCNGKit($slug), $name);
        }catch(\Exception $e){
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
