<?php
include_once(dirname( __FILE__ )  . '/../../classes/ChilexpressOficialProductMeta.php'); // NOSONAR
include_once(dirname( __FILE__ )  . '/../../chilexpress_oficial_api.php'); // NOSONAR
class Chilexpress_OficialAjaxModuleFrontController extends ModuleFrontController
{
 
    public function initContent()
    {
        $this->ajax = true;
        $this->api = new Chilexpress_Oficial_API();
        // your code here
        parent::initContent();
    }

    public function displayAjax() // NOSONAR
    {   
        $CONSTANT_ACTION = "action";
        $CONSTANT_ORDER_ID = "order_id";
    	header('Content-Type: application/json');
    	$action = 'obtener_regiones';
    	if (isset($_POST[$CONSTANT_ACTION])) {
    		$action = $_POST[$CONSTANT_ACTION];
    	}

    	switch ($action) {

            case 'get_tracking_code_from_reference':

                $references = array();
                if (isset($_POST['references'])) {
                    $references = $_POST['references'];
                }

                $orders = new PrestaShopCollection('Order');
                $orders->where('reference', 'in', $references);

                $response = array();

                foreach ($orders as $order) {
                    if ($this->context->customer->id == $order->id_customer) {
                        $response[$order->reference] = array(
                                'tracking' => $order->getWsShippingNumber(), $CONSTANT_ORDER_ID => $order->id
                        );
                    }
                }
                


                die(json_encode( array( $CONSTANT_ACTION => $action, 'response' => $response, "default" => "ok")));

            break;
            case 'track_order':
                $order_id = "0";
                $tracking_code = "";
                if (isset($_POST[$CONSTANT_ORDER_ID])) {
                    $order_id = $_POST[$CONSTANT_ORDER_ID];
                }
                if (isset($_POST["tracking_code"])) {
                    $tracking_code = $_POST["tracking_code"];
                }

                $order = new Order($order_id);
                $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                $transportOrderNumbers = explode(',', $order_carrier->tracking_number);

                if (!in_array($tracking_code, $transportOrderNumbers )) {
                    die(json_encode( 
                        array( 
                            $CONSTANT_ACTION => $action,
                            "tracking_code" => $tracking_code,
                            'error'=> "Tracking number Inválido"
                        )));
                }

                $response = $this->api->obtener_estado_ot(
                                                    $tracking_code,
                                                    "ORDEN-".$order_id,
                                                    intval(Configuration::get('rut_marketplace_remitente'))
                                                ); 
                
                die(json_encode(
                    array(
                        $CONSTANT_ACTION => $action,
                        "tracking_code" => $tracking_code,
                        "response"=>$response
                    )));
                
            break;
    		case 'obtener_regiones':
				die(json_encode( array( $CONSTANT_ACTION => $action, "regiones" => $this->api->obtener_regiones() )));
    		break;
            case 'obtener_comunas_con_id':
                $region = "0";
                if (isset($_POST["region"])) {
                    $region = $_POST["region"];
                }
                $region_iso_sql = 'SELECT `iso_code` FROM `'._DB_PREFIX_.'state` WHERE `id_state` = '.intval($region);
                $result = Db::getInstance()->getRow($region_iso_sql);
                $region_iso = $result["iso_code"];
                
                die(json_encode(
                    array(
                        $CONSTANT_ACTION => $action,
                        "result" => $region_iso,
                        "comunas" => $this->api->obtener_comunas_desde_region($region_iso)
                    )));
            break;
    		case 'obtener_comunas':

				$region = "R1";
                $regiones = array(
                    "R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15","R16","RM"
                );

				if (isset($_POST["region"])) {
		    		$region = $_POST["region"];
                    if (in_array($region,$regiones)){
                        $region = $regiones[array_search($region, $regiones)];
                    }
		    	}

				die(json_encode(
                    array(
                        $CONSTANT_ACTION => $action,
                        "comunas" => $this->api->obtener_comunas_desde_region($region)
                    )));
    		break;
            case 'set_dimension':

                $product = new Product($_POST['product_id']);
                $product->height = $_POST['alto'];
                $product->width = $_POST['ancho'];
                $product->depth = $_POST['largo'];
                $product->weight = $_POST['peso'];

                $productMeta = new ChilexpressOficialProductMeta( (int) $_POST['product_id'] );
                $productMeta->id_product = (int) $_POST['product_id'];
                $productMeta->meta_key = '_service_ampm';
                $productMeta->meta_value = $_POST['service_ampm'];

                $update = true;

                if($_POST['service_ampm'] == 'true' && ($_POST['peso'] > 15 || $_POST['alto'] > 70 || $_POST['largo'] > 70 || $_POST['ancho'] > 70)) {
                    $update = false;
                }

                if( $update ) {
                    if( $product->save() && $productMeta->save() ) {
                        $status = 'success';
                        $response = 'Datos actualizados con exíto.!';
                    }
                    else{
                        $status = 'error';
                        $response = 'Disculpe, los datos no han sido actualizados.!';
                    }
                }
                else {

                    $status = 'error';
                    $response = 'El producto seleccionado supera las dimensiones y/o peso'.
                                'habilitadas para un servicio AMPM.';

                }
                
                die(json_encode( array( $CONSTANT_ACTION => $action, "status" => $status, "response" => $response )));
            break;
            case 'close_certificate':

                $payload = array(
                    "certificateNumber" => floatval($_POST['numero_ce']),
                    "certificateType"   => 1,
                    "dropNumber"        => 0
                );

                $response = $this->api->cerrar_certificado( json_encode($payload) );
                if( $response["closedCertificate"] != null ) {
                    $status = 'success';
                }
                else{
                    $status = 'error';
                    $response = 'Certificado no generado';
                }

                die(json_encode( array( $CONSTANT_ACTION => $action, "status" => $status, "response" => $response )));
            break;
    		default;
    			die(json_encode( array( $CONSTANT_ACTION => $action, "default" => "ok")));
    		break;
    	}        
    }
}