<?php
/**
 * voucher_admin.php
 *
 * Voucher 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 ControllerRestVoucherAdmin extends RestAdminController {

    /*
    * Get vouchers
    */
    public function listVouchers($request) {

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

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

        $parameters = array(
            "limit" => $this->config->get('config_limit_admin'),
            "start" => 1,
        );

        /*check limit parameter*/
        if (isset($request->get['limit']) && ctype_digit($request->get['limit'])) {
            $parameters["limit"] = $request->get['limit'];
        }

        /*check page parameter*/
        if (isset($request->get['page']) && ctype_digit($request->get['page'])) {
            $parameters["start"] = $request->get['page'];
        }

        $parameters["start"] = ($parameters["start"] - 1) * $parameters["limit"];

        $vouchers = array();

        $results = $this->model_rest_restadmin->getVouchers($parameters);

        foreach ($results as $result) {
            $vouchers[] = array(
                'voucher_id' => $result['voucher_id'],
                'code'       => $result['code'],
                'from'       => $result['from_name'],
                'to'         => $result['to_name'],
                'theme'      => $result['theme'],
                'amount'     => $this->currency->format($result['amount'], $this->config->get('config_currency')),
                'status'     => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
            );
        }


        if (empty($vouchers)) {
            $json['error'] = "No voucher found";
        } else {
            $json['success'] = true;
            $json['data'] = $vouchers;
        }

        $this->sendResponse($json);
    }

    /*
    * delete voucher
    {
        "vouchers": [8, 9]
    }
    */
    public function deleteVoucher($post) {

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

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

        if (isset($post['vouchers'])) {
            foreach ($post['vouchers'] as $voucher_id) {
                $this->model_rest_restadmin->deleteVoucher($voucher_id);
            }
        } else {
            $json['error'] = "Error";
            $json["success"] = false;
        }

        $this->sendResponse($json);
    }

    public function addVoucher($post) {

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

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

        $error = $this->validateForm($post);

        if (!empty($post) && empty($error)) {
            $retval  =$this->model_rest_restadmin->addVoucher($post);
            $json["data"]["id"] = $retval;
        } else {
            $json['error'] = $error;
            $json["success"] = false;
        }

        $this->sendResponse($json);
    }

    public function editVoucher($id, $post) {

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

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

        $data = $this->model_rest_restadmin->getVoucher($id);

        $error = $this->validateForm($post, $id);

        if (!empty($post) && empty($error)) {
            $post = array_merge($data, $post);
             $this->model_rest_restadmin->editVoucher($id, $post);
        } else {
            $json['error'] = $error;
            $json["success"] = false;
        }

        $this->sendResponse($json);
    }

    protected function validateForm($post, $voucher_id=null) {
        $this->load->model('rest/restadmin');
        $error  = array();

        if ((utf8_strlen($post['code']) < 3) || (utf8_strlen($post['code']) > 10)) {
            $error['code'] = $this->language->get('error_code');
        }

        $voucher_info = $this->model_rest_restadmin->getVoucherByCode($post['code']);

        if ($voucher_info) {
            if (empty($voucher_id)) {
                $error['warning'] = $this->language->get('error_exists');
            } elseif ($voucher_info['voucher_id'] != $voucher_id)  {
                $error['warning'] = $this->language->get('error_exists');
            }
        }

        if ((utf8_strlen($post['to_name']) < 1) || (utf8_strlen($post['to_name']) > 64)) {
            $error['to_name'] = $this->language->get('error_to_name');
        }

        if ((utf8_strlen($post['to_email']) > 96) || !preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $post['to_email'])) {
            $error['to_email'] = $this->language->get('error_email');
        }

        if ((utf8_strlen($post['from_name']) < 1) || (utf8_strlen($post['from_name']) > 64)) {
            $error['from_name'] = $this->language->get('error_from_name');
        }

        if ((utf8_strlen($post['from_email']) > 96) || !preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $post['from_email'])) {
            $error['from_email'] = $this->language->get('error_email');
        }

        if ($post['amount'] < 1) {
            $error['amount'] = $this->language->get('error_amount');
        }

        return $error;
    }

    /*
    * VOUCHER FUNCTIONS
    * index.php?route=rest/voucher_admin/vouchers
    */
    public function vouchers() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $this->listVouchers($this->request);

        } else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson)) {
                $this->addVoucher($requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        } else if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);

            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])
                && !empty($requestjson)) {
                $this->editVoucher($this->request->get['id'], $requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        } else if ( $_SERVER['REQUEST_METHOD'] === 'DELETE' ){
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson) && isset($requestjson["vouchers"])) {
                $this->deleteVoucher($requestjson);
            }else {
                $this->sendResponse(array('success' => false));
            }
        }
    }
    /*
    * VOUCHERTHEME FUNCTIONS
    * index.php?route=rest/voucher_admin/voucherthemes
    */
    public function voucherthemes() {

        $this->checkPlugin();

        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            $this->listVoucherThemes();

        }
    }

    /*
    * Get voucherthemes
    */
    public function listVoucherThemes() {
        $this->load->model('rest/restadmin');
        $json['success'] = true;
        $json['data'] = $this->model_rest_restadmin->getVoucherThemes();
        $this->sendResponse($json);
    }
}