<?php

namespace Drupal\basket\Plugin\Basket\Delivery;

use Drupal\basket\Plugins\Delivery\Annotation\BasketDelivery;
use Drupal\basket\Plugins\Delivery\BasketDeliveryInterface;

/**
 * @BasketDelivery(
 *          id        = "basket_address_field",
 *          name      = "Delivery address",
 * )
 */
class DeliveryAddressField implements BasketDeliveryInterface {

	const FIELDS = 'basket_address_field';
	protected static $Basket;
	protected $address;

	function __construct(){
		self::$Basket = \Drupal::service('Basket');
	}

	public function basketFieldParents(){
		return [self::FIELDS];
	}
	public function basketFormAlter(&$form, $form_state){
		$tid = $form_state->getValue(['basket_delivery', 'value']);
		$settings = self::$Basket->getSettings('delivery_settings', $tid);

		$form['address'] = [
			'#type'			=> 'textarea',
			'#required'		=> !empty($settings['required']),
			'#title'		=> !empty($settings['title']) ? self::$Basket->Translate()->t(trim($settings['title'])) : NULL,
			'#title_display'=> !empty($settings['title_display']) ? 'before' : 'none',
			'#default_value'=> $this->basketLoad($form_state)
		];
		if(!empty($settings['placeholder'])){
			$form['address']['#attributes']['placeholder'] = self::$Basket->Translate()->t(trim($settings['placeholder']));
		}
	}
	public function basketDelete($entity, $entity_delete){
		
	}
	public function basketSave($entity, $form_state){
		$this->address[$entity->id()] = $form_state->getValue([self::FIELDS, 'address']);
	}
	public function basketLoad($form_state){
		$getAddress = $form_state->getValue([self::FIELDS, 'address']);
		if(empty($getAddress)){
			$entity = $form_state->getBuildInfo()['callback_object']->getEntity();
			$getAddress = \Drupal::database()->select('basket_orders_delivery', 'd')
								->fields('d', ['address'])
								->condition('d.did', $form_state->getValue(['basket_delivery', 'value']))
								->condition('d.nid', $entity->id())
								->execute()->fetchField();
			$getAddress = !empty($getAddress) ? unserialize($getAddress) : NULL;
		}
		return $getAddress;
	}
	public function basketGetAddress($entity){
		return !empty($this->address[$entity->id()]) ? $this->address[$entity->id()] : NULL;
	}
	public function deliverySumAlter(&$info){
		
	}
}