<?php

namespace Saswp\Api\Vendor;
use Saswp\Api;
use Saswp\DTOs\Response\Vendor\LoginJsonDTO;
use Saswp\Settings;
use WP_REST_Request;

class VendorLoginJsonController
{
    private Api $api;
    private Settings $settings;
    private $apiUrl = "/api/vendor/login_json";

    public function __construct(){
        $this->api = new Api();
        $this->settings = new Settings();
    }
    public function __invoke(WP_REST_Request $wpRestRequest):array
    {
        $_params = $wpRestRequest->get_params() ?? [];
        
        $this->api
            ->setApiUrl($this->settings->getFullUrl())
            ->setApiUrlPath($this->apiUrl)
            ->setApiMethod("POST")
            ->setRequestData($_params)
            ->setApiToken($this->settings->get("sas_api_token", ''))
            ->doRequest();

        $result = $this->api->getResult();
        if (isset($result['data']['result']['access_token'])) {
            $loginJsonDTO = new LoginJsonDTO($result['data']['result'] ?? []);
            $result['data']['result'] = $loginJsonDTO->toArray();
            session_start();
            $_SESSION['saswp_vendor_token'] = $result['data']['result']['access_token'];
            $_SESSION['saswp_account_id'] = $result['data']['result']['account_id'];
            $_SESSION['saswp_vendor_id'] = $result['data']['result']['id'];
        }
        return $result;
    }
}
