<?php
/**
 * option_value_admin.php
 *
 * Option value management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    1.0
 * @link       http://opencart-api.com/product/opencart-rest-admin-api/
 * @see        http://webshop.opencart-api.com/rest-admin-api/
 */
require_once(DIR_SYSTEM . 'engine/restadmincontroller.php');

class ControllerRestOptionValueAdmin extends RestAdminController {

    private static $defaultFields = array(
        "option_value_description",
        "sort_order",
        "image",
    );

    private static $defaultFieldValues = array(
        "option_value_description"=>array()
    );
    /*
    * delete option values
    {
        "option_values": [8, 9 ]
    }
    */
    public function deleteOptionValue($post) {

        $json = array('success' => true);

        $this->load->model('rest/restadmin');

        if (isset($post['option_values'])) {
            foreach ($post['option_values'] as $option_value_id) {
                $this->model_rest_restadmin->deleteOptionValue($option_value_id);
            }
        } else {
            $json['error'] = "Empty request.";
            $json["success"] = false;
        }

        $this->sendResponse($json);
    }

    /*
    * Add option value
     *
      {
            "sort_order": 1,
            "option_value_description": [
                {
                    "language_id": 1,
                    "name": "Large"
                }
            ]
      }
    */
    public function addOptionValue($option_id,$post) {

        $json = array('success' => true);

        $this->load->model('rest/restadmin');

        if(!$this->model_rest_restadmin->isOptionExist($option_id)){
            $json['error'] = 'Option with id: '.$option_id. ' does not exist.';
            $json["success"] = false;
        } else {
            $error = $this->validateForm($post);

            if (!empty($post) && empty($error)) {
                foreach (self::$defaultFields as $field) {
                    if (!isset($post[$field])) {
                        if (!isset(self::$defaultFieldValues[$field])) {
                            $post[$field] = "";
                        } else {
                            $post[$field] = self::$defaultFieldValues[$field];
                        }
                    }
                }

                $optionError = array();
                foreach ($post['option_value_description'] as $option_value_description) {
                    if($this->model_rest_restadmin->isOptionValueNameExist($option_id, $option_value_description['name'], $option_value_description['language_id'])){
                        $optionError[] = $option_value_description['name'];
                    }
                }

                if(empty($optionError)){
                    $retval = $this->model_rest_restadmin->addOptionValue($option_id, $post);
                    $json["data"] = $retval;
                } else {
                    $json['error'] = 'Error.Invalid option value name(s): '.implode(',', $optionError);
                    $json["success"] = false;
                }

            } else {
                if(!empty($error)){
                    $json['error'] = $error;
                } else {
                    $json['error'] = 'Empty request.';
                }
                $json["success"] = false;
            }
        }

        $this->sendResponse($json);
    }

    /*
    * Edit option value
     *
      {
            "sort_order": 1,
            "option_value_description": [
                {
                    "language_id": 1,
                    "name": "Large updated"
                }
            ]
      }
    */
    public function editOptionValue($id, $post) {

        $json = array('success' => true);

        $this->load->model('rest/restadmin');
        if(!$this->model_rest_restadmin->isOptionValueExist($id)){
            $json['error'] = 'Option value with id: '.$id. ' does not exist.';
            $json["success"] = false;
        } else {
            $error = $this->validateForm($post);

            if (!empty($post) && empty($error)) {
                $this->model_rest_restadmin->editOptionValue($id, $post);
            } else {
                if(!empty($error)){
                    $json['error'] = $error;
                } else {
                    $json['error'] = 'Empty request.';
                }
                $json["success"] = false;
            }
        }

        $this->sendResponse($json);
    }
    protected function validateForm($post) {

        $error  = array();

        foreach ($post['option_value_description'] as $option_value_description) {
            if ((utf8_strlen($option_value_description['name']) < 1) || (utf8_strlen($option_value_description['name']) > 128)) {
                $error['name'][$option_value_description['language_id']] = 'Option value Name must be between 1 and 128 characters!';
            }
        }

        return $error;
    }
    /*
    * OPTION VALUE FUNCTIONS
    * index.php?route=rest/option_value_admin/optionvalue
    */
    public function optionvalue() {

        $this->checkPlugin();

        $inputData = file_get_contents('php://input');
        $requestjson = json_decode($inputData, true);

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->addOptionValue($this->request->get['id'], $requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        } else if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->editOptionValue($this->request->get['id'], $requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        } else if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){

            if (!empty($requestjson) && isset($requestjson["option_values"])) {
                $this->deleteOptionValue($requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        }
    }
}