<?php

namespace App\Http\Controllers;

use App\Models\Colortone;

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


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

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

            if($request->ajax()){
                
                 $data = Exteriorcolor::select('exteriorcolor.*','colortone.name as color_name')
                 
                    ->leftJoin('colortone','colortone.id','=','exteriorcolor.tone_selection')
                    ->whereIn('exteriorcolor.status', ['active', 'inactive'])
                    ->orderBy('id' , 'desc');
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

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

                            if (auth()->user()->can('exterior-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('exterior_name', false)) {
                                    $query->where('exteriorcolor.name', 'like', "%" . request()->get("exterior_name") . "%");
                                }
                                 if (request()->get('color_name', false)) {
                                    $query->where('colortone.name', 'like', "%" . request()->get("color_name") . "%");
                                }
                            })
                        ->make(true);
            }
            
            return view('exterior.index'); 
        }
    /** index */

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

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

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

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

    /** view */
        public function view(Request $request){
            $id = base64_decode($request->id);
            
             $data = Exteriorcolor::select('exteriorcolor.*','colortone.name as color_name')
                    ->leftJoin('colortone','colortone.id','=','exteriorcolor.tone_selection')
                    ->where('exteriorcolor.id', $id)->first();
                    
            return view('exterior.view')->with(['data'=>$data]);
        }
    /** view */
    
    /** edit */
        public function edit(Request $request){
            $id = base64_decode($request->id);
            $data = Exteriorcolor::where(['id' => $id])->first();

            
            $Colortone = Colortone::where(['status' => 'active'])->get();

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

    /** update */
        public function update(Request $request){
            if($request->ajax()){ return true; }
            $id = $request->id;
            
            $crud = [
                'name' => $request->name,
                'tone_selection' => $request->tselection,
                'status' => 'active',
                'created_by' => auth()->user()->id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            DB::enableQueryLog();
            $update = Exteriorcolor::where(['id' => $id])->update($crud);
            // dd(DB::getQueryLog());
            if ($update){
                return redirect()->route('exterior')->with(['success' => 'Record updated successfully']);
            }else{
                return redirect()->back()->with(['error'=>'Faild to update 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 = Exteriorcolor::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = Exteriorcolor::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 ImportExteriorcolor(), $request->file('file'));    
            if($import){
                Excel::store(new ImportExteriorcolor(), 'Exteriorcolor_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('exterior')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

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