<?php
require_once APPPATH . 'modules/advancedreports/services/InventoryAPIService.php';
require_once APPPATH . 'modules/advancedreports/helpers/InputDataHelper.php';

/**
 * Class Inventory
 */
class Inventory extends Cf_Controller
{
    /** @var null */
    private $username = null;

    public function __construct()
    {
        parent::__construct();
        if (CLI === false) {
            $this->username = $this->session->userdata('username');
        }
    }

    /**
     * Get variables
     */
    public function variables()
    {
        $inventoryAPIService = new InventoryAPIService($this->getRestClient());
        respond_ok($inventoryAPIService->getVariables());
    }

    /**
     * Update variable dictionary
     * @param $id
     */
    public function update_variable($id)
    {
        $inventoryAPIService = new InventoryAPIService($this->getRestClient());
        $inputData = InputDataHelper::getFromJsonInput();
        respond_ok($inventoryAPIService->updateVariable($id, $inputData));
    }

    /**
     * Get inventory data
     */
    public function data()
    {
        try {
            $inventoryAPIService = new InventoryAPIService($this->getRestClient());
            $inputData = InputDataHelper::getFromJsonInput();
            $data = json_decode($inventoryAPIService->getData($inputData), JSON_OBJECT_AS_ARRAY);
            if (
                isset($GLOBALS['CF_HOOKS']['beforeSQLOutput']) &&
                is_array($GLOBALS['CF_HOOKS']['beforeSQLOutput']) &&
                count($GLOBALS['CF_HOOKS']['beforeSQLOutput'])
            ) {
                foreach ($GLOBALS['CF_HOOKS']['beforeSQLOutput'] as $callback) {
                    $this->load->hookload($this, $callback[0]);
                    $data = $this->{$callback[0]}->{$callback[1]}($this, $data);
                }
            }
            respond_ok(json_encode($data));
        } catch (Exception $exception) {
            respond_internal_error($exception->getMessage());
        }
    }
}
