<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Wiaas_Admin_Delivery_Process_Order {

	public static function init() {

		if (isset($_GET['wiaas-procurement-order-id'])) {

			add_action('admin_init', array(__CLASS__, 'download_procurement_order'));
		}

		add_action('add_meta_boxes', array(__CLASS__, 'add_delivery_process_metabox'), 100 );

		add_action('woocommerce_process_shop_order_meta', array(__CLASS__, 'maybe_assign_delivery_process'), 999);
	}

	/**
	 * Assign delivery process for order
	 *
	 * @param int $order_id
	 */
	public static function maybe_assign_delivery_process($order_id) {

		if (! empty($_POST['wiaas_order_delivery_process_id'])) {

			$process_id = absint($_POST['wiaas_order_delivery_process_id']);

			Wiaas_Delivery_Process::create_delivery_process_for_order($order_id, $process_id);
		}
	}

	public static function add_delivery_process_metabox() {

		add_meta_box(
			'order_delivery_process_meta_box',
			__('Delivery Process', 'cmb'),
			array(__CLASS__, 'order_delivery_process_meta_box'),
			'shop_order',
			'side',
			'high'
		);
	}

	public static function order_delivery_process_meta_box() {

		global $post;

		$order_id = $post->ID;

		$process_entry = Wiaas_Delivery_Process::get_order_delivery_process_entry($order_id);

		if ( empty($process_entry) ) {

			$country_code = Wiaas_Order::get_order_country_code($order_id);

			$list_of_delivery_processes = Wiaas_Delivery_Process::get_available_process_list_for_country($country_code);

			?>
			<div>
				<select name="wiaas_order_delivery_process_id" style="width: 100%;">
					<option value="" disabled selected>Assign process to order ... </option>
					<?php
					foreach($list_of_delivery_processes as $index => $process){
						echo '<option value=' . $process['id'] . '>' . $process['title'] . '</option>';
					}
					?>
				</select>
				<button type="submit" class="button" style="margin-top: 10px;">Assign</button>
			</div>
			<?php
		}  else{

			$entry_url = add_query_arg( array(
				'page' => 'gravityflow-inbox',
				'view' => 'entry',
				'id' => $process_entry['form_id'],
				'lid' => $process_entry['id']
			), admin_url() );

			?>
			<a href="<?php esc_attr_e($entry_url, 'wiaas') ?>"> Delivery Process </a>
			<?php
		}
	}

	/**
	 * Download procurement order report
	 *
	 * @throws \PhpOffice\PhpSpreadsheet\Exception
	 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
	 *
	 */
	public static function download_procurement_order() {

		if (!is_user_logged_in()) {
			wp_die(	__( 'No Access.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 403 ) );
		}

		$order_id = $_GET['wiaas-procurement-order-id'];
		$order = wc_get_order($order_id);

		if (! $order) {
			wp_die(	__( 'Invalid order.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 404 ) );
		}

		$customer_user_id = $order->get_customer_id();
		$organization_id = wiaas_get_user_organization_id($customer_user_id);
		$customer_organization_info = wiaas_get_organization_info($organization_id);

		$delivery_address = $order->get_shipping_address_1() . ',' .
		                    $order->get_shipping_city() . ',' .
		                    $order->get_shipping_country() . ',' .
		                    $order->get_shipping_postcode();
		$billing_address = $order->get_billing_address_1() . ',' .
		                   $order->get_billing_city() . ',' .
		                   $order->get_billing_country() . ',' .
		                   $order->get_billing_postcode();

		$order_procurement_info = wiaas_get_order_procurement_info($order->get_id());

		$spreadsheet = new Spreadsheet();
		$spreadsheet->getProperties()->setCreator("RICOH")
		            ->setLastModifiedBy("Ricoh Dash")
		            ->setTitle("Order Procurement Report")
		            ->setSubject("Order Procurement Report")
		            ->setDescription("Order Procurement Report")
		            ->setKeywords("office 2007 openxml php order procurement")
		            ->setCategory("Procurement report file");

		$spreadsheet->setActiveSheetIndex(0);
		$sheet = $spreadsheet->getActiveSheet();
		$sheet->setTitle('Order procurement');

		$sheet->setCellValue('A1', 'Customer details');
		$sheet->setCellValue('A2', 'Name');
		$sheet->setCellValue('A3', 'Invoice address');
		$sheet->setCellValue('A4', 'Invoice Full Name');
		$sheet->setCellValue('A5', 'Invoice Email');
		$sheet->setCellValue('A6', 'VAT Number');

		$sheet->setCellValue('B2', ! empty($customer_organization_info) ? $customer_organization_info['name'] : '');
		$sheet->setCellValue('B3', $billing_address);
		$sheet->setCellValue('B4', $order->get_formatted_billing_full_name());
		$sheet->setCellValue('B5', $order->get_billing_email());
		$sheet->setCellValue('B6', ! empty($customer_organization_info) ? $customer_organization_info['vat_code'] : '');

		$sheet->getStyle('A1')->getFont()->setBold(true);

		$sheet->setCellValue('A9', 'OrderDetails');
		$sheet->setCellValue('A10', 'Order number');
		$sheet->setCellValue('A11', 'Project number');
		$sheet->setCellValue('A12', 'Delivery addres');
		$sheet->setCellValue('A13', 'Delivery Full Name');
		$sheet->setCellValue('A14', 'Reference');
		$sheet->setCellValue('B10', $order->get_order_number());
		$sheet->setCellValue('B11', Wiaas_Order_Project::get_project_name_for_order($order->get_id()) );
		$sheet->setCellValue('B12', $delivery_address);
		$sheet->setCellValue('B13', $order->get_formatted_shipping_full_name());
		$sheet->setCellValue('B14', $order->get_meta('_wiaas_reference'));

		$sheet->getStyle('A9')->getFont()->setBold(true);

		$row = 14;

		foreach ($order_procurement_info as $category => $products) {

			$col = 1; $row += 2;

			$sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
			$sheet->getStyleByColumnAndRow($col, $row)->getFont()->setBold(true);

			$sheet->setCellValueByColumnAndRow($col, $row, ucfirst(strtolower($category)));

			$row += 2;

			if (! empty($products)) {

				$product_columns = array_keys($products[0]);

				foreach ($product_columns as $product_column_index => $product_column) {

					$sheet->getColumnDimensionByColumn($product_column_index + 1)->setAutoSize(true);
					$sheet->getStyleByColumnAndRow($product_column_index + 1, $row)->getFont()->setBold(true);
					$sheet->setCellValueByColumnAndRow($product_column_index + 1, $row, $product_column);
				}
			}

			$row += 1;
			foreach ($products as $product) {

				$product_values = array_values($product);
				foreach ($product_values as $product_value_index => $product_value) {

					$sheet->setCellValueByColumnAndRow($product_value_index + 1, $row, $product_value);
				}
				$row += 1;
			}
		}

		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Procurement Report '.$order->get_order_number().'.xlsx"');
		header('Cache-Control: max-age=0');

		$writer = new Xlsx($spreadsheet);
		$writer->save('php://output');

		exit;

	}
}

Wiaas_Admin_Delivery_Process_Order::init();
