<?php
declare (strict_types = 1);

namespace Magetop\Advancepreview\Controller\AddressDropdown;

use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;

class AjaxReceive extends Action {

	private $customerRepository;
	private $addressRepository;

	public function __construct(CustomerRepositoryInterface $customerRepository,
		AddressRepositoryInterface $addressRepository,
		Context $context) {

		$this->customerRepository = $customerRepository;
		$this->addressRepository = $addressRepository;
		parent::__construct($context);
	}

	public function execute() {

		if ($this->getRequest()->getPost('shippingid')) {
			$addressId = $this->getRequest()->getPost('shippingid');
			$customerId = $this->getRequest()->getPost('customerid');

			$address = $this->addressRepository->getById($addressId)->setCustomerId($customerId);
			$address->setIsDefaultShipping(true);

			$this->addressRepository->save($address);

			$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
			$resultJson->setData('success');
			return $resultJson;
		}
	}
}