<?php

namespace Saswp\Api\Booking;
use Saswp\Api;
use Saswp\Settings;
use WP_REST_Request;

class BookingStoreController
{
    private Api $api;
    private Settings $settings;
    private $apiUrl = "/api/booking/store";

    public function __construct(){
        $this->api = new Api();
        $this->settings = new Settings();
    }
    public function __invoke(WP_REST_Request $wpRestRequest):array
    {
        // Verify nonce
        if (!wp_verify_nonce($wpRestRequest->get_header('X-WP-Nonce'), 'wp_rest')) {
            return ['error' => __('Invalid security token', 'searchandstay')];
        }

        // Check capability
        if (!current_user_can('edit_posts')) {
            return ['error' => __('Unauthorized', 'searchandstay')]; 
        }

        // Validate and sanitize parameters
        $required_params = ['property_id', 'check_in', 'check_out', 'guests'];
        $errors = [];
        
        foreach ($required_params as $param) {
            if (empty($wpRestRequest->get_param($param))) {
                /* translators: %s: required parameter name */
                $errors[] = sprintf(__('Missing required parameter: %s', 'searchandstay'), $param);
            }
        }
        
        if (!empty($errors)) {
            return ['error' => implode(', ', $errors)];
        }
        
        // Sanitize parameters with specific validation
        $sanitized_params = [];
        $sanitized_params['property_id'] = absint($wpRestRequest->get_param('property_id'));
        $sanitized_params['check_in'] = sanitize_text_field($wpRestRequest->get_param('check_in'));
        $sanitized_params['check_out'] = sanitize_text_field($wpRestRequest->get_param('check_out'));
        $sanitized_params['guests'] = absint($wpRestRequest->get_param('guests'));
        
        // Validate dates
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $sanitized_params['check_in'])) {
            /* translators: %s: expected date format (YYYY-MM-DD) */
            $errors[] = __('Invalid check-in date format. Use YYYY-MM-DD', 'searchandstay');
        }
        
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $sanitized_params['check_out'])) {
            /* translators: %s: expected date format (YYYY-MM-DD) */
            $errors[] = __('Invalid check-out date format. Use YYYY-MM-DD', 'searchandstay');
        }
        
        if (!empty($errors)) {
            return ['error' => implode(', ', $errors)];
        }

        $this->api
            ->setApiUrl($this->settings->getFullUrl())
            ->setApiUrlPath($this->apiUrl)
            ->setRequestData($sanitized_params)
            ->withAuthenticationBearer()
            ->setApiToken($this->settings->get("sas_api_token", ''))
            ->doRequest();

        return $this->api->getResult();
    }


}
