<?php

namespace App\Http\Controllers\IncentiveSlab;

use App\Http\Controllers\Controller;
use App\Exports\IncentiveSlabDetailsExport;
use App\Imports\IncentiveSlabDetailsImport;
use App\Models\IncentiveSlab;
use App\Models\IncentiveSlabDetail;
use App\Models\Product;
use App\Models\ProductBrand;
use App\Models\ProductCategory;
use App\Models\ProductGroup;
use App\Models\TaxMaster;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class IncentiveSlabDetailsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:incentive-slab-details-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = IncentiveSlabDetail::select([
            'incentive_slab_details.id',
            'incentive_slab_details.slab_id',
            'incentive_slab_details.product_id',
            'incentive_slab_details.calculation_type',
            'incentive_slab_details.percentage',
            'incentive_slab_details.price',
            'incentive_slab_details.other_charges',
            'incentive_slab_details.status',
        ])
            ->with('getProduct')
            ->with('getSlab')
            ->paginate(10);

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

            $data = IncentiveSlabDetail::when(!empty($search_query), function ($query) use ($search_query) {
                return $query->whereHas('getSlab', function($subquery) use ($search_query) {
                    $subquery->where('slab_name', 'like', '%'.$search_query.'%');
                });
            });

            $data = $data->when(!empty($incentive_slab_details), function($query) use ($incentive_slab_details) {
                return $query->where('incentive_slab_details.slab_id', $incentive_slab_details);
            })
                    ->paginate($sort_by);

            return view('incentive-slab-details.table', compact('data'));
        }
        else
        {
            $incentive_slab_details = IncentiveSlabDetail::select('id', 'slab_id')->with('getSlab')->groupBy('slab_id')->get();
            return view('incentive-slab-details.index',compact('data','incentive_slab_details'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $slab = IncentiveSlab::select('id','slab_name')->where('status',1)->get();
        $product = Product::select('id','name')->get();
        return view('incentive-slab-details.create',compact('slab','product'));
    }

    /**
     * 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_id'    => 'required',
            'product_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'
        ]);

        IncentiveSlabDetail::create($data);

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

        return redirect()->route('incentive-slab-details.index')
            ->with('success','Incentive Slab Details 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)
    {
        $slab = IncentiveSlab::select('id','slab_name')->where('status',1)->get();
        $product = Product::select('id','name')->get();
        $Incentive_slab_detail = IncentiveSlabDetail::find($id);

        return view('incentive-slab-details.edit',compact('slab','product','Incentive_slab_detail'));
    }

    /**
     * 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_id'    => 'required',
            'product_id' => 'required'
        ]);

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

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

        $paymentMode = IncentiveSlabDetail::find($id);

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

        $paymentMode->update($data);

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

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

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

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

        $data->delete();

        $Redirect = 'incentive-slab-details';

        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 = IncentiveSlabDetail::where('id', '=', $request->id)->update($data);

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


    public function incentiveSlabDetailsExportCreate($id = '')
    {
        $incentive_slab = IncentiveSlab::select('id','slab_name')->get();
        return view('incentive-slab-details.export-create',compact('incentive_slab','id'));
    }
    public function incentiveSlabDetailsExportView()
    {
        $brand = ProductBrand::select('id','name')->get();
        $product_category = ProductCategory::select('id','name')->get();
        $product_group = ProductGroup::select('id','name')->get();

        return view('incentive-slab-details.view', compact('brand','product_category','product_group'));
    }
    public function incentiveSlabDetailExport(Request $request)
    {
        return Excel::download(new IncentiveSlabDetailsExport(request()), 'Incentive_Slab_Details_Export.xlsx');
    }
    public function incentiveSlabDetailImport(Request $request)
    {
        Excel::import(new IncentiveSlabDetailsImport($request), $request->file('incentive_slab_details'));
        return redirect()->back()->with('success', 'File uploaded successfully');
    }

}
