<?php

namespace Saswp\Api\Admin;
use Saswp\DTOs\Response\PropertyListDTO;
use Saswp\DTOs\SasSettingsDTO;
use Saswp\Settings;
use WP_REST_Request;

class PropertyListController
{
	private PropertyListDTO $propertyListDTO;
	private Settings $settings;
	private string $getParams;


    private string $propertyFilterName;

    public function __construct(){
        $this->settings = new Settings();
        $this->settings->all();
        $this->propertyListDTO = new PropertyListDTO([]);
    }
    public function retrieveProperties( WP_REST_Request $wpRestRequest ) {
		$_data = $wpRestRequest->get_query_params() ;
        $this->propertyFilterName = $_data['property_filter_name']??null;
		$this->retrievePropertyList();
        return $this->sendResponse([ 'success' => true ]);
    }

    public function buildParams(){
        $this->getParams = "?page=1&per_page=99999999999";
        if($this->propertyFilterName !=""){
            $this->getParams .= "&property_name=".$this->propertyFilterName ."&";
        }
    }

    function retrievePropertyList() {
        $sasSettingsDTO = $this->settings->getSasSettingsDTO();
        $this->buildParams();
		$url                                = $sasSettingsDTO->sas_api_url . "/api/properties/external".$this->getParams;
		$defaults[ CURLOPT_URL ]            = $url;
		$defaults[ CURLOPT_RETURNTRANSFER ] = 1;

		$host = wp_parse_url($url, PHP_URL_HOST);

		$headers = [
			'Host' => $host,
			'Accept' => 'application/json',
			'Content-Type' => 'application/json',
			'User-Agent' => 'WordPress/' . get_bloginfo('version'),
			'SearchAndStayApiToken' => $sasSettingsDTO->sas_api_token,
		];

		$args = [
			'headers' => $headers,
			'timeout' => 30,
		];

		$response = wp_remote_get($url, $args);

		if (is_wp_error($response)) {
			$error_message = $response->get_error_message();
			wp_admin_notice($error_message, [
				'dismissible' => true,
			]);
			$result = [];
		} else {
			$body = wp_remote_retrieve_body($response);
			$result = json_decode($body, true) ?? [];
		}

		$this->propertyListDTO = new PropertyListDTO($result['data'] ?? []);

		return $this;
	}

	private function sendResponse($params = []) {
		$params = array_merge([
			'success' => false,
			'only'    => [],
			'except'  => [],
		], $params);
		$response = ['data' => []];
		$response['data']['properties'] = $this->propertyListDTO->properties;
		$response['success'] = $params['success'];
		return $response;
	}
}
