<?php

use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Database\QueryException;

function formatDate( $date ): string {
	return Carbon::parse( $date )->format( getOption( 'ui', 'dateFormat', 'F j, Y' ) );
}

function formatTime( $date ): string {
	return Carbon::parse( $date )->format( getOption( 'ui', 'timeFormat', 'H:i' ) );
}

function formatDatetime( $date ): string {
	return Carbon::parse( $date )->format( getOption( 'ui', 'dateFormat', 'F j, Y' ) . ' ' . getOption( 'ui', 'timeFormat', 'H:i' ) );
}

function getOption( $group, $name, $default = '' ): string {
	try {
		$option = Setting::select( 'value' )->where( [
			'group' => $group,
			'name'  => $name
		] )->first();

		if ( $option ) {
			return $option->value;
		}
	} catch ( QueryException $e ) {
		return $default;
	}

	return $default;
}

function getLangDirection( $language ): string {
	return in_array( $language, [ 'ar' ] ) ? 'rtl' : 'ltr';

}

function generateLicenseKey( $characters, $chunksNumber, $chunkLength ): string {
	$characters_length = strlen( $characters );
	$license_chunks    = array();

	for ( $i = 0; $i < $chunksNumber; $i ++ ) {
		$chunk = '';

		for ( $j = 0; $j < $chunkLength; $j ++ ) {
			$chunk .= $characters[ rand( 0, $characters_length - 1 ) ];
		}

		$license_chunks[] = $chunk;
	}

	return implode( '-', $license_chunks );
}

function isEnvatoPurchaseCode( $purchase_code ): bool {
	if ( ! preg_match( "/^([a-f0-9]{8})-(([a-f0-9]{4})-){3}([a-f0-9]{12})$/i", $purchase_code ) ) {
		return false;
	}

	return true;
}

function getEnvatoPurchase( $purchase_code, $personalToken = '' ): array {
	return json_decode(
		Http::withToken( $personalToken != '' ? $personalToken : getOption( 'envato', 'personalToken' ) )
		    ->get( "https://api.envato.com/v3/market/author/sale?code=" . trim( $purchase_code ) )
		    ->body(),
		true
	);
}

function can( $capability ): bool {
	return in_array( $capability, Auth::user()->getCapabilities() );
}


/**
 * @param array $requestData
 * @param mixed $private_key
 * @param mixed $passphrase
 * @param mixed $algorithm
 *
 * @return array
 */
function sign( array $requestData, mixed $private_key, mixed $passphrase, mixed $algorithm ): array {
	$requestData['timestamp'] = time();
	$response                 = base64_encode( json_encode( $requestData ) );
	$binary_signature         = '';

	if ( extension_loaded( 'openssl' ) ) {
		if ( $private_key == '' ) {
			$signature = __( 'Private key not set' );
		} else {
			try {
				$pk_id     = openssl_pkey_get_private( $private_key, $passphrase );
				$is_signed = openssl_sign( $response, $binary_signature, $pk_id, (int) $algorithm );
				if ( $is_signed ) {
					$signature = base64_encode( $binary_signature );
				} else {
					$signature = openssl_error_string();
				}
			} catch ( Exception ) {
				$signature = __( 'Supplied key param cannot be coerced into a private key' );
			}
		}
	} else {
		$signature = __( 'Openssl is not installed on your server' );
	}

	return array( $requestData, $response, $signature );
}

function strToColor( $str ): string {
	return '#' . substr( md5( $str ), 0, 6 );
}

function getKeevaultProductInfo(): array {
	return [
		'appVersion' => [
			'displayName' => __( 'Keevault Version' ),
			'value'       => '1.0.3'
		],
	];
}

function autoMigrate(): void {
	if ( file_exists( storage_path( 'installed' ) ) && ! file_exists( storage_path( 'version_101_update_installed' ) ) ) {
		Artisan::call( 'migrate', array( '--path' => 'database/migrations/2024_03_14_194454_add_endpoint_permission_to_api_keys_table.php', '--force' => true ) );

		file_put_contents( storage_path( 'version_101_update_installed' ), '' );
	}
}