<?php

class CurlService {
    private $url;
    private $payLoad;
    
    private $logger;

    /**
     * set the URL
     * @param mixed $url
     */
    public function setUrl($url = null) {
        $this->url = $url;
    }

    /**
     * set the data to be posted
     * @param mixed $data
     */
    public function setPayload($payLoad = null) {
        $this->payLoad = $payLoad;
    }

    /**
     * set the logger
     * @param mixed $logger
     */
    public function setLogger($logger = null) {
        $this->logger = $logger;
    }

    /**
     * Get the data
     * @return void
     */
    public function get() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1000);

        // Enable verbose output
        curl_setopt($ch, CURLOPT_VERBOSE, true);

        $startTime = microtime(true); // if curl failed, we'll log the time
        // Capture verbose output into a variable
        $curlOutput = curl_exec($ch);

        // Check for errors
        if (!$curlOutput) {
            $error = curl_error($ch);
            curl_close($ch);
            // $logger->log(Logger::DEBUG, $error);
            LogHelper::logInfo($error, $startTime, microtime(true), [], 'mcp_2025_log', $this->logger);
            throw new CustomErrorException(BaseResponse::DATA_NOT_AVAILABLE, 'Gangguan penarikan data');
        }
        curl_close($ch);
        return json_decode($curlOutput);
    }

    /**
     * Post the data
     * @throws \CustomErrorException
     */
    public function post() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1000);

        // Set method to POST
        curl_setopt($ch, CURLOPT_POST, true);

        // Set the JSON data as the POST fields
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->payLoad);

        // Set the content type header
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($this->payLoad)
        ]);

        // Enable verbose output
        curl_setopt($ch, CURLOPT_VERBOSE, true);

        $startTime = microtime(true); // if curl failed, we'll log the time
        // Capture verbose output into a variable
        $curlOutput = curl_exec($ch);

        // Check for errors
        if (!$curlOutput) {
            $error = curl_error($ch);
            curl_close($ch);
            // $logger->log(Logger::DEBUG, $error);
            LogHelper::logInfo($error, $startTime, microtime(true), [], 'mcp_2025_log', $this->logger);
            throw new CustomErrorException(BaseResponse::DATA_NOT_AVAILABLE, 'Updating answer failed');
        }
        curl_close($ch);
        return json_decode($curlOutput);
    }
}