<?php

namespace EasyLinkAutomations;

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

/**
 * Minimal .env file loader.
 *
 * Reads key=value pairs from a flat file, auto-prefixes each key with
 * Config::VAR_PREFIX, and stores them in $_ENV. Values are cast to their
 * natural PHP type (int, float, bool, or string).
 */
final class Dotenv
{
    public static function load(string $path = ''): bool
    {
        if (!file_exists($path)) {
            return false;
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        foreach ($lines as $line) {
            $line = trim($line);

            // Skip comments and lines without =
            if (str_starts_with($line, '#') || !str_contains($line, '=')) {
                continue;
            }

            // Strip inline comments
            $commentPos = strpos($line, ' #');
            if ($commentPos !== false) {
                $line = substr($line, 0, $commentPos);
            }

            [$name, $value] = explode('=', trim($line), 2);

            $name  = Config::VAR_PREFIX . trim($name);
            $value = self::castValue(trim($value));

            if (!array_key_exists($name, $_ENV)) {
                $_ENV[$name] = $value;
            }
        }

        return true;
    }

    /**
     * Update or append a key in the .env file.
     */
    public static function setEnv(string $key, bool $flag): int|false
    {
        $envFilePath = realpath(__DIR__ . '/../../.env');

        if (!$envFilePath || !file_exists($envFilePath)) {
            return false;
        }

        $lines   = file($envFilePath, FILE_IGNORE_NEW_LINES);
        $value   = $flag ? 'true' : 'false';
        $pattern = "/^{$key}\s*=\s*(.*)/m";
        $found   = false;

        foreach ($lines as &$line) {
            if (preg_match($pattern, $line)) {
                $line  = "{$key} = {$value}";
                $found = true;
                break;
            }
        }

        unset($line);

        if (!$found) {
            $lines[] = "{$key} = {$value}";
        }

        return file_put_contents($envFilePath, implode("\n", $lines));
    }

    /**
     * Cast string values to their natural PHP types.
     */
    private static function castValue(string $value): mixed
    {
        if (is_numeric($value)) {
            return $value + 0;
        }

        return match (strtolower($value)) {
            'true'  => true,
            'false' => false,
            'null'  => null,
            default => $value,
        };
    }
}
