<?php

declare(strict_types=1);

namespace mirzaev\arming_bot\models\traits\yandex;

// Built-in libraries
use exception;

/**
 * Trait for "Yandex Disk"
 *
 * @package mirzaev\arming_bot\models\traits\yandex
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
trait disk
{
	/**
	 * Download file from "Yandex Disk"
	 *
	 * @param string $uri URI of the file from "Yandex Disk"
	 * @param string $destination Destination to write the file
	 * @param array &$errors Registry of errors
	 *
	 * @return bool The file is downloaded?
	 */
	private static function download(
		string $uri,
		string $destination,
		array &$errors = []
	): bool {
		try {
			if (!empty($uri)) {
				// Not empty URI

				if (!empty($destination)) {
					// Not empty destination

					// Initializing URL of the file
					$url = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key=$uri";

					// Checking if the file is available for download
					$ch = curl_init($url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_exec($ch);
					$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
					curl_close($ch);

					if ($code === 200) {
						// The file is available for download

						// Downloading the file and exit (success)
						return file_put_contents($destination, file_get_contents(json_decode(file_get_contents($url))?->href)) > 0;
					} else throw new exception("File not available for download: $uri");
				} else throw new exception("Empty destination");
			} else throw new exception("Empty URI");
		} catch (exception $e) {
			// Writing to the registry of errors
			$errors[] = [
				'text' => $e->getMessage(),
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'stack' => $e->getTrace()
			];
		}

		// Exit (fail)
		return false;
	}
}
