<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CompanyBank;

class CompanyBanksController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:company-bank-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 = CompanyBank::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('company-banks.create', compact('id','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(), [
            'company_id'          => 'required',
            'ifsc_code'          => 'required',
            'bank_name'          => 'required',
            'account_holder_name' => 'required',
            'account_number'      => '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'
        ]);

        $count = CompanyBank::where(['company_id' => $request->company])->count();

        if ($count == 0) {
            $data['is_default'] = '1';
        }

        $quality = CompanyBank::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bank details has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Bank details has been 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)
    {
        $bank = CompanyBank::find($id);

        return view('company-banks.edit', compact('bank'));
    }

    /**
     * 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(), [
            'account_holder_name' => 'required',
            'ifsc_code'          => 'required',
            'bank_name'          => 'required',
            'account_number'      => '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'
        ]);

        $bank = CompanyBank::find($id);

        if (!$bank) {
            return redirect()->back()
                ->with('error','Company Bank not found!');
        }

        $bank->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Bank details has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Bank details has been updated successfully');
    }

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

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

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

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Company Bank 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 = CompanyBank::where(['is_default' => $request->status,'company_id'=> $request->company])->count();

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

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

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