<?php
class ControllerApiCart extends Controller {
	public function add() {
		$this->load->language('api/cart');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error']['warning'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->post['product'])) {
				$this->cart->clear();

				foreach ($this->request->post['product'] as $product) {
					if (isset($product['option'])) {
						$option = $product['option'];
					} else {
						$option = array();
					}
					if(!isset($product['quantity'])){
                        $product['quantity']=1;
                    }
                    $order_id = $this->request->get['order_id'];
					$this->load->model('checkout/order');

					$statuses = $this->model_checkout_order->getStatuses($product['product_id'], $product['date'], $product['quantity'], $order_id);
                    if(!empty($statuses)) {
					    $this->cart->add($product['product_id'], $product['quantity'], $option, 0, $product['date'], $statuses['customer'], $statuses['confirm'], $statuses['status']);
                    } else {
                        $this->cart->add($product['product_id'], $product['quantity'], $option, 0, $product['date']);
                    }
				}

				$json['success'] = $this->language->get('text_success');

				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
				unset($this->session->data['payment_method']);
				unset($this->session->data['payment_methods']);
			} elseif (isset($this->request->post['product_id'])) {
				$this->load->model('catalog/product');

				$product_info = $this->model_catalog_product->getProduct($this->request->post['product_id']);

				if ($product_info) {
					if (isset($this->request->post['quantity'])) {
						$quantity = $this->request->post['quantity'];
					} else {
						$quantity = 1;
					}

					if (isset($this->request->post['date'])) {
						$day = $this->request->post['date'];
					} else {
                        $day = false;
					}

					if (isset($this->request->post['date_end'])) {
						$day_end = $this->request->post['date_end'];
					} else {
                        $day_end = false;
					}

					if(isset($this->request->get['user_id'])) {
					    $user_id = $this->request->get['user_id'];
                    } else {
                        $user_id = 0;
                    }

					if (isset($this->request->post['option'])) {
						$option = array_filter($this->request->post['option']);
					} else {
						$option = array();
					}

                    $begin = new DateTime($day);
                    $end = new DateTime($day_end);
                    if($day==$day_end){
                        $end = $end->modify( '+1 day' );
                    }

                    $interval = new DateInterval('P1D');
                    $daterange = new DatePeriod($begin, $interval ,$end);

                    foreach($daterange as $date){
                        $tenure[] = ($date->format("Y-m-d"));
                    }

					$product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);

					foreach ($product_options as $product_option) {
						if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
							$json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
						}
					}

                    $comment_options = array();

					if (!isset($json['error']['option'])){
					    if($option && $product_options) {
                            foreach($option as $option_id => $option_val) {
                                foreach ($product_options as $prod_opt_id => $prod_opt_val) {
                                    if(($prod_opt_val['product_option_id'] == $option_id) && !is_array($option_val)) {
                                        foreach ($prod_opt_val['product_option_value'] as $final_option)
                                            if($final_option['product_option_value_id'] == $option_val) {
                                                $comment_options[$prod_opt_val['name']] = $final_option['name'];
                                            }
                                    } elseif (($prod_opt_val['product_option_id'] == $option_id) && is_array($option_val)) {
                                        foreach ($option_val as $opt_val) {
                                            foreach ($prod_opt_val['product_option_value'] as $final_option) {
                                                if($final_option['product_option_value_id'] == $opt_val) {
                                                    $comment_options[$prod_opt_val['name']][$opt_val] = $final_option['name'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

					    foreach ($tenure as $data_day) {
						$this->cart->add($this->request->post['product_id'], $quantity, $option, 0, $data_day, $user_id);
                            $this->session->data['added_order_info'][$data_day] = array(
                                'product_id' => $this->request->post['product_id'],
                                'options'    => $comment_options
                            );
					    }

						$json['success'] = $this->language->get('text_success');

						unset($this->session->data['shipping_method']);
						unset($this->session->data['shipping_methods']);
						unset($this->session->data['payment_method']);
						unset($this->session->data['payment_methods']);
					}
				} else {
					$json['error']['store'] = $this->language->get('error_store');
				}
			}
		}

        $this->session->data['product_action'] = 'add';

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function edit() {
		$this->load->language('api/cart');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			$this->cart->update($this->request->post['key'], $this->request->post['quantity']);

			$json['success'] = $this->language->get('text_success');

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
			unset($this->session->data['reward']);
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function remove() {
		$this->load->language('api/cart');

		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			// Remove
			if (isset($this->request->post['key'])) {
                $this->session->data['added_order_info'] = $this->cart->getKeyData($this->request->post['key']);
				 $this->session->data['cart_product_name']=   $this->cart->getProductByKey($this->request->post['key']);
                $this->cart->remove($this->request->post['key']);

				unset($this->session->data['vouchers'][$this->request->post['key']]);

				$json['success'] = $this->language->get('text_success');

				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
				unset($this->session->data['payment_method']);
				unset($this->session->data['payment_methods']);
				unset($this->session->data['reward']);
			}
		}

        $this->session->data['product_action'] = 'remove';

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function products() {
		$this->load->language('api/cart');
        $order_id = $this->request->get['order_id'];
		$json = array();

		if (!isset($this->session->data['api_id'])) {
			$json['error']['warning'] = $this->language->get('error_permission');
		} else {
			// Stock
			if (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
				$json['error']['stock'] = $this->language->get('error_stock');
			}

			// Products
			$json['products'] = array();
            $product_status = $this->language->get('text_not_provided');
			$products = $this->cart->getProducts();

			foreach ($products as $product) {
				$product_total = 0;
                $this->load->model('checkout/order');

                $get_status = $this->model_checkout_order->getStatus($product['product_id'], $product['booking_day'], $order_id);

                if($get_status) {
                    if($get_status['status'] == 1) {
                        $product_status = $this->language->get('text_provided');
                    } else {
                        $product_status = $this->language->get('text_not_provided');
                    }
                }

                $customer = $product['customer'] != 0 ? $this->model_checkout_order->getUserName($product['customer']) : false;
                $confirm = $product['confirm'] != 0 ? $this->model_checkout_order->getUserName($product['confirm']) : false;

                foreach ($products as $product_2) {
                    if ($product_2['product_id'] == $product['product_id']) {
						$product_total += $product_2['quantity'];
					}
				}

				if ($product['minimum'] > $product_total) {
					$json['error']['minimum'][] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
				}

				$option_data = array();

				foreach ($product['option'] as $option) {
					$option_data[] = array(
						'product_option_id'       => $option['product_option_id'],
						'product_option_value_id' => $option['product_option_value_id'],
						'name'                    => $option['name'],
						'value'                   => $option['value'],
						'type'                    => $option['type']
					);
				}

                $date = new \DateTime($product['booking_day']);
                $date = $date->format('d.m.Y');

				$json['products'][] = array(
					'cart_id'    => $product['cart_id'],
					'product_id' => $product['product_id'],
					'name'       => $product['name'],
                    'date'       => $product['booking_day'],
                    'show_date'  => $date,
                    'booking_date'=> $product['booking_day'],
					'option'     => $option_data,
					'quantity'   => $product['quantity'],
                    'customer'   => $customer != false ? sprintf($this->language->get('text_help_customer'), $customer) : $this->language->get('text_added_by_customer'),
                    'confirm'    => $confirm != false ? sprintf($this->language->get('text_help_confirm'), $confirm) : $this->language->get('text_not_confirm'),
                    'status_text'=> $product_status,
                    'status'     => isset($get_status['status']) ? $get_status['status'] : 0,
                    'status_id'  => isset($get_status['status']) ? $get_status['status'] : 0,
					'stock'      => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
					'shipping'   => $product['shipping'],
					'price'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']),
					'total'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'], $this->session->data['currency']),
					'total_raw'  => $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'],
					'reward'     => $product['reward']
				);
			}

			// Voucher
			$json['vouchers'] = array();

			if (!empty($this->session->data['vouchers'])) {
				foreach ($this->session->data['vouchers'] as $key => $voucher) {
					$json['vouchers'][] = array(
						'code'             => $voucher['code'],
						'description'      => $voucher['description'],
						'from_name'        => $voucher['from_name'],
						'from_email'       => $voucher['from_email'],
						'to_name'          => $voucher['to_name'],
						'to_email'         => $voucher['to_email'],
						'voucher_theme_id' => $voucher['voucher_theme_id'],
						'message'          => $voucher['message'],
						'price'            => $this->currency->format($voucher['amount'], $this->session->data['currency']),			
						'amount'           => $voucher['amount']
					);
				}
			}

			// Totals
			$this->load->model('extension/extension');

			$totals = array();
			$taxes = $this->cart->getTaxes();
			$total = 0;

			// Because __call can not keep var references so we put them into an array. 
			$total_data = array(
				'totals' => &$totals,
				'taxes'  => &$taxes,
				'total'  => &$total
			);

			$sort_order = array();

			$results = $this->model_extension_extension->getExtensions('total');

			foreach ($results as $key => $value) {
				$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
			}

			array_multisort($sort_order, SORT_ASC, $results);

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('extension/total/' . $result['code']);
					
					// We have to put the totals in an array so that they pass by reference.
					$this->{'model_extension_total_' . $result['code']}->getTotal($total_data, $json['products']);
				}
			}

			$sort_order = array();

			foreach ($totals as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}

			array_multisort($sort_order, SORT_ASC, $totals);

			$json['totals'] = array();

			foreach ($totals as $total) {
				$json['totals'][] = array(
					'title' => $total['title'],
					'text'  => $this->currency->format($total['value'], $this->session->data['currency'])
				);
			}
		}

		if (isset($this->request->server['HTTP_ORIGIN'])) {
			$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
			$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
			$this->response->addHeader('Access-Control-Max-Age: 1000');
			$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
		}

        if(isset($this->session->data['product_action']) && $this->session->data['product_action'] == 'add') {
            if(isset($this->session->data['added_order_info'])) {
                foreach($this->session->data['added_order_info'] as $day => $values) {
                    $sprint_options = '';
                    if($values['options']) {
                        foreach ($values['options'] as $option_name => $option_value) {
                            if(is_array($option_value)) {
                                $shuffle = '';
                                foreach ($option_value as $last_option) {
                                    $shuffle .= "<p>-$last_option</p>";
                                }
                                $sprint_options .= $option_name.': '.$shuffle;
                            } else {
                                $sprint_options .= $option_name.': '.$option_value.'<br>';
                            }
                        }
                    }
                    $this->model_checkout_order->addOrderHistory($order_id, $this->request->get['order_status_id'], sprintf($this->language->get('text_modify_by'), $customer, $product['name'], $day, $sprint_options));
                }
            }
        } elseif(isset($this->session->data['product_action']) && $this->session->data['product_action'] == 'remove') {
            $sprint_options = '';
		    if($this->session->data['added_order_info']['options']) {
                foreach($this->session->data['added_order_info']['options'] as $information) {
                    $sprint_options .= '<p>-'.$information['name'].': '.$information['value'].'</p>';
                }
            }
            if(isset($this->session->data['cart_product_name'])){
		        $product_name=$this->session->data['cart_product_name'];
            }else{
                $product_name="";
            }
            $this->load->model('checkout/order');
            if(isset($customer)){
                $name=$customer;
            }else{
                if(isset($this->session->data['user_id'])){
                  $name = $this->model_checkout_order->getUserName($this->session->data['user_id']);
                }else{
                    $name ="";
                }
            }
            $this->model_checkout_order->addOrderHistory($order_id, $this->request->get['order_status_id'], sprintf($this->language->get('text_remove_by'), $name, $product_name, $this->session->data['added_order_info']['booking_day'], $sprint_options),false,false,true);

        }

        unset($this->session->data['cart_product_name']);
        unset($this->session->data['product_action']);
        unset($this->session->data['added_order_info']);

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}
}
