<?php

namespace PloverCRM\Core;

/**
 * Module Installer
 * 
 * Handles module installation and updates
 */
class ModuleInstaller
{
    /**
     * @var string Repository URL
     */
    private $repositoryUrl = 'https://webplover.com/downloads/plover-crm/modules.json';

    /**
     * Get available modules from repository
     * 
     * @return array|WP_Error
     */
    public function getAvailableModules()
    {
        $transient_key = 'plover_crm_available_modules';
        $cached = get_transient($transient_key);

        if ($cached !== false) {
            return $cached;
        }

        $response = wp_remote_get($this->repositoryUrl, ['timeout' => 10]);

        if (is_wp_error($response)) {
            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data['modules']) || !is_array($data['modules'])) {
            return new \WP_Error('invalid_response', 'Invalid repository response');
        }

        set_transient($transient_key, $data['modules'], HOUR_IN_SECONDS);
        return $data['modules'];
    }

    /**
     * Install a module
     * 
     * @param string $slug Module slug
     * @param string $downloadUrl Download URL
     * @return array
     */
    public function installModule(string $slug, string $downloadUrl): array
    {
        // Check license
        if (!\PloverCRM\Common\LicenseChecker::isValid()) {
            return ['success' => false, 'message' => 'Domain not licensed'];
        }

        // Download module
        $tmpFile = download_url($downloadUrl);

        if (is_wp_error($tmpFile)) {
            return ['success' => false, 'message' => $tmpFile->get_error_message()];
        }

        // Extract to modules directory
        $modulesDir = PLOVER_CRM_PLUGIN_PATH . 'app/Modules/';

        require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';

        $result = unzip_file($tmpFile, $modulesDir);
        @unlink($tmpFile);

        if (is_wp_error($result)) {
            return ['success' => false, 'message' => $result->get_error_message()];
        }

        // Clear cache
        delete_transient('plover_crm_available_modules');

        return ['success' => true, 'message' => 'Module installed successfully'];
    }

    /**
     * Get installed module version
     * 
     * @param string $slug Module slug
     * @return string|null
     */
    public function getInstalledVersion(string $slug): ?string
    {
        $plugin = Plugin::getInstance();
        $allModules = $plugin->getAllDiscoveredModules();

        foreach ($allModules as $moduleId => $moduleInstance) {
            if ($moduleId === $slug) {
                $metadata = $moduleInstance->getMetadata();
                return $metadata['version'] ?? null;
            }
        }

        return null;
    }

    /**
     * Check if module needs update
     * 
     * @param string $slug Module slug
     * @param string $latestVersion Latest version from repository
     * @return bool
     */
    public function needsUpdate(string $slug, string $latestVersion): bool
    {
        $installedVersion = $this->getInstalledVersion($slug);

        if (!$installedVersion) {
            return false;
        }

        return version_compare($installedVersion, $latestVersion, '<');
    }
}
