<?php

namespace App\Http\Controllers;

use App\Models\AccountingGroup;
use Illuminate\Http\Request;
use App\Models\PaymentMode;

class PaymentModesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:payment-mode-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = PaymentMode::with('getAccountingGroup')->paginate(10);

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

            $data = PaymentMode::when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where(function ($innerQuery) use ($search_query) {
                    $innerQuery->where('mode', 'like', '%' . $search_query . '%')
                                ->orWhere('status', 'like', '%' . $search_query . '%')
                                ->orWhereHas('getAccountingGroup', function ($groupQuery) use ($search_query) {
                                    $groupQuery->where('name', 'like', '%' . $search_query . '%');
                                });
                });
            })->paginate($sort_by);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = PaymentMode::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $groups = AccountingGroup::where('is_payment_mode',1)->get();

        return view('payment-modes.create',compact('priority','groups'));
    }

    /**
     * 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(), [
            'mode'                => 'required|unique:payment_modes',
            'accounting_group_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 = PaymentMode::where(['is_default' => 1,'status' => 1])->first();

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

        $category = PaymentMode::create($data);

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

        return redirect()->route('payment-modes.index')->with('success','Payment Mode 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)
    {
        $payment_modes = PaymentMode::find($id);
        $groups = AccountingGroup::where('is_payment_mode',1)->get();

        return view('payment-modes.edit',compact('payment_modes','groups'));
    }

    /**
     * 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(), [
            'mode'                => 'required|unique:payment_modes,mode,'.$id,
            'accounting_group_id' => 'required'
        ]);

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

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

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

        if (!$paymentMode) {
            return redirect()->route('payment-modes.index')
                ->with('error','Payment Mode not found!');
        }

        $paymentMode->update($data);

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

        return redirect()->route('payment-modes.index')
            ->with('success','Payment Mode updated successfully');
    }

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

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

        $data->delete();

        $Redirect = 'payment-modes';

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

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

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

    //         $groups_cash = AccountingGroup::where('name','Cash in Hand')->first();
    //         $groups = AccountingGroup::where('name','Bank Account')->first();

    //         $data  = array('is_default' => $request->status );
    //         $count = PaymentMode::where(['is_default' => $request->status])->count();

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

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

    //         if($Update){
    //             return response()->json([
    //                 'success'=>true,
    //                 'message'=>['Payment Mode default status successfully changed.'],
    //                 'data'=>[
    //                    'redirect'=>'/users/',
    //                    'reload'=>true,
    //                 ]
    //             ]);
    //         } else {
    //             return response()->json([
    //                'success'=>false,
    //                'message'=>['Error for change default'],
    //                'data'=>[
    //                    'redirect'=>'',
    //                ]
    //             ]);
    //         }
    //     }
    // }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $paymentMode = PaymentMode::find($request->id);

            $groupsCash = AccountingGroup::where('name', 'Cash in Hand')->first();

            $groupsBank = AccountingGroup::where('name', 'Bank Account')->first();

            $existingDefault = PaymentMode::where([
                'accounting_group_id' => $paymentMode->accounting_group_id,
                'is_default' => 1,
            ])->first();

            $isDifferentGroup = ($groupsCash->id !== $groupsBank->id);

            if (($isDifferentGroup && $request->status == 1 && !$existingDefault) || ($request->status == 0)) {
                $data = array('is_default' => $request->status);
                $update = $paymentMode->update($data);

                if ($update) {
                    return response()->json([
                        'success' => true,
                        'message' => ['Payment Mode default status successfully changed.'],
                        'data'    => [
                            'redirect' => '/users/',
                            'reload'   => true,
                        ]
                    ]);
                }
            }

            return response()->json([
                'success' => false,
                'message' => ['Error for changing default'],
                'data'    => [
                    'redirect' => '',
                ]
            ]);
        }
    }


}
