<?php

namespace App\Http\Controllers\Accounts;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AccountPayment;
use App\Models\PaymentMode;

class AccountPaymentsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:account-payment-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $priority = AccountPayment::where('account_id', $id)->max('priority');
        $types    = PaymentMode::select(['id','is_default','mode'])->orderBy('priority', 'ASC')->get();
        $priority = $priority != '' ? $priority : 0;

        return view('account-payments.create', compact('id','types','priority'));
    }

    /**
     * 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(), [
            'account_id'      => 'required',
            'payment_mode_id' => 'required',
            'priority'        => '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 = AccountPayment::where(['is_default' => '1','status' => '1'])->first();

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

        AccountPayment::create($data);

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

        return redirect()->back()
            ->with('success','Account Payment 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 = AccountPayment::find($id);
        $types   = PaymentMode::select(['id','is_default','mode'])->orderBy('priority', 'ASC')->get();

        return view('account-payments.edit', compact('payment','types'));
    }

    /**
     * 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(), [
            'payment_mode_id' => 'required',
            'priority'        => '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'
        ]);

        $type = AccountPayment::find($id);

        if (!$type) {
            return redirect()->back()
                ->with('error','Address Payment not found!');
        }

        $type->update($data);

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

        return redirect()->back()
            ->with('success','Account Payment has been updated successfully');
    }

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

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

        $account->delete();

        $Redirect = 'accounts';

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

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

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Account Payment status successfully change'],
                   'data'=>[
                       'redirect'=>'/financialyear/',
                       '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 = AccountPayment::where(['is_default' => $request->status,'account_id'=> $request->account])->count();

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

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

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