<?php

namespace App\Http\Controllers\IncentiveSlab;

use App\Http\Controllers\Controller;
use App\Exports\IncentiveSettingExport;
use App\Imports\IncentiveSettingExport as ImportsIncentiveSettingExport;
use App\Imports\IncentiveSettingImport;
use App\Models\Account;
use App\Models\AccountingType;
use App\Models\IncentiveSetting;
use App\Models\IncentiveSlab;
use App\Models\MasterType;
use App\Models\TaxCategory;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class IncentiveSettingsController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:incentive-setting-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = IncentiveSetting::select([
            'incentive_settings.id',
            'incentive_settings.account_id',
            'incentive_settings.slab_id',
            'incentive_settings.date_upto',
            'incentive_settings.received_by',
            'incentive_settings.status',
        ])
            ->with('getAccount')
            ->with('getIncentiveSlab')
            ->paginate(10);

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

                $data = IncentiveSetting::query()
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    $query->whereHas('getAccount', function ($subQuery) use ($search_query) {
                        $subQuery->where('name', 'like', '%' . $search_query . '%');
                    });
                })
                        ->paginate($sort_by);

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $account_id = $request->input('account_id');
        $validator = \Validator::make($request->all(), [
            'slab_id' => [
                'required',
                Rule::unique('incentive_settings')->where(function ($query) use ($account_id) {
                    return $query->where('account_id', $account_id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);

        $customMessages = [
            'slab_id.unique' => 'The Slab is Already Taken.',
        ];

        $validator->setCustomMessages($customMessages);
        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'
        ]);

        // $data['date_upto'] = $request->date_upto != '' && $request->date_upto != '0000-00-00' &&  $request->date_upto != Null ? date('Y-m-d', strtotime($request->date_upto)) : null;
        // $data['date_upto'] = $request->date_upto != '' ? date('Y-m-d', strtotime($request->date_upto)) : '';
        $data['date_upto'] = $request->date_upto != '' && $request->date_upto != '0000-00-00' &&  $request->date_upto != Null ? date('Y-m-d', strtotime($request->date_upto)) : null;

        $source = IncentiveSetting::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bed Group Created successfully',
                'data' => $source
            ]);
        }
        return redirect()->route('incentive-settings.index')
            ->with('success', 'Bed Group 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)
    {
        $incentive_setting = IncentiveSetting::find($id);
        $account = Account::select('id', 'name')->get();
        $slab = IncentiveSlab::select('id', 'slab_name')->where('status',1)->get();
        return view('incentive-settings.edit', compact('slab','account','incentive_setting'));
    }

    /**
     * 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',
        ]);

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

        $data = $request->except([
            '_token',
            '_method'
        ]);
        $data['date_upto'] = $request->date_upto != '' && $request->date_upto != '0000-00-00' &&  $request->date_upto != Null ? date('Y-m-d', strtotime($request->date_upto)) : null;

        $payment_term = IncentiveSetting::find($id);

        if (!$payment_term) {
            return redirect()->route('incentive-settings.index')
                ->with('error','Payment Term not found!');
        }

        $payment_term->update($data);

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

        return redirect()->route('incentive-settings.index')
            ->with('success','Payment Term updated successfully');
    }


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

        $Redirect = 'incentive-settings';

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Incentive Setting status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function changeReceivedBy(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('received_by' => $request->status );
            $Update = IncentiveSetting::where('id', '=', $request->id)->update($data);

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

    public function exportCreate()
    {
        return view('incentive-settings.export-create');
    }
    public function exportView()
    {
        $MasterType = MasterType::select('id','type_name')->get();
        return view('incentive-settings.view', compact('MasterType'));
    }
    public function export(Request $request)
    {
        return Excel::download(new IncentiveSettingExport(request()), 'incentive_settings.xlsx');
    }
    public function import(Request $request)
    {
        Excel::import(new IncentiveSettingImport, $request->file('incentive_settings'));
        return redirect()->back()->with('success','file uploaded successfully');
    }
    public function searchAccount(Request $request)
    {
        // dd($request->all());
        $searchTerm = $request->search_text;
        $results = Account::select('id','name')
        ->where('name', 'LIKE', '%' . $searchTerm . '%')
        ->get();

        return response()->json(['result' => $results, 'status' => true]);
    }
}
