<?php

namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Validator;
use App\NexmoSettings;

class NexmoSettingsController extends Controller
{
	
	public function index(Request $request)
    {
		
		$settings = NexmoSettings::where('company_id', $this->_getCompany()->id)->get();

        return response()->json($settings, 200);
		
    }

	public function store(Request $request)
    {
		
		$setting = $this->_save($request);
		
		if ($setting) {
			return response()->json([
				'title' => 'Nexmo Settings',
				'message' => 'Nexmo Settings was added successfully.',
				'object' => $setting
			], 201);
		} else {
			return response()->json([
				'title' => 'Nexmo Settings',
				'message' => 'It was not possible to add the Nexmo Settings.'
			], 500);
		}
		
    }
	
	public function update(Request $request, $id)
    {

		$setting = $this->_save($request, $id);

		if ($setting) {
			return response()->json([
				'title' => 'Nexmo Settings',
				'message' => 'Nexmo Settings was edited successfully.',
				'object' => $setting
			], 200);
		} else {
			return response()->json([
				'title' => 'Nexmo Settings',
				'message' => 'It was not possible to edit the Nexmo Settings.'
			], 500);
		}
	
    }
	
	private function _save(Request $request, $id = null) 
    {

		if ($id) {

			$setting = NexmoSettings::find($id);

			if (!$setting || $setting->company_id != $this->_getCompany()->id) {
				return response()->json([
					'title' => 'Nexmo Settings',
					'message' => 'Record not found',
				], 404);
			}

		} else {

			$setting = new NexmoSettings();
			
			$setting->created_at = date('Y-m-d H:i:s');

		}
		
		$setting->updated_at = date('Y-m-d H:i:s');
		$setting->company_id = $this->_getCompany()->id;
		$setting->virtual_number = $request->virtual_number;
		$setting->api_key = $request->api_key;
		$setting->api_secret = $request->api_secret;
		$setting->active = $request->active;

		if ($setting->save()) {
			return $setting;
		}

		return null;

    }

}
