<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Department;
use App\Models\carcompany;
use App\Exports\ExportCarCompany;
use App\Imports\ImportCarCompany;
use Maatwebsite\Excel\Facades\Excel;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
use App\Imports\ImportDepartment;

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

//  index 
    public function index(Request $request){
        if($request->ajax()){
            $data = carcompany::select('*')->orderBy('id' , 'desc');
            
                return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($data){
                        $return = '<div class="btn-group">';

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

                       if (auth()->user()->can('carcompany-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) . '">Delete</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>';
                        }else{
                            return '-';
                        }
                    })

                    ->rawColumns([ 'action' ,'status'])
                    ->filter(function ($query) {
                                if (request()->get('company_name', false)) {
                                    $query->where('carcompany.company_name', 'like', "%" . request()->get("company_name") . "%");
                                }
                            })
                    ->make(true);
            }
        return view('carcompany.index');
    }
//  index 

// create /
    public function create(Request $request){
        
        $data = carcompany::select('carcompany.*')->where(['status' => 'active'])->get(); 
        $country = carcompany::select('carcompany.*')->where(['status'=>'active'])->get();
        return view('carcompany.create')->with(['data' => $data,'country'=>$country]);
    }
//  create /
//  insert 
    public function insert(Request $request){
        if($request->ajax()){
            return true ;
        }
        $crud = [
   
                'id' => $request->id,
                'company_name' => $request->company_name,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
        ];
        
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $last_id = carcompany::insertGetId($crud);
            if ($last_id) {
                
                DB::commit();
                return redirect()->route('carcompany')->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);
                                
        $data = carcompany::select('*')->where(['id' => $id])->first();
        $country = carcompany::select('carcompany.*')->where(['status'=>'active'])->get(); 
        return view('carcompany.view')->with(['data' => $data,'country'=>$country]);
    }
// view /

// edit /
    public function edit(Request $request){
        $id = base64_decode($request->id);
                                
        $data = carcompany::select('*')->where(['id' => $id])->first();
        $country = carcompany::select('carcompany.*')->where(['status'=>'active'])->get(); 
        //   $data = AllCity::select('all_city.*')->where(['status' => 'active'])->get(); 
     //   $country = AllCity::select('all_city.*')->where(['status'=>'active'])->get();
        return view('carcompany.edit')->with(['data' => $data,'country'=>$country]);;
    }
// edit /

//  update 
    public function update(Request $request){
        if($request->ajax()){
            return true ;
        }
       // $branch_admin=$request->branch_admin ? 1 : NULL;
        $crud = [
            'id' => $request->id,
            'company_name' => $request->company_name,
            'status' => 'active',
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];
       
        
        DB::beginTransaction();
        try {
            DB::enableQueryLog();
            $update = carcompany::where(['id' => $request->id])->update($crud);
            if($update){
                DB::commit();
                return redirect()->route('carcompany')->with('success', 'Record updated successfully');
            } else {
                DB::rollback();
                return redirect()->back()->with('error', 'Failed to update record')->withInput();
            }
        } catch (\Throwable $th) {
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong, please try again later')->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 = carcompany::where(['id' => $id])->first();
       
            if(!empty($data)){
                $update = carcompany::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]);
            }
    }
//  change-status 

    public function export(Request $request){
        if(isset($request->slug) && $request->slug != null){
            $slug = $request->slug;
        }else{
            $slug = 'all';
        }

        $name = 'CarCompany_'.Date('YmdHis').'.xlsx';

        try {
            return Excel::download(new ExportCarCompany($slug), $name);
        }catch(\Exception $e){
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
    
    /** Import */
        public function import(Request $request){
               
            if(Excel::import(new ImportCarCompany, $request->file('file')->store('file'))){
                return redirect()->route('carcompany')->with('sucess' ,'File Imported Sucessfully');
            }else{
                return redirect()->route('carcompany')->with('error' ,'Faild To Import File!');
            }
        }
        /** Import */
/* Export /
   /* public function export(Request $request){
        if(isset($request->slug) && $request->slug != null){
            $slug = $request->slug;
        }else{
            $slug = 'all';
        }

        $name = 'all_city_'.Date('YmdHis').'.xlsx';

        try {
            return Excel::download(new ExportDepartment($slug), $name);
        }catch(\Exception $e){
            return redirect()->back()->with('error', $e->getMessage());
        }
    }*/
/* Export /
/* Import /
/*public function import(Request $request){
       
    if(Excel::import(new ImportDepartment, $request->file('file')->store('file'))){
        return redirect()->route('department')->with('sucess' ,'File Imported Sucessfully');
    }else{
        return redirect()->route('department')->with('error' ,'Faild To Import File!');
    }
}*/
//  Import /
}