<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RSA;
use App\Models\Carmodel;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportRSA;
use App\Exports\ExportRSA;
use App\Exports\ExportCCS;
use Auth, DB, Mail, Validator, File, DataTables, Exception;

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

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

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

                            if (auth()->user()->can('rsa-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('rsa_name', false)) {
                                    $query->where('rsa.name', 'like', "%" . request()->get("rsa_name") . "%");
                                }
                                if (request()->get('rsa_ccs', false)) {
                                    $query->where('rsa.rsa_ccs', 'like', "%" . request()->get("rsa_ccs") . "%");
                                }
                                if (request()->get('years', false)) {
                                    $query->where('rsa.years', 'like', "%" . request()->get("years") . "%");
                                }
                                if (request()->get('car_name', false)) {
                                    $query->where('car_model.name', 'like', "%" . request()->get("car_name") . "%");
                                }
                                if (request()->get('amount', false)) {
                                    $query->where('rsa.amount', 'like', "%" . request()->get("amount") . "%");
                                }
                                if (request()->get('profit', false)) {
                                    $query->where('rsa.profit', 'like', "%" . request()->get("profit") . "%");
                                }
                                if (request()->get('gst_percentage', false)) {
                                    $query->where('rsa.gst_percentage', 'like', "%" . request()->get("gst_percentage") . "%");
                                }
                                if (request()->get('gst', false)) {
                                    $query->where('rsa.gst', 'like', "%" . request()->get("gst") . "%");
                                }
                                if (request()->get('total_profit', false)) {
                                    $query->where('rsa.total_profit', 'like', "%" . request()->get("total_profit") . "%");
                                }
                            })
                        ->make(true);
            }
            return view('rsa.index');
        }
    /** index */

    /** create */
        public function create(Request $request){
            $car_model = Carmodel::where(['status' => "active"])->get();

            return view('rsa.create')->with(['car_model' => $car_model]);
        }
    /** create */
    
    /** insert */
        public function insert(Request $request){
            if($request->ajax()){
                return true;
            }
            $crud = [
                'rsa_ccs' => $request->rsa_ccs,
                'name' => ucfirst($request->name),
                'car_model' => $request->car_model,
                'years' => $request->years,
                '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'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            DB::beginTransaction();
            try {
                DB::enableQueryLog();
                $last_id = RSA::insertGetId($crud);
                if ($last_id) {
                    
                    DB::commit();
                    return redirect()->route('rsa')->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 = RSA::select('rsa.*','car_model.name as car_name')
            ->leftJoin('car_model','car_model.id','=','rsa.car_model')
            ->where('rsa.id', $id)->first();

            return view('rsa.view')->with(['data' => $data]);
        }
    /** view */
        
    /** edit */
        public function edit(Request $request){
            $id = base64_decode($request->id);
            $data = RSA::where(['id' => $id])->first();
            $car_model = Carmodel::where(['status' => "active"])->get();

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

    /** update */
        public function update(Request $request){
            if($request->ajax()){ return true ; }
            $crud = [
                'rsa_ccs' => $request->rsa_ccs,
                'name' => ucfirst($request->name),
                'car_model' => $request->car_model,
                'years' => $request->years,
                'amount' => $request->amount,
                'profit' => $request->profit,
                'gst_percentage' => $request->gst_percentage,
                'gst' => $request->gst,
                'total_profit' => $request->total_profit,
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            
            DB::beginTransaction();
            try {
                DB::enableQueryLog();
                $update = RSA::where(['id' => $request->id])->update($crud);
                if ($update){
                    
                    DB::commit();
                    return redirect()->route('rsa')->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 */
    /** change-status */
        public function change_status(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
             $id = base64_decode($request->id);

            $data = RSA::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = RSA::where(['id' => $id])->update(['deleted_at' => 1, '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 */

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

            $import = Excel::import(new ImportRSA(), $request->file('file'));    
            if($import){
                Excel::store(new ImportRSA(), 'RSA_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('rsa')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

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