<?php
/**
 * Greenleaf License Installer
 *
 * Composer script to install the license activator mu-plugin
 * and optionally activate licenses via WP-CLI during deployment.
 *
 * Add to your Bedrock composer.json:
 *
 * "autoload": {
 *     "psr-4": {
 *         "Greenleaf\\Composer\\": "scripts/"
 *     }
 * },
 * "scripts": {
 *     "post-install-cmd": [
 *         "Greenleaf\\Composer\\LicenseInstaller::install"
 *     ],
 *     "post-update-cmd": [
 *         "Greenleaf\\Composer\\LicenseInstaller::install"
 *     ],
 *     "activate-licenses": [
 *         "Greenleaf\\Composer\\LicenseInstaller::activateViaWpCli"
 *     ]
 * }
 */

namespace Greenleaf\Composer;

use Composer\Script\Event;

class LicenseInstaller
{
    private const MU_PLUGIN_URL = 'https://raw.githubusercontent.com/greenleafadvancement/satis/main/templates/greenleaf-license-activator.php';
    private const MU_PLUGIN_NAME = 'greenleaf-license-activator.php';

    /**
     * Install the license activator mu-plugin
     */
    public static function install(Event $event): void
    {
        $io = $event->getIO();
        $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir');
        $projectDir = dirname($vendorDir);

        // Determine mu-plugins path (Bedrock structure)
        $muPluginsDir = $projectDir . '/web/app/mu-plugins';

        if (!is_dir($muPluginsDir)) {
            $io->write('<comment>mu-plugins directory not found, skipping license activator install</comment>');
            return;
        }

        $targetPath = $muPluginsDir . '/' . self::MU_PLUGIN_NAME;

        // Check if already installed
        if (file_exists($targetPath)) {
            $io->write('<info>License activator mu-plugin already installed</info>');
            return;
        }

        // Try to download from GitHub
        $io->write('<info>Installing Greenleaf License Activator mu-plugin...</info>');

        $content = @file_get_contents(self::MU_PLUGIN_URL);

        if ($content === false) {
            // Fall back to local copy if available in vendor
            $localCopy = $vendorDir . '/greenleafadvancement/satis/templates/' . self::MU_PLUGIN_NAME;
            if (file_exists($localCopy)) {
                $content = file_get_contents($localCopy);
            } else {
                $io->writeError('<error>Could not download license activator mu-plugin</error>');
                return;
            }
        }

        if (file_put_contents($targetPath, $content) !== false) {
            $io->write('<info>License activator installed to: ' . $targetPath . '</info>');
        } else {
            $io->writeError('<error>Failed to write license activator mu-plugin</error>');
        }
    }

    /**
     * Activate licenses via WP-CLI (for use in deployment scripts)
     *
     * This is an alternative to the mu-plugin approach for environments
     * where you want to activate once during deployment rather than on each request.
     */
    public static function activateViaWpCli(Event $event): void
    {
        $io = $event->getIO();
        $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir');
        $projectDir = dirname($vendorDir);
        $wpPath = $projectDir . '/web/wp';

        // Check if WP-CLI is available
        $wpCli = $vendorDir . '/bin/wp';
        if (!file_exists($wpCli)) {
            $wpCli = 'wp'; // Try system WP-CLI
        }

        // Define license activations
        $licenses = [
            'YOOTHEME_API_KEY' => function ($key) use ($wpCli, $wpPath) {
                $config = json_encode(['apikey' => $key]);
                return "{$wpCli} option update yootheme '{$config}' --format=json --path={$wpPath}";
            },
            'ACF_PRO_LICENSE' => function ($key) use ($wpCli, $wpPath) {
                return "{$wpCli} option update acf_pro_license '{$key}' --path={$wpPath}";
            },
            'PMP_LICENSE_KEY' => function ($key) use ($wpCli, $wpPath) {
                $config = json_encode(['license_key' => $key, 'license_status' => 'valid']);
                return "{$wpCli} option update permalink_manager_pro_license '{$config}' --format=json --path={$wpPath}";
            },
            'URE_LICENSE_KEY' => function ($key) use ($wpCli, $wpPath) {
                return "{$wpCli} option update ure_license_key '{$key}' --path={$wpPath}";
            },
            'LOGINWP_LICENSE_KEY' => function ($key) use ($wpCli, $wpPath) {
                return "{$wpCli} option update loginwp_license_key '{$key}' --path={$wpPath}";
            },
        ];

        $activated = 0;

        foreach ($licenses as $envVar => $commandBuilder) {
            $key = getenv($envVar);
            if (empty($key)) {
                // Also check for defined constant
                if (defined($envVar)) {
                    $key = constant($envVar);
                }
            }

            if (empty($key)) {
                continue;
            }

            $command = $commandBuilder($key);
            $io->write("<info>Activating {$envVar}...</info>");

            $output = [];
            $returnCode = 0;
            exec($command . ' 2>&1', $output, $returnCode);

            if ($returnCode === 0) {
                $io->write("<info>  ✓ Activated</info>");
                $activated++;
            } else {
                $io->writeError("<error>  ✗ Failed: " . implode("\n", $output) . "</error>");
            }
        }

        $io->write("<info>Activated {$activated} license(s)</info>");
    }
}
