<?php

namespace App\Http\Controllers;

use App\Http\Requests\SalesRequest;
use App\Models\Branch;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Models\Category;
use App\Models\Fuletype;
use App\Models\Product;
use App\Models\Sales;
use App\Models\Teammaster;
use Illuminate\Http\Request;
use App\Models\OBF;
use DB, Validator, DataTables;

class SalesController extends Controller
{
    //

    public function index(Request $request)
    {
        if ($request->ajax()) {


            // $data = DB::table('sales as s')
            //     ->select('s.id',  's.veriant', 'cv.name as varient_name', 'cm.name as car_name', 's.monthly_target', 'fule_type.title as fuel_type', 's.status')
            //     ->leftjoin('car_model as cm', 'cm.id', 's.name')
            //     ->leftjoin('car_varient as cv', 'cv.id', 's.veriant')
            //     ->leftJoin('exteriorcolor', 'exteriorcolor.id', '=', 's.exterior_color')
            //     ->leftJoin('interiorcolor', 'interiorcolor.id', '=', 's.interior_color')
            //     ->leftjoin('fule_type', 'fule_type.id', '=', 's.fuel_type')
            //     ->groupBy('s.id')
            //     ->orderBy('s.id', 'desc')
            //     ->where('s.status', '!=', 'deleted')
            //     ->get();


            $data = DB::table('sales as s')
                ->select('s.id',  's.name',  's.veriant', 's.status', 'cv.name as varient_name', 'cm.name as car_name', 's.monthly_target', 'fule_type.title as fuel_type')

                ->leftjoin('products', 's.name', 'products.id')
                ->leftjoin('car_model as cm', 'cm.id', 'products.car_model')
                ->leftjoin('car_varient as cv', 'cv.id', 'products.veriant')
                ->leftJoin('exteriorcolor', 'exteriorcolor.id', '=', 'products.exterior_color')
                ->leftJoin('interiorcolor', 'interiorcolor.id', '=', 'products.interior_color')
                ->leftJoin('obf', 'obf.product_id', '=', 's.name')
                ->leftjoin('fule_type', 'fule_type.id', '=', 's.fuel_type')
                ->groupBy('s.id')
                ->orderBy('s.id', 'desc')
                ->where('s.status', '!=', 'deleted')->get();


            // $data = DB::table('sales as s')
            // ->select('s.*')
            // ->where('s.status', '!=', 'deleted')
            // ->get();


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

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

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

                    if (auth()->user()->can('sales-delete')) {
                        if ($data->status == 'pdi_hold') {
                            $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">';

                            $return .= '<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>';
                        } else if ($data->status == 'allocated') {
                            //$return .= '';

                            $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">';


                            $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Deallocated</a></li>';
                            //Active

                            $return .= '</ul>';
                        } else {
                            $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">';

                            if ($data->status == 'active') {
                                $return .= '<li><a class="dropdown-item" href="' . route('inventory.accept', ['id' => base64_encode($data->id)]) . '">AllocateCustomer</a></li>';
                                $return .= '<li><a class="dropdown-item" href="' . route('dealer.accept', ['id' => base64_encode($data->id)]) . '">AllocateDealer</a></li>';
                            }

                            $return .= '<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'])
                ->make(true);
        }
        return view('sales.index');
    }
    public function create(Request $request)
    {

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

        $data = Product::select('car_model.name as car_name', 'products.id as car_id', 'car_varient.name as varient_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
            ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
            ->where('products.status', '=', 'active')
            ->get();

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

        $team_master = Teammaster::where(['status' => 'active'])->get();
        return view('sales.create')->with(['data' => $data, 'team_master' => $team_master, 'Carmodel_arr' => $Carmodel_arr, 'fuel_type' => $fuel_type]);
    }


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

        // dd($request);
        // $validate = Validator::make($request->all(),[
        //     'vin_number' => 'required|string|string|unique:inventory',
        // ]);
        // if ($validate->fails())
        // {
        //     return redirect()->back()->withErrors($validate);
        // }

        if (!empty($request->created_date) && $request->created_date != '' && $request->created_date != NULL) 
        {
            $created_date = date("Y-m-d", strtotime($request->created_date));
        }

        $data = [
            'name' => $request->name ?? NULL,
            'car_color' => $request->car_color ?? NULL,
            'fuel_type' => $request->fuel_type ?? NULL,
            'veriant' => $request->veriant ?? NULL,
            'team' => $request->team ?? NULL,
            'monthly_target' => $request->monthly_target ?? NULL,
            'exterior_color' => $request->exterior_color ?? NULL,
            'interior_color' => $request->interior_color ?? NULL,
            'status' => 'active',
            'created_date' => $created_date,
            '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
        ];

        $last_id = Sales::insertGetId($data);

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



    /** edit */
    public function edit(Request $request)
    {
        $id = base64_decode($request->id);


        $fuel_type = Fuletype::where(['status' => 'active'])->get();
        $data = Sales::select('sales.*', 'fule_type.title', 'fule_type.id as fuel_id')->leftjoin('fule_type', 'fule_type.id', '=', 'sales.fuel_type')->where(['sales.id' => $id])->first();

        // $Carmodel = Carmodel::select('car_model.name as car_name','car_model.id as car_id','car_varient.name as varient_name','exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
        //             ->leftJoin('car_varient','car_varient.car_model','=','car_model.id')
        //             ->leftJoin('exteriorcolor','exteriorcolor.id','=','car_varient.exterior_color')
        //             ->leftJoin('interiorcolor','interiorcolor.id','=','car_varient.interior_color')
        //             ->where('car_model.status', '=', 'active')
        //             ->get();

        $Carmodel = Product::select('car_model.name as car_name', 'products.id as car_id', 'car_varient.name as varient_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
            ->leftjoin('car_model', 'car_model.id', 'products.car_model')
            ->leftjoin('car_varient', 'car_varient.id', 'products.veriant')
            ->leftjoin('interiorcolor', 'interiorcolor.id', 'products.interior_color')
            ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'products.exterior_color')
            ->where('products.status', '=', 'active')
            ->get();

        $Cardata = Obf::select('obf.id as o_id', 'obf.product_id as o_product', 'car_model.name as car_name', 'car_model.id as car_id', 'car_varient.name as varient_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
            ->leftJoin('car_model', 'car_model.id', '=', 'obf.product_id')
            ->leftJoin('car_varient', 'car_varient.car_model', '=', 'car_model.id')
            ->leftJoin('exteriorcolor', 'exteriorcolor.id', '=', 'car_varient.exterior_color')
            ->leftJoin('interiorcolor', 'interiorcolor.id', '=', 'car_varient.interior_color')
            ->where('obf.id', '=', $id)
            ->first();

        $Product_data = Product::select('products.*', 'fule_type.id', 'fule_type.title')->leftjoin('car_varient', 'car_varient.id', '=', 'products.veriant')->leftjoin('fule_type', 'fule_type.id', '=', 'car_varient.fule_type')->where('products.id', $data->name)->where('products.status', '=', 'active')->first();
        if ($Product_data == null) {
            return redirect()->back()->with('error', 'Failed to edit record');
        }
        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get();
        $Carvarient = Carvarient::where(['status' => 'active', 'car_model' => $Product_data->car_model, 'fule_type' => $data->fuel_id])->get();

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


        return view('sales.edit')->with(['data' => $data, 'Carmodel' => $Carmodel, 'Cardata' => $Cardata, 'Carmodel_arr' => $Carmodel_arr, 'Product_data' => $Product_data, 'fuel_type' => $fuel_type, 'Carvarient' => $Carvarient, 'team_master' => $team_master]);
    }
    /** edit */
    /** edit */
    public function editBKP(Request $request)
    {
        $id = base64_decode($request->id);


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

        $data = Sales::select('sales.*', 'fule_type.title', 'fule_type.id as fuel_id')->leftjoin('fule_type', 'fule_type.id', '=', 'sales.fuel_type')->where(['sales.id' => $id])->first();


        $Carmodel = Sales::select('car_model.name as car_name', 'sales.id as car_id', 'car_varient.name as varient_name', 'exteriorcolor.name as exterior_color', 'interiorcolor.name as interior_color')
            ->leftjoin('car_model', 'car_model.id', 'sales.name')
            ->leftjoin('car_varient', 'car_varient.id', 'sales.veriant')
            ->leftjoin('interiorcolor', 'interiorcolor.id', 'sales.interior_color')
            ->leftjoin('exteriorcolor', 'exteriorcolor.id', 'sales.exterior_color')
            ->where('sales.status', '=', 'active')
            ->get();



        $Product_data = Sales::select('sales.*', 'fule_type.id', 'fule_type.title')->leftjoin('car_varient', 'car_varient.id', '=', 'sales.veriant')->leftjoin('fule_type', 'fule_type.id', '=', 'car_varient.fule_type')->where('sales.name', $data->name)->where('sales.status', '=', 'active')->first();
        if ($Product_data == null) {
            return redirect()->back()->with('error', 'Failed to edit record');
        }
        $Carmodel_arr = Carmodel::where(['status' => 'active'])->get();
        $Carvarient = Carvarient::where(['status' => 'active', 'car_model' => $Product_data->name, 'fule_type' => $data->fuel_type])->get();
        return view('sales.edit')->with(['data' => $data, 'Carmodel' => $Carmodel, 'Carmodel_arr' => $Carmodel_arr, 'Product_data' => $Product_data, 'fuel_type' => $fuel_type, 'Carvarient' => $Carvarient]);
    }
    /** edit */

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


        if (!empty($request->created_date) && $request->created_date != '' && $request->created_date != NULL) 
        {
            $created_date = date("Y-m-d", strtotime($request->created_date));
        }


        $data = [
            'name' => $request->name ?? NULL,
            'car_color' => $request->car_color ?? NULL,
            'fuel_type' => $request->fuel_type ?? NULL,
            'veriant' => $request->veriant ?? NULL,
            'team' => $request->team ?? NULL,
            'monthly_target' => $request->monthly_target ?? NULL,
            'exterior_color' => $request->exterior_color ?? NULL,
            'interior_color' => $request->interior_color ?? NULL,
            'status' => 'active',
            'created_date' => $created_date,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => auth()->user()->id
        ];
        $update = Sales::where(['id' => $request->id])->update($data);

        if ($update)
            return redirect()->route('sales')->with('success', 'Record updated successfully');
        else
            return redirect()->back()->with('error', 'Failed 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 = Sales::where(['id' => $id])->first();

        if (!empty($data)) {
            // DB::enableQueryLog();

            $update = Sales::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth()->user()->id]);
            // dd(DB::getQueryLog());



            /* var_dump($update);
   
               die('stop');*/


            if ($update)
                return response()->json(['code' => 200]);
            else
                return response()->json(['code' => 201]);
        } else {
            return response()->json(['code' => 201]);
        }
    }
    /** change-status */
}
