<?php
if (!defined('ABSPATH')) {
    exit;
}

class Manfiet_Expense_Tracker_Other_Plugins {
    public function __construct() {
        add_action('admin_menu', [$this, 'add_other_plugins_page']);
    }

    public function add_other_plugins_page() {
        add_submenu_page(
            'manfi-expense-tracker',
            __('Other Plugins', 'manfi-expense-tracker'),
            __('Other Plugins', 'manfi-expense-tracker'),
            'manage_options',
            'manfiet-other-plugins',
            [$this, 'render_other_plugins_page'],
            35
        );
    }

    public function render_other_plugins_page() {
        // Clear transient caches so JSON changes and checkout URL map update instantly.
        delete_transient('manfiet_plugin_info_' . md5('dynamic-tags-for-elementor-pro'));
        $json_file = MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'includes/other-plugins.json';
        $cache_key = 'manfiet_other_plugins_' . md5($json_file . '|' . (string) @filemtime($json_file));
        delete_transient($cache_key);

        $plugins = $this->load_other_plugins_list();
        ?>
        <div class="wrap">
            <h2 class="wp-header-end" style="display:none;"></h2>
            <div class="manfiet-page-shell manfiet-page-shell-wide">
                <div class="manfiet-page-hero">
                    <div class="left-section">
                        <h1 class="manfiet-page-title"><?php esc_html_e('Other Plugins', 'manfi-expense-tracker'); ?></h1>
                        <p class="manfiet-page-subtitle"><?php esc_html_e('Discover other premium and productivity plugins by the same author to enhance your website.', 'manfi-expense-tracker'); ?></p>
                    </div>
                </div>

                <?php if (empty($plugins)) : ?>
                    <div class="manfiet-card">
                        <p><?php esc_html_e('No plugins found in the configuration. Please add plugin entries in includes/other-plugins.json.', 'manfi-expense-tracker'); ?></p>
                    </div>
                <?php else : ?>
                    <div class="manfiet-market-grid">
                        <?php foreach ($plugins as $plugin) : ?>
                            <?php
                            $plugin_data = $this->get_other_plugin_card_data($plugin);
                            $action      = $this->get_other_plugin_action_html($plugin_data);
                            ?>
                            <article class="manfiet-market-card">
                                <div class="manfiet-market-head">
                                    <img class="manfiet-market-icon" src="<?php echo esc_url($plugin_data['icon']); ?>" alt="<?php echo esc_attr($plugin_data['name']); ?>" />
                                    
                                    <div class="manfiet-market-content">
                                        <h2 class="manfiet-market-title"><?php echo esc_html($plugin_data['name']); ?></h2>
                                        <p class="manfiet-market-desc"><?php echo esc_html($plugin_data['description']); ?></p>
                                        
                                        <?php if (!empty($plugin_data['author'])) : ?>
                                            <p class="manfiet-market-author">
                                                <?php esc_html_e('By', 'manfi-expense-tracker'); ?>
                                                <?php echo wp_kses($plugin_data['author'], ['a' => ['href' => true, 'target' => true, 'rel' => true]]); ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="manfiet-market-actions">
                                    <?php echo wp_kses_post($action); ?>
                                    <a class="manfiet-button manfiet-button-secondary" href="<?php echo esc_url($plugin_data['details_url']); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('More Details', 'manfi-expense-tracker'); ?></a>
                                </div>

                                <div class="manfiet-market-foot">
                                    <div class="manfiet-market-stat">
                                        <span class="dashicons dashicons-star-filled" style="color: #fbbf24; font-size: 16px; width: 16px; height: 16px; margin-right: 4px; vertical-align: text-top;"></span>
                                        <strong><?php echo esc_html($plugin_data['rating_label']); ?></strong>
                                    </div>
                                    <div class="manfiet-market-stat">
                                        <span class="dashicons dashicons-download" style="color: #64748b; font-size: 16px; width: 16px; height: 16px; margin-right: 4px; vertical-align: text-top;"></span>
                                        <strong><?php echo esc_html($plugin_data['active_installs_label']); ?></strong>
                                    </div>
                                    <div class="manfiet-market-stat">
                                        <span class="dashicons dashicons-update" style="color: #64748b; font-size: 16px; width: 16px; height: 16px; margin-right: 4px; vertical-align: text-top;"></span>
                                        <span>
                                            <strong><?php esc_html_e('Updated:', 'manfi-expense-tracker'); ?></strong>
                                            <?php echo esc_html($plugin_data['last_updated_label']); ?>
                                        </span>
                                    </div>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private function load_other_plugins_list() {
        $json_file = MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'includes/other-plugins.json';
        $plugins   = [];

        $cache_key = 'manfiet_other_plugins_' . md5($json_file . '|' . (string) @filemtime($json_file));
        $cached    = get_transient($cache_key);

        if (is_array($cached)) {
            return $cached;
        }

        if (file_exists($json_file)) {
            $raw  = file_get_contents($json_file);
            $data = json_decode($raw, true);

            if (is_array($data)) {
                if (isset($data['plugins']) && is_array($data['plugins'])) {
                    $plugins = $data['plugins'];
                } else {
                    $plugins = $data;
                }
            }
        }

        $normalized_plugins = [];

        foreach ($plugins as $plugin) {
            if (!is_array($plugin)) {
                continue;
            }

            $slug = isset($plugin['slug']) ? sanitize_key($plugin['slug']) : '';
            $name = isset($plugin['name']) ? sanitize_text_field($plugin['name']) : '';
            $description = isset($plugin['description']) ? sanitize_text_field($plugin['description']) : '';
            $icon        = isset($plugin['icon']) ? esc_url_raw($plugin['icon']) : '';

            $details_url = isset($plugin['details_url']) ? esc_url_raw($plugin['details_url']) : '';

            if (empty($slug) || empty($name)) {
                continue;
            }

            $normalized_plugins[] = [
                'slug'        => $slug,
                'name'        => $name,
                'description' => $description,
                'icon'        => $icon,
                'details_url' => $details_url,
            ];
        }

        set_transient($cache_key, $normalized_plugins, 12 * HOUR_IN_SECONDS);

        return $normalized_plugins;
    }

    private function get_other_plugin_card_data($plugin) {
        $slug     = $plugin['slug'];
        $api_data = $this->fetch_wordpress_org_plugin_data($slug);

        $icon = !empty($plugin['icon']) ? $plugin['icon'] : '';

        if (empty($icon) && !empty($api_data['icon'])) {
            $icon = $api_data['icon'];
        }

        if (empty($icon)) {
            $icon = MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/img/icon-128x128.svg';
        }

        $description = !empty($plugin['description']) ? $plugin['description'] : '';

        if (empty($description) && !empty($api_data['short_description'])) {
            $description = wp_strip_all_tags($api_data['short_description']);
        }

        if (empty($description)) {
            $description = __('Install this plugin from wordpress.org plugin directory.', 'manfi-expense-tracker');
        }

        $details_url = !empty($plugin['details_url'])
            ? $plugin['details_url']
            : (!empty($api_data['details_url']) ? $api_data['details_url'] : 'https://wordpress.org/plugins/' . rawurlencode($slug) . '/');

        $has_rating = array_key_exists('rating', $api_data) && null !== $api_data['rating'];
        $has_num_ratings = array_key_exists('num_ratings', $api_data) && null !== $api_data['num_ratings'];
        $has_active_installs = array_key_exists('active_installs', $api_data) && null !== $api_data['active_installs'];

        $rating_value = $has_rating ? (float) $api_data['rating'] : null;
        $rating_count = $has_num_ratings ? (int) $api_data['num_ratings'] : null;
        $active_installs = $has_active_installs ? (int) $api_data['active_installs'] : null;
        $last_updated = !empty($api_data['last_updated']) ? mysql2date('F j, Y', $api_data['last_updated']) : __('Unknown', 'manfi-expense-tracker');

        $rating_label = __('Rating: N/A', 'manfi-expense-tracker');

        if (null !== $rating_value) {
            $rating_label = sprintf(
                /* translators: 1: Plugin rating out of 5, 2: Number of ratings. */
                __('Rating: %1$s/5 (%2$s)', 'manfi-expense-tracker'),
                number_format_i18n($rating_value, 1),
                number_format_i18n(null !== $rating_count ? $rating_count : 0)
            );
        }

        $active_installs_label = __('Active Installs: N/A', 'manfi-expense-tracker');

        if (null !== $active_installs) {
            if ($active_installs > 0) {
                /* translators: %s: Number of active installs. */
                $active_installs_label = sprintf(__('Active Installs: %s+', 'manfi-expense-tracker'), number_format_i18n($active_installs));
            } else {
                $active_installs_label = __('Active Installs: Less than 10', 'manfi-expense-tracker');
            }
        }

        return [
            'slug'                  => $slug,
            'name'                  => $plugin['name'],
            'description'           => $description,
            'icon'                  => $icon,
            'author'                => !empty($api_data['author']) ? $api_data['author'] : '',
            'details_url'           => $details_url,
            'rating_label'          => $rating_label,
            'active_installs_label' => $active_installs_label,
            'last_updated_label'    => $last_updated,
        ];
    }

    private function fetch_wordpress_org_plugin_data($slug) {
        $cache_key = 'manfiet_plugin_info_' . md5($slug);
        $cached    = get_transient($cache_key);

        if (is_array($cached)) {
            return $cached;
        }

        if (!function_exists('plugins_api')) {
            require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        }

        $api = plugins_api(
            'plugin_information',
            [
                'slug'   => $slug,
                'fields' => [
                    'short_description' => true,
                    'icons'             => true,
                    'active_installs'   => true,
                    'rating'            => true,
                    'num_ratings'       => true,
                    'last_updated'      => true,
                    'author'            => true,
                    'homepage'          => true,
                ],
            ]
        );

        if (is_wp_error($api) || !is_object($api)) {
            set_transient($cache_key, [], HOUR_IN_SECONDS);
            return [];
        }

        $icon = '';

        if (!empty($api->icons['2x'])) {
            $icon = $api->icons['2x'];
        } elseif (!empty($api->icons['1x'])) {
            $icon = $api->icons['1x'];
        } elseif (!empty($api->icons['svg'])) {
            $icon = $api->icons['svg'];
        } elseif (!empty($api->icons['default'])) {
            $icon = $api->icons['default'];
        }

        $data = [
            'short_description' => !empty($api->short_description) ? (string) $api->short_description : '',
            'icon'              => !empty($icon) ? esc_url_raw($icon) : '',
            'active_installs'   => isset($api->active_installs) ? (int) $api->active_installs : null,
            'rating'            => isset($api->rating) ? (float) $api->rating / 20 : null,
            'num_ratings'       => isset($api->num_ratings) ? (int) $api->num_ratings : null,
            'last_updated'      => !empty($api->last_updated) ? (string) $api->last_updated : '',
            'author'            => !empty($api->author) ? (string) $api->author : '',
            'details_url'       => 'https://wordpress.org/plugins/' . rawurlencode($slug) . '/',
        ];

        set_transient($cache_key, $data, 12 * HOUR_IN_SECONDS);

        return $data;
    }

    private function get_other_plugin_action_html($plugin_data) {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $slug        = $plugin_data['slug'];
        $all_plugins = get_plugins();
        $plugin_file = $this->find_plugin_file_by_slug($slug, $all_plugins);

        if ($plugin_file && is_plugin_active($plugin_file)) {
            return '<span class="manfiet-button button-disabled" aria-disabled="true">' . esc_html__('Installed', 'manfi-expense-tracker') . '</span>';
        }

        if ($plugin_file) {
            if (current_user_can('activate_plugins')) {
                $activate_url = wp_nonce_url(
                    self_admin_url('plugins.php?action=activate&plugin=' . urlencode($plugin_file)),
                    'activate-plugin_' . $plugin_file
                );

                return '<a class="manfiet-button manfiet-button-primary" href="' . esc_url($activate_url) . '">' . esc_html__('Activate', 'manfi-expense-tracker') . '</a>';
            }

            return '<span class="manfiet-button button-disabled" aria-disabled="true">' . esc_html__('Installed', 'manfi-expense-tracker') . '</span>';
        }

        if ('dynamic-tags-for-elementor-pro' === $slug) {
            return '<a class="manfiet-button manfiet-button-primary" href="' . esc_url($plugin_data['details_url']) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Install Now', 'manfi-expense-tracker') . '</a>';
        }

        if (current_user_can('install_plugins')) {
            $install_url = wp_nonce_url(
                self_admin_url('update.php?action=install-plugin&plugin=' . $slug),
                'install-plugin_' . $slug
            );

            return '<a class="manfiet-button manfiet-button-primary" href="' . esc_url($install_url) . '">' . esc_html__('Install Now', 'manfi-expense-tracker') . '</a>';
        }

        return '<span class="manfiet-button button-disabled" aria-disabled="true">' . esc_html__('Not Allowed', 'manfi-expense-tracker') . '</span>';
    }

    private function find_plugin_file_by_slug($slug, $all_plugins) {
        if (!is_array($all_plugins) || empty($slug)) {
            return null;
        }

        foreach (array_keys($all_plugins) as $plugin_file) {
            if ($plugin_file === $slug . '.php' || strpos($plugin_file, $slug . '/') === 0) {
                return $plugin_file;
            }
        }

        return null;
    }
}
