<?php

declare(strict_types=1);

namespace SiteFort\Modules\Cloud\Service;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Entitlements {
	private const DEFAULT_FLAGS = [
		'scan.enabled'           => true,
		'scan.on_demand.enabled' => true,
		'scan.scheduled.enabled' => false,
		'repair.enabled'         => false,
	];

	public static function all(): array {
		$settings = CloudSettings::get_all();
		$entitlements = $settings['entitlements'] ?? [];

		return is_array( $entitlements ) ? $entitlements : [];
	}

	public static function isEnabled( string $key ): bool {
		$entitlements = self::all();
		if ( array_key_exists( $key, $entitlements ) ) {
			return self::normalize_bool( $entitlements[ $key ] );
		}

		return self::DEFAULT_FLAGS[ $key ] ?? false;
	}

	public static function allowsScanning(): bool {
		return self::isEnabled( 'scan.enabled' );
	}

	public static function allowsOnDemandScans(): bool {
		return self::allowsScanning() && self::isEnabled( 'scan.on_demand.enabled' );
	}

	public static function allowsScheduledScans(): bool {
		return self::allowsScanning() && self::isEnabled( 'scan.scheduled.enabled' );
	}

	public static function allowsRepair(): bool {
		return self::isEnabled( 'repair.enabled' );
	}

	private static function normalize_bool( $value ): bool {
		if ( is_bool( $value ) ) {
			return $value;
		}

		if ( is_numeric( $value ) ) {
			return (int) $value === 1;
		}

		if ( is_string( $value ) ) {
			$normalized = strtolower( trim( $value ) );
			if ( in_array( $normalized, [ '1', 'true', 'yes', 'on' ], true ) ) {
				return true;
			}
			if ( in_array( $normalized, [ '0', 'false', 'no', 'off', '' ], true ) ) {
				return false;
			}
		}

		return ! empty( $value );
	}
}
