public function ajaxProcessAddProductOnOrder()
 {
     // Load object
     $order = new Order((int) Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.'))));
     }
     $old_cart_rules = Context::getContext()->cart->getCartRules();
     if ($order->hasBeenShipped()) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. '))));
     }
     $product_informations = $_POST['add_product'];
     if (isset($_POST['add_invoice'])) {
         $invoice_informations = $_POST['add_invoice'];
     } else {
         $invoice_informations = array();
     }
     $product = new Product($product_informations['product_id'], false, $order->id_lang);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     $feature_duration = Configuration::get('APH_FEATURE_DURATION');
     $services_duration = json_decode(Configuration::get('APH_SERVICES_DURATION'), true);
     // duration event
     $features = $product->getFeatures();
     foreach ($features as &$feature) {
         if ($feature_duration == $feature['id_feature']) {
             $product_informations['duration'] = (int) $services_duration[$feature['id_feature_value']];
         }
     }
     if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) {
         $combination = new Combination($product_informations['product_attribute_id']);
         if (!Validate::isLoadedObject($combination)) {
             die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.'))));
         }
     }
     // Total method
     $total_method = Cart::BOTH_WITHOUT_SHIPPING;
     // Create new cart
     $cart = new Cart();
     $cart->id_shop_group = $order->id_shop_group;
     $cart->id_shop = $order->id_shop;
     $cart->id_customer = $order->id_customer;
     $cart->id_carrier = $order->id_carrier;
     $cart->id_address_delivery = $order->id_address_delivery;
     $cart->id_address_invoice = $order->id_address_invoice;
     $cart->id_currency = $order->id_currency;
     $cart->id_lang = $order->id_lang;
     $cart->secure_key = $order->secure_key;
     // Save new cart
     $cart->add();
     // Save context (in order to apply cart rule)
     $this->context->cart = $cart;
     $this->context->customer = new Customer($order->id_customer);
     // always add taxes even if there are not displayed to the customer
     $use_taxes = true;
     $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
     // Creating specific price if needed
     if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) {
         $specific_price = new SpecificPrice();
         $specific_price->id_shop = 0;
         $specific_price->id_shop_group = 0;
         $specific_price->id_currency = 0;
         $specific_price->id_country = 0;
         $specific_price->id_group = 0;
         $specific_price->id_customer = $order->id_customer;
         $specific_price->id_product = $product->id;
         if (isset($combination)) {
             $specific_price->id_product_attribute = $combination->id;
         } else {
             $specific_price->id_product_attribute = 0;
         }
         $specific_price->price = $product_informations['product_price_tax_excl'];
         $specific_price->from_quantity = 1;
         $specific_price->reduction = 0;
         $specific_price->reduction_type = 'amount';
         $specific_price->reduction_tax = 0;
         $specific_price->from = '0000-00-00 00:00:00';
         $specific_price->to = '0000-00-00 00:00:00';
         $specific_price->add();
     }
     // Add product to cart
     $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop));
     /*if ($update_quantity < 0) {
           // If product has attribute, minimal quantity is set with minimal quantity of attribute
           $minimal_quantity = ($product_informations['product_attribute_id']) ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity;
           die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity))));
       } elseif (!$update_quantity) {
           die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false))));
       }*/
     // If order is valid, we can create a new invoice or edit an existing invoice
     if (false && $order->hasInvoice()) {
         $order_invoice = new OrderInvoice($product_informations['invoice']);
         // Create new invoice
         if ($order_invoice->id == 0) {
             // If we create a new invoice, we calculate shipping cost
             $total_method = Cart::BOTH;
             // Create Cart rule in order to make free shipping
             if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) {
                 $cart_rule = new CartRule();
                 $cart_rule->id_customer = $order->id_customer;
                 $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping'));
                 $cart_rule->date_from = date('Y-m-d H:i:s', time());
                 $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600);
                 $cart_rule->quantity = 1;
                 $cart_rule->quantity_per_user = 1;
                 $cart_rule->minimum_amount_currency = $order->id_currency;
                 $cart_rule->reduction_currency = $order->id_currency;
                 $cart_rule->free_shipping = true;
                 $cart_rule->active = 1;
                 $cart_rule->add();
                 // Add cart rule to cart and in order
                 $cart->addCartRule($cart_rule->id);
                 $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false));
                 $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values);
             }
             $order_invoice->id_order = $order->id;
             if ($order_invoice->number) {
                 Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop);
             } else {
                 $order_invoice->number = Order::getLastInvoiceNumber() + 1;
             }
             $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
             $carrier = new Carrier((int) $order->id_carrier);
             $tax_calculator = $carrier->getTaxCalculator($invoice_address);
             $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false);
             $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost();
             $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method;
             // Update current order field, only shipping because other field is updated later
             $order->total_shipping += $order_invoice->total_shipping_tax_incl;
             $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl;
             $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl;
             $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->add();
             $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
             $order_carrier = new OrderCarrier();
             $order_carrier->id_order = (int) $order->id;
             $order_carrier->id_carrier = (int) $order->id_carrier;
             $order_carrier->id_order_invoice = (int) $order_invoice->id;
             $order_carrier->weight = (double) $cart->getTotalWeight();
             $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->add();
         } else {
             $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->update();
         }
     }
     // Create Order detail information
     $order_detail = new AphOrderDetail();
     $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse'));
     if ($product_informations['delivery_date'] != '') {
         $order_detail->id_employee = (int) $product_informations['id_employee'];
         $order_detail->delivery_date = $product_informations['delivery_date'];
         $order_detail->delivery_time_from = $product_informations['delivery_time_from'];
         if (!empty($product_informations['duration'])) {
             $time = new DateTime($order_detail->delivery_date . ' ' . $order_detail->delivery_time_from);
             $time->add(new DateInterval('PT' . $product_informations['duration'] . 'M'));
             $time_to = $time->format('H:i');
             if ($time_to > $product_informations['delivery_time_to']) {
                 $product_informations['delivery_time_to'] = $time_to;
             }
         }
         $order_detail->delivery_time_to = $product_informations['delivery_time_to'];
         $order_detail->update();
     }
     // update totals amount of order
     $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
     $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
     $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
     $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
     $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
     if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
         $order->total_shipping = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
     }
     // discount
     $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     // Save changes of order
     $order->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         if ($order_carrier->update()) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Update Tax lines
     $order_detail->updateTaxAmount($order);
     // Delete specific price if exists
     if (isset($specific_price)) {
         $specific_price->delete();
     }
     $products = $this->getProducts($order);
     // Get the last product
     $product = end($products);
     $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
         $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
         if (!empty($warehouse_location)) {
             $product['warehouse_location'] = $warehouse_location;
         } else {
             $product['warehouse_location'] = false;
         }
     } else {
         $product['warehouse_name'] = '--';
         $product['warehouse_location'] = false;
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         /** @var OrderInvoice $invoice */
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     $this->sendChangedNotification($order);
     $new_cart_rules = Context::getContext()->cart->getCartRules();
     sort($old_cart_rules);
     sort($new_cart_rules);
     $result = array_diff($new_cart_rules, $old_cart_rules);
     $refresh = false;
     $res = true;
     foreach ($result as $cart_rule) {
         $refresh = true;
         // Create OrderCartRule
         $rule = new CartRule($cart_rule['id_cart_rule']);
         $values = array('tax_incl' => $rule->getContextualValue(true), 'tax_excl' => $rule->getContextualValue(false));
         $order_cart_rule = new OrderCartRule();
         $order_cart_rule->id_order = $order->id;
         $order_cart_rule->id_cart_rule = $cart_rule['id_cart_rule'];
         $order_cart_rule->id_order_invoice = $order_invoice->id;
         $order_cart_rule->name = $cart_rule['name'];
         $order_cart_rule->value = $values['tax_incl'];
         $order_cart_rule->value_tax_excl = $values['tax_excl'];
         $res &= $order_cart_rule->add();
         $order->total_discounts += $order_cart_rule->value;
         $order->total_discounts_tax_incl += $order_cart_rule->value;
         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
         $order->total_paid -= $order_cart_rule->value;
         $order->total_paid_tax_incl -= $order_cart_rule->value;
         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
     }
     // Update Order
     $res &= $order->update();
     die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch(), 'refresh' => $refresh)));
 }
    public function ajaxProcessSaveOrder()
    {
        $products = Tools::getValue('products');
        $delivery_date = Tools::getValue('delivery_date');
        $delivery_time_from = Tools::getValue('delivery_time_from');
        $delivery_time_to = Tools::getValue('delivery_time_to');
        $id_employee = Tools::getValue('employees');
        if (!empty($id_employee) && is_array($id_employee)) {
            $id_employee = $id_employee[0];
        }
        $other = Tools::getValue('other');
        if (empty($products)) {
            PrestaShopLogger::addLog('AphCalendar::saveOrder - Products to be select', 1, null, 'AphCalendar', 0, true);
            die(Tools::jsonEncode(array('result' => false, 'error' => 'Non e\' stato selezionato nessun prodotto. Prego selezionarle almeno uno.')));
        }
        $id_customer = (int) Tools::getValue('id_customer');
        if ($id_customer < 1) {
            $customer = new Customer();
            $customer->firstname = Tools::getValue('firstname');
            $customer->lastname = Tools::getValue('lastname');
            $customer->email = Tools::getValue('email');
            $customer->phone = Tools::getValue('phone');
            $customer->id_gender = Tools::getValue('id_gender');
            $customer->id_shop = (int) Context::getContext()->shop->id;
            $customer->passwd = strtoupper(Tools::passwdGen(10));
            $customer->newsletter = 1;
            if ($customer->validateFields(false, true) !== true) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of customer not valid', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.')));
            }
            $result = $customer->add();
            if (!$result) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Address of customer is to be added', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.')));
            }
            $stores = Db::getInstance()->executeS('
			SELECT st.id_country,st.id_state,st.city
			FROM ' . _DB_PREFIX_ . 'store_shop ss
			LEFT JOIN `' . _DB_PREFIX_ . 'store` st 
				ON (ss.`id_store` = st.`id_store`)
			WHERE ss.`id_shop` = ' . (int) Context::getContext()->shop->id);
            $address = new Address();
            $address->id_customer = $customer->id;
            $address->alias = 'indirizzo';
            $address->firstname = $customer->firstname;
            $address->lastname = $customer->lastname;
            $address->address1 = '-';
            $address->postcode = '00000';
            $address->phone = $customer->phone;
            $address->phone_mobile = $customer->phone;
            $address->id_country = $stores[0]['id_country'];
            $address->id_state = $stores[0]['id_state'];
            $address->city = $stores[0]['city'];
            if ($address->validateFields(false, true) !== true) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of address of customer not valid', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.')));
            }
            $address->add();
            $customer->id_address_delivery = $address->id;
            $customer->id_address_invoice = $address->id;
            if (!$result) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Customer is to be added', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.')));
            }
            $id_customer = $customer->id;
        } else {
            $customer = new Customer($id_customer);
            $customer->firstname = Tools::getValue('firstname');
            $customer->lastname = Tools::getValue('lastname');
            $customer->email = Tools::getValue('email');
            $customer->phone = Tools::getValue('phone');
            $customer->id_gender = Tools::getValue('id_gender');
            $customer->id_shop = (int) Context::getContext()->shop->id;
            $customer->update();
            $addresses = $customer->getAddresses((int) Context::getContext()->language->id);
            if (empty($addresses)) {
                $customer->id_address_delivery = $customer->id_address_invoice = 0;
            } else {
                $customer->id_address_delivery = $addresses[0]['id_address'];
                $customer->id_address_invoice = $addresses[0]['id_address'];
                $address = new Address($addresses[0]['id_address'], (int) Context::getContext()->language->id);
                $address->firstname = $customer->firstname;
                $address->lastname = $customer->lastname;
                $address->phone = $customer->phone;
                $address->phone_mobile = $customer->phone;
                $address->update();
            }
        }
        $id_order = (int) Tools::getValue('id_order');
        $feature_duration = Configuration::get('APH_FEATURE_DURATION');
        $services_duration = json_decode(Configuration::get('APH_SERVICES_DURATION'), true);
        $reservation_offline_status = Configuration::get('APH_RESERVATION_OFFLINE_STATUS');
        // always add taxes even if there are not displayed to the customer
        $use_taxes = true;
        // Total method
        $total_method = Cart::BOTH_WITHOUT_SHIPPING;
        //TODO ajaxProcessAddProductOnOrder() in AdminOrdersController
        if ($id_order < 1) {
            do {
                $reference = Order::generateReference();
            } while (Order::getByReference($reference)->count());
            $order = new Order();
            $order->id_customer = (int) $customer->id;
            $order->secure_key = $customer->secure_key;
            $order->id_address_invoice = $customer->id_address_delivery;
            $order->id_address_delivery = $customer->id_address_invoice;
            $order->id_currency = (int) Context::getContext()->currency->id;
            $order->id_lang = (int) Context::getContext()->language->id;
            $order->reference = $reference;
            $order->id_shop = (int) Context::getContext()->shop->id;
            $order->id_shop_group = (int) Context::getContext()->shop->id_shop_group;
            $order->id_cart = 0;
            $order->id_carrier = 0;
            $order->payment = 'Pagamento alla consegna';
            $order->module = 'cashondelivery';
            $order->total_paid = 0;
            $order->total_paid_real = 0;
            $order->total_products = 0;
            $order->total_products_wt = 0;
            $order->conversion_rate = 1;
            $order->delivery_number = 1;
            $order->delivery_date = $delivery_date . ' ' . $delivery_time_from;
            $order->current_state = $reservation_offline_status;
            if ($order->validateFields(false, true) !== true) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of order not valid', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione dell\'appuntamento. Prego riprovare.')));
            }
            $result = $order->add();
            if (!$result) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Order is about to be added', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione dell\'appuntamento. Prego riprovare.')));
            }
            // Create new cart
            $cart = new Cart();
            $cart->id_shop_group = $order->id_shop_group;
            $cart->id_shop = $order->id_shop;
            $cart->id_customer = $order->id_customer;
            $cart->id_carrier = $order->id_carrier;
            $cart->id_address_delivery = $order->id_address_delivery;
            $cart->id_address_invoice = $order->id_address_invoice;
            $cart->id_currency = $order->id_currency;
            $cart->id_lang = $order->id_lang;
            $cart->secure_key = $order->secure_key;
            // Save new cart
            $cart->add();
            // Save context (in order to apply cart rule)
            $this->context->cart = $cart;
            $this->context->customer = new Customer($order->id_customer);
            // calculate prices of products
            $products_detail = array();
            foreach ($products as &$product_id) {
                $product = new Product($product_id, false, $order->id_lang, $order->id_shop);
                $products_detail[$product_id] = array();
                $products_detail[$product_id]['id'] = $products_detail[$product_id]['id_product'] = $product_id;
                $products_detail[$product_id]['name'] = $product->name;
                $products_detail[$product_id]['ean13'] = $product->ean13;
                $products_detail[$product_id]['upc'] = $product->upc;
                $products_detail[$product_id]['reference'] = $product->reference;
                $products_detail[$product_id]['cart_quantity'] = 1;
                $products_detail[$product_id]['id_product_attribute'] = 0;
                $products_detail[$product_id]['id_shop'] = $order->id_shop;
                $products_detail[$product_id]['id_supplier'] = 0;
                $products_detail[$product_id]['weight'] = $product->weight;
                $products_detail[$product_id]['height'] = $product->height;
                $products_detail[$product_id]['depth'] = $product->depth;
                $products_detail[$product_id]['ecotax'] = $product->ecotax;
                $products_detail[$product_id]['price_without_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                $products_detail[$product_id]['price_with_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                $products_detail[$product_id]['price'] = $products_detail[$product_id]['price_with_reduction_without_tax'] = Product::getPriceStatic((int) $product_id, false, $products_detail[$product_id]['id_product_attribute'], 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                switch (Configuration::get('PS_ROUND_TYPE')) {
                    case Order::ROUND_TOTAL:
                        $products_detail[$product_id]['total'] = $products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'];
                        $products_detail[$product_id]['total_wt'] = $products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'];
                        break;
                    case Order::ROUND_LINE:
                        $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                        $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                        break;
                    case Order::ROUND_ITEM:
                    default:
                        $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity'];
                        $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity'];
                        break;
                }
                $products_detail[$product_id]['price_wt'] = $products_detail[$product_id]['price_with_reduction'];
                $products_detail[$product_id]['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
                $products_detail[$product_id]['wholesale_price'] = $product->wholesale_price;
                $products_detail[$product_id]['additional_shipping_cost'] = $product->additional_shipping_cost;
                // Add product to cart
                $update_quantity = $cart->updateQty($products_detail[$product_id]['cart_quantity'], $product->id, $products_detail[$product_id]['id_product_attribute'], null, 'up', 0, new Shop($cart->id_shop));
                $order_detail = new AphOrderDetail();
                $order_detail->createList($order, $cart, $order->current_state, array($products_detail[$product_id]), 0, $use_taxes, 0);
                // update totals amount of order
                $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
                $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
                $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
                $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
                $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
                // discount
                $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
                $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
                $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
                // Save changes of order
                $order->id_cart = $cart->id;
                $order->update();
                // Update Tax lines
                $order_detail->updateTaxAmount($order);
                // duration event
                $features = $product->getFeatures();
                foreach ($features as &$feature) {
                    if ($feature_duration == $feature['id_feature']) {
                        $products_detail[$product_id]['duration'] = (int) $services_duration[$feature['id_feature_value']];
                    }
                }
                $order_detail->id_employee = $id_employee;
                $order_detail->delivery_date = $delivery_date;
                $order_detail->delivery_time_from = $delivery_time_from;
                if (!empty($products_detail[$product_id]['duration'])) {
                    $time = new DateTime($delivery_date . ' ' . $delivery_time_from);
                    $time->add(new DateInterval('PT' . $products_detail[$product_id]['duration'] . 'M'));
                    $time_to = $time->format('H:i');
                    if ($time_to > $delivery_time_to) {
                        $delivery_time_to = $time_to;
                    }
                }
                $order_detail->delivery_time_to = $delivery_time_to;
                $order_detail->note = $other;
                $order_detail->update();
            }
        } else {
            $order = new Order($id_order);
            $order->id_customer = (int) $customer->id;
            $order->secure_key = $customer->secure_key;
            $order->id_address_invoice = $customer->id_address_delivery;
            $order->id_address_delivery = $customer->id_address_invoice;
            $order->id_currency = (int) Context::getContext()->currency->id;
            $order->id_lang = (int) Context::getContext()->language->id;
            $order->total_paid = 0;
            $order->total_paid_real = 0;
            $order->total_products = 0;
            $order->total_products_wt = 0;
            $order->conversion_rate = 1;
            $order->delivery_number = 1;
            $order->delivery_date = $delivery_date . ' ' . $delivery_time_from;
            if ($order->validateFields(false, true) !== true) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of order not valid', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante l\'aggiornamento dell\'appuntamento. Prego riprovare.')));
            }
            $result = $order->update();
            if (!$result) {
                PrestaShopLogger::addLog('AphCalendar::saveOrder - Order is about to be added', 1, null, 'AphCalendar', 0, true);
                die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante l\'aggiornamento dell\'appuntamento. Prego riprovare.')));
            }
            // Create new cart
            $cart = new Cart($order->id_cart);
            // Save context (in order to apply cart rule)
            $this->context->cart = $cart;
            $this->context->customer = new Customer($order->id_customer);
            $id_order_detail = Tools::getValue('id_order_detail');
            $order_detail = new AphOrderDetail($id_order_detail);
            if (empty($products_detail[$order_detail->product_id])) {
                $order_detail->delete();
            }
            // calculate prices of products
            $products_detail = array();
            $is_to_update = false;
            foreach ($products as &$product_id) {
                $is_to_update = $product_id == $order_detail->product_id;
                $product = new Product($product_id, false, $order->id_lang, $order->id_shop);
                $products_detail[$product_id] = array();
                $products_detail[$product_id]['id'] = $products_detail[$product_id]['id_product'] = $product_id;
                $products_detail[$product_id]['name'] = $product->name;
                $products_detail[$product_id]['ean13'] = $product->ean13;
                $products_detail[$product_id]['upc'] = $product->upc;
                $products_detail[$product_id]['reference'] = $product->reference;
                $products_detail[$product_id]['cart_quantity'] = 1;
                $products_detail[$product_id]['id_product_attribute'] = 0;
                $products_detail[$product_id]['id_shop'] = $order->id_shop;
                $products_detail[$product_id]['id_supplier'] = 0;
                $products_detail[$product_id]['weight'] = $product->weight;
                $products_detail[$product_id]['height'] = $product->height;
                $products_detail[$product_id]['depth'] = $product->depth;
                $products_detail[$product_id]['ecotax'] = $product->ecotax;
                $products_detail[$product_id]['price_without_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                $products_detail[$product_id]['price_with_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                $products_detail[$product_id]['price'] = $products_detail[$product_id]['price_with_reduction_without_tax'] = Product::getPriceStatic((int) $product_id, false, $products_detail[$product_id]['id_product_attribute'], 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context);
                switch (Configuration::get('PS_ROUND_TYPE')) {
                    case Order::ROUND_TOTAL:
                        $products_detail[$product_id]['total'] = $products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'];
                        $products_detail[$product_id]['total_wt'] = $products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'];
                        break;
                    case Order::ROUND_LINE:
                        $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                        $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                        break;
                    case Order::ROUND_ITEM:
                    default:
                        $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity'];
                        $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity'];
                        break;
                }
                $products_detail[$product_id]['price_wt'] = $products_detail[$product_id]['price_with_reduction'];
                $products_detail[$product_id]['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
                $products_detail[$product_id]['wholesale_price'] = $product->wholesale_price;
                $products_detail[$product_id]['additional_shipping_cost'] = $product->additional_shipping_cost;
                // Add product to cart
                $update_quantity = $cart->updateQty($products_detail[$product_id]['cart_quantity'], $product->id, $products_detail[$product_id]['id_product_attribute'], null, 'up', 0, new Shop($cart->id_shop));
                $order_detail = new AphOrderDetail();
                $order_detail->createList($order, $cart, $order->current_state, array($products_detail[$product_id]), 0, $use_taxes, 0);
                // update totals amount of order
                $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
                $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
                $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
                $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
                $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
                // discount
                $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
                $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
                $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
                // Save changes of order
                $order->id_cart = $cart->id;
                $order->update();
                // Update Tax lines
                $order_detail->updateTaxAmount($order);
                // duration event
                $features = $product->getFeatures();
                foreach ($features as &$feature) {
                    if ($feature_duration == $feature['id_feature']) {
                        $products_detail[$product_id]['duration'] = (int) $services_duration[$feature['id_feature_value']];
                    }
                }
                $order_detail->id_employee = $id_employee;
                $order_detail->delivery_date = $delivery_date;
                $order_detail->delivery_time_from = $delivery_time_from;
                if (!empty($products_detail[$product_id]['duration'])) {
                    $time = new DateTime($delivery_date . ' ' . $delivery_time_from);
                    $time->add(new DateInterval('PT' . $products_detail[$product_id]['duration'] . 'M'));
                    $time_to = $time->format('H:i');
                    if ($time_to > $delivery_time_to) {
                        $delivery_time_to = $time_to;
                    }
                }
                $order_detail->delivery_time_to = $delivery_time_to;
                $order_detail->note = $other;
                if ($is_to_update) {
                    $order_detail->update();
                } else {
                    $order_detail->add();
                }
            }
        }
        $send_memo = (bool) Tools::getValue('send_memo');
        if (!empty($send_memo)) {
            $shop = new AphStore($products_detail[$product_id]['id_shop']);
            $topic = 'Promemoria appuntamento';
            $data = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{product_name}' => $products_detail[$product_id]['name'], '{delivery_date}' => $order_detail->delivery_date, '{delivery_time_from}' => $order_detail->delivery_time_from, '{shop_name}' => $shop->name, '{shop_address}' => $shop->shop_address1 . (!empty($shop->shop_address2) ? ' ' . $shop->shop_address2 : ''), '{shop_city}' => $shop->shop_city, '{shop_link_rewrite}' => $shop->shop_link_rewrite, '{shop_phone}' => $shop->phone);
            if (Validate::isLoadedObject($order)) {
                !Mail::Send((int) $order->id_lang, 'order_memo', $topic, $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, false, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
            }
        }
        die(Tools::jsonEncode(array('result' => true)));
    }