<?php

namespace App\Http\Controllers\IncentiveSlab;

use App\Http\Controllers\Controller;
use App\Models\BusinessDivision;
use App\Models\Company;
use App\Models\IncentiveSlab;
use App\Models\IncentiveSlabDetail;
use App\Models\MasterType;
use App\Models\ProductGroup;
use App\Models\Product;
use App\Models\ProductBrand;
use App\Models\ProductCategory;
use Illuminate\Http\Request;

class IncentiveSlabController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:incentive-slab-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = IncentiveSlab::select([
            'incentive_slabs.id',
            'incentive_slabs.slab_name',
            'incentive_slabs.code',
            'incentive_slabs.account_type_id',
            'incentive_slabs.company_id',
            'incentive_slabs.calculation_type',
            'incentive_slabs.percentage',
            'incentive_slabs.price',
            'incentive_slabs.is_default',
            'incentive_slabs.status'
        ])
            ->with('getType')
            ->with('getCompany')
            ->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = IncentiveSlab::when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('incentive_slabs.slab_name', 'like', '%'.$search_query.'%');
            })
                    ->paginate($sort_by);

            return view('incentive-slabs.table', compact('data'));
        }
        else
        {
            return view('incentive-slabs.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $company = Company::select('id','name')->get();
        $MasterType = MasterType::select('id','type_name')->where('status',1)->get();
        return view('incentive-slabs.create',compact('company','MasterType'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'slab_name'       => 'required|unique:incentive_slabs,slab_name,NULL,id,deleted_at,NULL',
            'account_type_id' => 'required'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $default_check = IncentiveSlab::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        IncentiveSlab::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Incentive Slab created successfully',
            ]);
        }

        return redirect()->route('incentive-slabs.index')
            ->with('success','Incentive Slab created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $company = Company::select('id','name')->get();
        $MasterType = MasterType::select('id','type_name')->where('status',1)->get();
        $slab = IncentiveSlab::find($id);

        return view('incentive-slabs.edit',compact('slab','MasterType','company'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'slab_name'       => 'required|unique:incentive_slabs,slab_name,'.$id.',id,deleted_at,NULL',
            'account_type_id'     => 'required'

        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $source = IncentiveSlab::find($id);

        if (!$source) {
            return redirect()->route('incentive-slabs.index')
                ->with('error','Incentive Slab not found!');
        }

        $source->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Incentive Slab updated successfully',
                'data'    => $source
            ]);
        }

        return redirect()->route('incentive-slabs.index')
            ->with('success','Incentive Slab updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = IncentiveSlab::find($request->id);

        if ($data->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'incentive-slabs';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = IncentiveSlab::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Incentive Slab status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data  = array('is_default' => $request->status );
            $count = IncentiveSlab::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Incentive Slab!'],
                    'data'    => []
                ]);
            }

            $Update = IncentiveSlab::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Incentive Slab default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

    public function details($id, Request $request)
    {
        $slab = IncentiveSlab::with('getType')
            ->find($id);

        if (!$slab) {
            abort(404);
        }
        $data = Product::select([
            'products.id',
            'products.name',
            'products.brand_id',
            'incentive_slab_details.id as slab_detail_id',
            'slab_id',
            'calculation_type',
            'percentage',
            'price',
            'product_prices.sale_price',
        ])

        ->leftjoin('incentive_slab_details', function ($join) use ($id) {
            $join->on('incentive_slab_details.product_id', '=', 'products.id')
                    ->where('incentive_slab_details.slab_id', '=', $id);
        })
        ->leftjoin('product_prices', 'product_prices.product_id', 'products.id')
        ->where('products.status','1');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $brand_id     = $request->get('brand_id');
            $group_id     = $request->get('group_id');
            $category_id  = $request->get('category_id');
            $division_id  = $request->get('division_id');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('products.name', 'like', '%'.$search_query.'%');
                })
                ->when(!empty($brand_id), function ($query) use ($brand_id) {
                    return $query->where('products.brand_id', $brand_id);
                })
                ->when(!empty($group_id), function ($query) use ($group_id) {
                    return $query->where('products.composition_id', $group_id);
                })
                ->when(!empty($division_id), function ($query) use ($division_id) {
                    return $query->where('products.business_division_id', $division_id);
                })
                ->when(!empty($category_id), function ($query) use ($category_id) {
                    return $query->where('products.category_id', $category_id);
                })
                ->groupBy('products.id')
                ->orderBy('products.name')
                ->paginate($sort_by);

            return view('incentive-slabs.details.table', compact('data','search_query'));
        } else {
            $business_division = BusinessDivision::select('id','name')->where('status',1)->get();
            $brand             = ProductBrand::select('id','name')->where('status',1)->get();
            $category          = ProductCategory::select('id','name')->where('status',1)->get();
            $group             = ProductGroup::select('id','name')->where('status',1)->get();

            $data = $data->groupBy('products.id')
                ->orderBy('products.name')
                ->paginate(10);

            return view('incentive-slabs.details.index',compact('data', 'slab', 'id','business_division','brand','category','group'));
        }
    }

    public function storeDetails(Request $request, $id)
    {
        $slab = IncentiveSlab::find($id);

        if (!$slab) {
            abort(404);
        }
        $percentage = $request->percentage ?? [];
        $price      = $request->price ?? [];

        foreach($request->calculation_type as $key => $value) {
            IncentiveSlabDetail::updateOrCreate([
                'slab_id'    => $id,
                'product_id' => $key
            ],[
                'calculation_type' => $value,
                'percentage'       => $percentage[$key],
                'price'            => $price[$key],
            ]);
        }

        return redirect()->back()->with('success', 'Details updated successfully.');
    }
}
