<?php

namespace NixfilePlugin\Api;

class Client {

	private string $baseApi = "https://api.nixfile.com"; // <--- YOUR BASE API
	private string $domainId;
	private string $token;

	public function __construct() {
		$this->domainId = "d33d8710-bae1-11f0-af03-86cd56488d0f";
		$this->token    = "d33d8710-bae1-11f0-af03-86cd56488d0f";
	}

	public function getFolder( $folderId = "", $page = 1 ) {
		$url = "{$this->baseApi}/v2/domain/file-manager/{$this->domainId}"
		       . "?folder_id={$folderId}&page={$page}";

		$args     = [
			"method"  => "GET",
			"headers" => [
				"Accept" => "application/json"
			]
		];
		$response = wp_remote_request( $url, $args );

		if ( is_wp_error( $response ) ) {
			return [ "success" => false, "message" => "Network error" ];
		}

		return json_decode( wp_remote_retrieve_body( $response ), true );
	}

	public function upload() {
		if ( ! isset( $_FILES['file'] ) ) {
			return [ "success" => false, "message" => "No file uploaded" ];
		}

		$file = $_FILES['file'];

		$url = "{$this->baseApi}/v2/domain/file-manager/{$this->domainId}/media";

		$curlFile   = new \CURLFile(
			$file['tmp_name'],
			$file['type'],
			$file['name']
		);
		$postFields = [
			'folder_id'  => $_REQUEST['folder_id'],
			'collection' => 6,
			'file'       => $curlFile,
		];
		array_filter( $postFields );
		$ch = curl_init();

		curl_setopt_array( $ch, [
			CURLOPT_URL            => $url,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $postFields,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER     => [
				'Accept: application/json',
			],
		] );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
		$response = curl_exec( $ch );
		$error    = curl_error( $ch );
		curl_close( $ch );

		if ( $error ) {
			return [ "success" => false, "message" => $error ];
		}

		return json_decode( $response, true );
	}


}