<?php
class ControllerReportSaleShipping extends Controller {
	public function index() {
		$this->load->language('report/sale_shipping');

		$this->document->setTitle($this->language->get('heading_title'));

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = date("Y-m-01", strtotime('- 1 month'));
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = date("Y-m-t", strtotime('- 1 month'));
		}


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

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

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

		$url = '';

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . $this->request->get['filter_date_start'];
		} else {
            $url .= '&filter_date_start=' . $filter_date_start;
        }

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . $this->request->get['filter_date_end'];
		} else {
            $url .= '&filter_date_end=' . $filter_date_end;
        }

		if (isset($this->request->get['filter_group'])) {
			$url .= '&filter_group=' . $this->request->get['filter_group'];
		}

		if (isset($this->request->get['filter_order_status_id'])) {
			$url .= '&filter_order_status_id=' . $this->request->get['filter_order_status_id'];
		} else {
            $url .= '&filter_order_status_id=' . $filter_order_status_id;
        }

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('report/sale_shipping', 'token=' . $this->session->data['token'] . $url, true)
		);

        $data['invoice'] = $this->url->link('report/sale_shipping/invoice', 'token=' . $this->session->data['token'].$url, true);

		$this->load->model('report/sale');

		$data['orders'] = array();
		$data['products'] = array();

		$filter_data = array(
			'filter_date_start'	     => $filter_date_start,
			'filter_date_end'	     => $filter_date_end,
			'filter_order_status_id' => $filter_order_status_id,
			'start'                  => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                  => $this->config->get('config_limit_admin')
		);

		$order_total = $this->model_report_sale->getTotalAllOrders($filter_data);

		$results = $this->model_report_sale->getAllOrders($filter_data);

		$bad = 'На счёт';
		$payment_methods = array($bad=>$bad);

		foreach ($results as $result) {
		    $products = array();

		    $payments = array();

            $order_products = $this->model_report_sale->getOrderProducts($result['order_id']);

            foreach ($order_products as $product) {
                if(in_array($product['product_id'],array_merge($this->config->get('config_payment'), $this->config->get('config_payment_auto')))) {

                    if(!isset($payment_methods[$product['name']])) {
                        $payment_methods[$product['name']] = $product['name'];
                    }

                    $payments[] = array(
                        'name'         => $product['name'],
                        'total'        => -$product['total']
                    );

                } else {

                    $products[] = array(
                        'name'         => $product['name'],
                        'booking_date' => $product['booking_date'],
                        'quantity'     => $product['quantity'],
                        'price'        => $product['price'],
                        'total'        => $product['total'],
                        'options'      => $product['option_name'] ? ($product['option_name'].': '.$product['option_value']) : false,
                        'payments'     => array()
                    );
                }
            }

            foreach ($products as $i=>$product) {
                if (count($payments)>0) {
                    $last = $product['total'];
                    $summa = 1;
                    while (count($payments)>0 AND $last>0 AND $summa>0){
                        reset($payments);
                        $ind = key($payments);
                        $summa = max(min($payments[$ind]['total'], $product['total']),0); // какую сумму
                        if (!isset($products[$i]['payments'][$payments[$ind]['name']])){
                            $products[$i]['payments'][$payments[$ind]['name']] = 0;
                        }
                        $products[$i]['payments'][$payments[$ind]['name']] += $summa;
                        $last -= $summa;
                        $payments[$ind]['total'] -= $summa;
                        if ($payments[$ind]['total']==0){
                            unset($payments[$ind]);
                        }
                    }
                    if ($last>0){
                        if (!isset($products[$i]['payments'][$bad])){
                            $products[$i]['payments'][$bad] = 0;
                        }
                        $products[$i]['payments'][$bad] += $last;
                    }
                }else{
                    // не осталось оплат
                    if (!isset($products[$i]['payments'][$bad])){
                        $products[$i]['payments'][$bad] = 0;
                    }
                    $products[$i]['payments'][$bad] += $last;
                }
            }
            $customer = $this->model_report_sale->getCustomerInfo($result['order_id']);

            $data['orders'][] = array(
				'firstname'  => $customer['firstname'],
				'sername'    => $customer['lastname'],
				'phone'      => $customer['telephone'],
				'mail'       => $customer['email'],
				'date_start' => date("d.m.Y", strtotime($result['min_date'])),
				'date_end'   => date("d.m.Y", strtotime($result['max_date'])),
                'total'      => $this->currency->format($result['total'], $this->config->get('config_currency')),
                'products'   => $products
			);
		}

		$data['payment_methods'] = $payment_methods;
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_list'] = $this->language->get('text_list');
        $data['text_list_head'] = $this->language->get('text_list_head');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');
		$data['text_all_status'] = $this->language->get('text_all_status');
		$data['text_customer_info'] = $this->language->get('text_customer_info');
		$data['text_product_name'] = $this->language->get('text_product_name');
		$data['text_booking_date'] = $this->language->get('text_booking_date');
		$data['text_price'] = $this->language->get('text_price');
		$data['text_quantity'] = $this->language->get('text_quantity');
		$data['text_total'] = $this->language->get('text_total');

		$data['column_date_start'] = $this->language->get('column_date_start');
		$data['column_date_end'] = $this->language->get('column_date_end');
		$data['column_last_product'] = $this->language->get('column_last_product');
		$data['column_total'] = $this->language->get('column_total');

		$data['entry_date_start'] = $this->language->get('entry_date_start');
		$data['entry_date_end'] = $this->language->get('entry_date_end');
		$data['entry_group'] = $this->language->get('entry_group');
		$data['entry_status'] = $this->language->get('entry_status');

		$data['button_filter'] = $this->language->get('button_filter');

		$data['token'] = $this->session->data['token'];

		$this->load->model('localisation/order_status');

		$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

		$data['groups'] = array();

		$data['groups'][] = array(
			'text'  => $this->language->get('text_year'),
			'value' => 'year',
		);

		$data['groups'][] = array(
			'text'  => $this->language->get('text_month'),
			'value' => 'month',
		);

		$data['groups'][] = array(
			'text'  => $this->language->get('text_week'),
			'value' => 'week',
		);

		$data['groups'][] = array(
			'text'  => $this->language->get('text_day'),
			'value' => 'day',
		);

		$url = '';

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . $this->request->get['filter_date_start'];
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . $this->request->get['filter_date_end'];
		}

		if (isset($this->request->get['filter_group'])) {
			$url .= '&filter_group=' . $this->request->get['filter_group'];
		}

		if (isset($this->request->get['filter_order_status_id'])) {
			$url .= '&filter_order_status_id=' . $this->request->get['filter_order_status_id'];
		}

		$pagination = new Pagination();
		$pagination->total = $order_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('report/sale_shipping', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));

		$data['filter_date_start'] = $filter_date_start;
		$data['filter_date_end'] = $filter_date_end;
		$data['filter_group'] = $filter_group;
		$data['filter_order_status_id'] = $filter_order_status_id;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('report/sale_shipping', $data));
	}

    public function invoice() {
        $this->load->language('report/sale_shipping');

        $this->load->model('report/sale');

        $data['orders'] = array();
        $data['products'] = array();

        $filter_data = array(
            'filter_date_start'	     => $this->request->get['filter_date_start'],
            'filter_date_end'	     => $this->request->get['filter_date_end'],
            'filter_order_status_id' => $this->request->get['filter_order_status_id']
        );

        $order_total = $this->model_report_sale->getTotalAllOrders($filter_data);

        $results = $this->model_report_sale->getAllOrders($filter_data);

        $bad = 'На счёт';
        $payment_methods = array($bad=>$bad);

        foreach ($results as $result) {
            $products = array();

            $payments = array();

            $order_products = $this->model_report_sale->getOrderProducts($result['order_id']);

            foreach ($order_products as $product) {
                if(in_array($product['product_id'],array_merge($this->config->get('config_payment'), $this->config->get('config_payment_auto')))) {

                    if(!isset($payment_methods[$product['name']])) {
                        $payment_methods[$product['name']] = $product['name'];
                    }

                    $payments[] = array(
                        'name'         => $product['name'],
                        'total'        => -$product['total']
                    );

                } else {

                    $products[] = array(
                        'name'         => $product['name'],
                        'booking_date' => $product['booking_date'],
                        'quantity'     => $product['quantity'],
                        'price'        => $product['price'],
                        'total'        => $product['total'],
                        'options'      => $product['option_name'] ? ($product['option_name'].': '.$product['option_value']) : false,
                        'payments'     => array()
                    );
                }
            }

            foreach ($products as $i=>$product) {
                if (count($payments)>0) {
                    $last = $product['total'];
                    $summa = 1;
                    while (count($payments)>0 AND $last>0 AND $summa>0){
                        reset($payments);
                        $ind = key($payments);
                        $summa = max(min($payments[$ind]['total'], $product['total']),0); // какую сумму
                        if (!isset($products[$i]['payments'][$payments[$ind]['name']])){
                            $products[$i]['payments'][$payments[$ind]['name']] = 0;
                        }
                        $products[$i]['payments'][$payments[$ind]['name']] += $summa;
                        $last -= $summa;
                        $payments[$ind]['total'] -= $summa;
                        if ($payments[$ind]['total']==0){
                            unset($payments[$ind]);
                        }
                    }
                    if ($last>0){
                        if (!isset($products[$i]['payments'][$bad])){
                            $products[$i]['payments'][$bad] = 0;
                        }
                        $products[$i]['payments'][$bad] += $last;
                    }
                }else{
                    // не осталось оплат
                    if (!isset($products[$i]['payments'][$bad])){
                        $products[$i]['payments'][$bad] = 0;
                    }
                    $products[$i]['payments'][$bad] += $last;
                }
            }
            $customer = $this->model_report_sale->getCustomerInfo($result['order_id']);

            $data['orders'][] = array(
                'firstname'  => $customer['firstname'],
                'sername'    => $customer['lastname'],
                'phone'      => $customer['telephone'],
                'mail'       => $customer['email'],
                'date_start' => date("d.m.Y", strtotime($result['min_date'])),
                'date_end'   => date("d.m.Y", strtotime($result['max_date'])),
                'total'      => $this->currency->format($result['total'], $this->config->get('config_currency')),
                'products'   => $products
            );
        }

        $data['payment_methods'] = $payment_methods;
        $data['heading_title'] = $this->language->get('heading_title');

        $start = date("d/m/Y", strtotime($this->request->get['filter_date_start']));
        $end = date("d/m/Y", strtotime($this->request->get['filter_date_end']));

        $data['text_list'] = sprintf($this->language->get('text_list'), $start, $end);
        $data['text_no_results'] = $this->language->get('text_no_results');
        $data['text_confirm'] = $this->language->get('text_confirm');
        $data['text_all_status'] = $this->language->get('text_all_status');
        $data['text_customer_info'] = $this->language->get('text_customer_info');
        $data['text_product_name'] = $this->language->get('text_product_name');
        $data['text_booking_date'] = $this->language->get('text_booking_date');
        $data['text_price'] = $this->language->get('text_price');
        $data['text_quantity'] = $this->language->get('text_quantity');
        $data['text_total'] = $this->language->get('text_total');

        $data['column_date_start'] = $this->language->get('column_date_start');
        $data['column_date_end'] = $this->language->get('column_date_end');
        $data['column_last_product'] = $this->language->get('column_last_product');
        $data['column_total'] = $this->language->get('column_total');

        $data['entry_date_start'] = $this->language->get('entry_date_start');
        $data['entry_date_end'] = $this->language->get('entry_date_end');
        $data['entry_group'] = $this->language->get('entry_group');
        $data['entry_status'] = $this->language->get('entry_status');

        $data['button_filter'] = $this->language->get('button_filter');

        $this->response->setOutput($this->load->view('report/invoice2', $data));
    }
}