<?php

namespace Dashboard\Controllers\Settings;

use Curl\Curl;
use Dashboard\Core\Controller;
use Dashboard\Core\Redirect;

class ApiController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SETTINGS');
    }

    public function index()
    {
        return view('settings.api.index');
    }

    public function regenerateApiKey()
    {
        if (get('code')) {
          $curl = new Curl();
          $curl->setHeader('Content-Type', 'application/json');
	        $curl->setHeader('Accept', 'application/json');
          $curl->post("https://connect-api.leaderos.net/api/api-keys/verify-code", [
            "code"      => get('code'),
            "location"  => LOCATION,
          ]);
          $redirect = new Redirect(url('dashboard.settings.api.index'));
          if (isset($curl->response->apiKey)) {
            updateSetting('apiKey', $curl->response->apiKey);
            createLog("API_SETTINGS_UPDATED");

            return $redirect->flash("success", t__('Changes has been saved successfully!'));
          }
          else {
            return $redirect->flash("error", t__('Error!'));
          }
        }

        redirect(leaderosWebsiteUrl() . '/api-keys/regenerate?domain=' . getDomain($_SERVER['HTTP_HOST']));
    }

    public function toggle()
    {
      updateSetting('apiStatus', settings('apiStatus') == '0' ? '1' : '0');

      response()->json([
        'status' => 'success',
        'message' => settings('apiStatus') == '0' ? t__('API enabled successfully!') : t__('API disabled successfully!')
      ]);
    }
}