<?php

namespace Drupal\basket;

use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;

class BasketExtraFields{

	protected $nodeTypeSettings;
	protected $basket;

	public function __construct(){
		$this->basket = \Drupal::service('Basket');
	}

	public function info(&$extra){
		/*
			Node
		*/
		$SettingsNodeTypes = $this->basket->getNodeTypes();
		if(!empty($SettingsNodeTypes)){
			foreach ($SettingsNodeTypes as $row){
				if(empty($row->extra_fields)) continue;
				foreach (unserialize($row->extra_fields) as $key => $rowExtra){
					if(empty($rowExtra['on']))	continue;
					switch($key){
						case'add':
							$extra['node'][$row->type]['display']['basket_add'] = array(
				                'label'             => $this->basket->Translate()->t('Add button'),
				                'weight'            => 100,
				                'visible'           => TRUE,
				            );
						break;
						case'add_params':
							$extra['node'][$row->type]['display']['basket_add_params'] = array(
				                'label'             => $this->basket->Translate()->t('Selection of parameters'),
				                'weight'            => 100,
				                'visible'           => FALSE,
				            );
						break;
					}
				}
			}
		}
		$enabledServices = $this->basket->getSettings('enabled_services', NULL);
		if(!empty($enabledServices['delivery'])){
			$extra['node']['basket_order']['form']['basket_delivery'] = array(
                'label'             => $this->basket->Translate()->t('Delivery'),
                'weight'            => 100,
                'visible'           => TRUE,
            );
			$extra['node']['basket_order']['display']['basket_delivery'] = array(
                'label'             => $this->basket->Translate()->t('Delivery'),
                'weight'            => 100,
                'visible'           => TRUE,
            );
			$extra['node']['basket_order']['display']['basket_delivery_address'] = array(
                'label'             => $this->basket->Translate()->t('Address'),
                'weight'            => 100,
                'visible'           => TRUE,
            );
		}
		if(!empty($enabledServices['payment'])){
			$extra['node']['basket_order']['form']['basket_payment'] = array(
                'label'             => $this->basket->Translate()->t('Payment'),
                'weight'            => 100,
                'visible'           => TRUE,
            );
			$extra['node']['basket_order']['display']['basket_payment'] = array(
                'label'             => $this->basket->Translate()->t('Payment'),
                'weight'            => 100,
                'visible'           => TRUE,
            );
		}
		/*
			Users
		*/
		$extra['user']['user']['form']['basket_user_percent'] = array(
            'label'             => $this->basket->Translate()->t('Individual user discount'),
            'weight'            => -100,
            'visible'           => TRUE,
        );
	}
	public function nodeView(&$build, $entity, $display){
		if ($display->getComponent('basket_add')){
	        $build['basket_add'] = $this->BasketAddGenerate($entity, 'node_view');
	    }
		if ($display->getComponent('basket_add_params')){
	        $build['basket_add_params'] = \Drupal::service('BasketParams')->getField($entity);
	    }
		if ($display->getComponent('basket_delivery')){
			$order = $this->basket->Orders(NULL, $entity->id())->load();
			if(!empty($order->delivery_id)){
				$delivery = $this->basket->Term()->load($order->delivery_id);
				if(!empty($delivery)){
			        $build['basket_delivery'] = [
			        	'#title'		=> $this->basket->Translate()->t('Delivery'),
			        	[
			        		'#markup'		=> $this->basket->Translate()->t($delivery->name)
			        	]
			        ];
				}
			}
			if(!empty($order->delivery_address)){
				$delivery_address = unserialize($order->delivery_address);
				if(!empty($delivery_address)){
					$build['basket_delivery_address'] = [
						'#title'		=> $this->basket->Translate()->t('Address'),
						[
							'#markup'		=> $delivery_address
						]
					];
				}
			}
	    }
		if ($display->getComponent('basket_payment')){
			$order = $this->basket->Orders(NULL, $entity->id())->load();
			if(!empty($order->payment_id)){
				$payment = $this->basket->Term()->load($order->payment_id);
				if(!empty($payment)){
			        $build['basket_payment'] = [
			        	'#title'		=> $this->basket->Translate()->t('Payment'),
			        	[
			        		'#markup'		=> $this->basket->Translate()->t($payment->name)
			        	]
			        ];
				}
			}
	    }
	}
	public function BasketAddGenerate($entity, $type_view, $settings = NULL){
		if(!\Drupal::currentUser()->hasPermission('basket add_button_access')){
			return [];
		}
		if(!$entity->isPublished()){
			return [];
		}
		if(empty($settings)){
			$settings = $this->getNodeTypeSettings($entity->bundle());
		}
		// ---
		if(empty($settings->extra_fields['add']['on'])) return [];
		$views = !empty($entity->view) ? [
			'id'			=> $entity->view->id(),
			'display'		=> $entity->view->current_display
		] : [];
		if(!empty($entity->basketAddParams)){
			$views['popup'] = 'popup';
		}
		// ---
		$info = [
			'node'			=> $entity,
			'type_view'		=> $type_view,
			'allOptions'	=> !empty($settings->extra_fields) ? $settings->extra_fields : [],
			'add'			=> [
				'text'			=> !empty($settings->extra_fields['add']['text']) ? $this->basket->Translate()->t($settings->extra_fields['add']['text']) : $this->basket->Translate()->t('Buy'),
				'attributes'		=> new Attribute([
					'href'				=> 'javascript:void(0);',
					'class'				=> ['addto_basket_button button'],
					'onclick'			=> 'basket_ajax_link(this, \''.Url::fromRoute('basket.pages', ['page_type' => 'api-add'])->toString().'\')',
					'data-basket_node'	=> $entity->id()
				]),
				'insert_values'		=> [
					'nid'				=> $entity->id(),
					'post_type'			=> 'add',
					'params'			=> !empty($settings->setParams) ? $settings->setParams : [],
					'add_key'			=> $entity->id().'_'.implode('_', $views),
					'add_popup'			=> !empty($entity->basketAddParams) ? 1 : 0
				]
			],
		];
		if(!empty($settings->extra_fields['add']['count'])){
            $attr = [
                'min'       => 1,
                'step'      => 1,
                'max'       => 999,
                'scale'     => 0
            ];
            $productID = $entity->id();
            $params    = NULL;
            // Alter
            \Drupal::moduleHandler()->alter('basket_count_input_attr', $attr, $productID, $params);
            // ---
            if ( isset($attr['scale']) ){
                $attr['data-basket-scale'] = $attr['scale'];
                unset($attr['scale']);
            } else {
                $attr['data-basket-scale'] = 0;
            }
			$info += [
				'input'		=> [
					'attributes'	=> new Attribute($attr + [
						'type'			=> 'number',
						'min'			=> 1,
						'max'			=> 999,
						'step'			=> 1,
						'value'			=> 1,
						'class'			=> ['count_input'],
                        'onblur'		=> 'basket_input_count_format(this)'
					])
				],
				'button'	=> [
					'min'			=> [
						'attributes'	=> new Attribute([
							'href'			=> 'javascript:void(0);',
							'class'			=> ['arrow', 'min'],
							'onclick'		=> 'basket_change_input_count(this, \'-\')'
						]),
						'text'			=> '-'
					],
					'plus'			=> [
						'attributes'	=> new Attribute([
							'href'			=> 'javascript:void(0);',
							'class'			=> ['arrow', 'plus'],
							'onclick'		=> 'basket_change_input_count(this, \'+\')'
						]),
						'text'			=> '+'
					]
				]
			];
		}
		// Alter
        \Drupal::moduleHandler()->alter('basket_add', $info);
        // ---
		$info['add']['attributes']['data-post'] = json_encode($info['add']['insert_values']);
		return [
			'#theme'		=> 'basket_add',
			'#info'			=> $info,
			'#attached'		=> [
				'library'		=> [
					'basket/basket.js'
				]
			]
		];
	}
	public function getNodeTypeSettings($nodeType){
		if(!isset($this->nodeTypeSettings[$nodeType])){
			$this->nodeTypeSettings[$nodeType] = \Drupal::database()->select('basket_node_types', 't')
															->fields('t')
															->condition('t.type', $nodeType)
															->execute()->fetchObject();
			if(!empty($this->nodeTypeSettings[$nodeType]->extra_fields)){
				$this->nodeTypeSettings[$nodeType]->extra_fields = unserialize($this->nodeTypeSettings[$nodeType]->extra_fields);
 			}
		}
		return $this->nodeTypeSettings[$nodeType];
	}
	public function userFormAlter(&$form, $form_state){
		$form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')->load('user.user.default');
        if($display = $form_display->getComponent('basket_user_percent')){
        	$entity = $form_state->getBuildInfo()['callback_object']->getEntity();
        	$form['basket_user_percent'] = [
        		'#type'			=> 'select',
        		'#title'		=> $this->basket->Translate()->t('Individual user discount'),
        		'#options'		=> array_combine(range(0, 100), range(0, 100)),
        		'#field_suffix'	=> '%',
        		'#disabled'		=> !\Drupal::currentUser()->hasPermission('basket access_edit_user_percent'),
        		'#default_value'=> $this->basket->getCurrentUserPercent($entity->id())
        	];
        	$form['actions']['submit']['#submit'][] = [$this, 'basketUserPercentSubmit'];
        }
	}
	public function basketUserPercentSubmit($form, $form_state){
		$entity = $form_state->getBuildInfo()['callback_object']->getEntity();
		if(!empty($entity->id())){
			$percent = $form_state->getValue('basket_user_percent');
			\Drupal::database()->merge('basket_user_percent')
                        ->key([
                            'uid'       => $entity->id()
                        ])
                        ->fields([
                            'percent'   => !empty($percent) ? $percent : 0
                        ])
                        ->execute();
		}
	}
}
