<?php

namespace Drupal\basket;

class Entity{
	/*
	* Entiti removal process
	*/
	public static function delete($entity){
		switch($entity->getEntityTypeId()){
			case'node_type':
				\Drupal::database()->delete('basket_node_types')->condition('type', $entity->id())->execute();
			break;
			case'user':
				\Drupal::database()->delete('basket_user_percent')->condition('uid', $entity->id())->execute();
			break;
			case'node':
				$isBundle = \Drupal::database()->select('basket_node_types', 'n')
										->fields('n')
										->condition('n.type', $entity->bundle())
										->execute()->fetchField();
				if(!empty($isBundle)){
					\Drupal::database()->delete('basket')->condition('nid', $entity->id())->execute();
				}
				// Delete order
				$orderClass = \Drupal::service('Basket')->Orders(NULL, $entity->id());
				$orderClass->delete($entity);
				// Delete all
				\Drupal::database()->delete('basket_node_delete')
							->condition('nid', $entity->id())
							->execute();
			break;
		}
	}
	/*
	* Checkout process
	*/
	public static function insertOrder($entity, $form_state){
		$_SESSION['delivery_tid'] = $form_state->getValue(['basket_delivery', 'value']);
		// ---
		$Basket = \Drupal::service('Basket');
		$Cart = $Basket->Cart();
		$CartItems = $Cart->getItemsInBasket();
		// ---
		$countGoods = 0;
		foreach ($CartItems as $row){
			$bd_nids[$row->nid] = $row->nid;
			$countGoods += $row->count;
		}
		$nodesAdd = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($bd_nids);

		$getPayInfo = $Cart->getPayInfo();

		$basketOrderFields = [
			'nid'				=> $entity->id(),
			'price'				=> $Cart->getTotalSum(),
			'goods'				=> $countGoods,
			'currency'			=> $Basket->Currency()->getCurrent(),
			'status'			=> $Basket->Term()->getDefaultNewOrder('status'),
			'fin_status'		=> $Basket->Term()->getDefaultNewOrder('fin_status'),
			'pay_price'			=> $getPayInfo['price'],
			'pay_currency'		=> $getPayInfo['currency']->id,
			'add_price'			=> 0,
			'delivery_price'	=> 0
		];
		// Delivery sum
		$deliveryInfo = \Drupal::service('BasketDelivery')->getDeliveryInfo($entity);
		if(!empty($deliveryInfo['sum']) && !empty($deliveryInfo['isPay'])){
			$basketOrderFields['delivery_price'] = $deliveryInfo['sum'];
		}
		// ---
		$basketItems = [];
		foreach ($CartItems as $row){
			$basketItems[$row->id] = [
				'isNew'				=> TRUE,
				'nid'				=> $row->nid,
				'order_nid'			=> $entity->id(),
				'price'				=> $Cart->getItemPrice($row),
				'discount'			=> [
					'percent'			=> $Cart->getItemDiscount($row)
				],
				'count'				=> $row->count,
				'fid'				=> $Cart->getItemImg($row),
				'params'			=> $row->all_params,
				'params_html'		=> !empty($row->all_params) ? [
					'full'				=> \Drupal::service('BasketParams')->getDefinitionParams($row->all_params, $row->nid),
					'inline'			=> \Drupal::service('BasketParams')->getDefinitionParams($row->all_params, $row->nid, TRUE)
				] : NULL,
				'add_time'			=> $row->add_time,
				'node_fields'		=> [
					'title'				=> $nodesAdd[$row->nid]->getTitle(),
					'img_uri'			=> ''
				],
				'setUriByFid'		=> NULL
			];
			if(!empty($basketItems[$row->id]['fid'])){
				$basketItems[$row->id]['setUriByFid'] = $basketItems[$row->id]['fid'];
			}
		}
		// Alters
		\Drupal::moduleHandler()->alter('basket_insertOrder', $basketOrderFields, $basketItems, $entity);
		// --
		$orderId = \Drupal::database()->insert('basket_orders')
								->fields([
									'nid'				=> $entity->id(),
									'price'				=> !empty($basketOrderFields['price']) 			? $basketOrderFields['price'] 			: 0,
									'goods'				=> !empty($basketOrderFields['goods']) 			? $basketOrderFields['goods'] 			: 0,
									'currency'			=> !empty($basketOrderFields['currency']) 		? $basketOrderFields['currency'] 		: NULL,
									'status'			=> !empty($basketOrderFields['status']) 		? $basketOrderFields['status'] 			: NULL,
									'fin_status'		=> !empty($basketOrderFields['fin_status']) 	? $basketOrderFields['fin_status'] 		: NULL,
									'pay_price'			=> !empty($basketOrderFields['pay_price']) 		? $basketOrderFields['pay_price'] 		: 0,
									'pay_currency'		=> !empty($basketOrderFields['pay_currency']) 	? $basketOrderFields['pay_currency'] 	: NULL,
									'add_price' 		=> !empty($basketOrderFields['add_price']) 		? $basketOrderFields['add_price'] 		: NULL,
									'delivery_price' 	=> !empty($basketOrderFields['delivery_price']) ? $basketOrderFields['delivery_price'] 	: NULL,
								])
								->execute();
		$form_state->setValue('orderId', $orderId);
		// Create order
		if(!empty($orderId)){
			$OrderClass = $Basket->Orders($orderId);
			$Order = $OrderClass->load();
			if(!empty($basketItems)){
				foreach ($basketItems as $basketItem){
					$Order->items[] = (object)$basketItem;
				}				
			}
            $form_state->set('BasketOrder', $Order);
		}
		// Create payment
		\Drupal::service('BasketPayment')->createPayment($entity, $form_state);
		// Save order
		if(!empty($Order)){
			$OrderClass->replaceOrder($Order);
            $OrderClass->save();
		}
        // Alters
		\Drupal::moduleHandler()->alter('basket_postInsertOrder', $entity, $orderId);
		// Clear
		if(empty($basketOrderFields['notClearAll'])){
			$Cart->clearAll();
		}
		// Send emails
		$notifications = $Basket->getSettings('notifications', 'config');
		// admin
		if(!empty($notifications['notification_order_admin']) && !empty($notifications['notification_order_admin_mails'])){
			foreach (explode(PHP_EOL, trim($notifications['notification_order_admin_mails'])) as $email){
				$Basket->MailCenter()->send(trim($email), [
					'template'			=> 'notification_order_admin',
					'nid'				=> $entity->id(),
					'uid'				=> $entity->get('uid')->target_id
				]);
			}
		}
		// user
		if(!empty($notifications['notification_order_user']) && 
			!empty($notifications['notification_order_user_field']) && 
			!empty($entity->{$notifications['notification_order_user_field']}) && 
			!empty($UserMail = $entity->get($notifications['notification_order_user_field'])->value)){
				$Basket->MailCenter()->send(trim($UserMail), [
					'template'			=> 'notification_order_user',
					'nid'				=> $entity->id(),
					'uid'				=> $entity->get('uid')->target_id
				]);
		}
		// END send emails
	}
}