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

class cookie_consent_Plugin_Updater {
    private $plugin_file;
    private $plugin_slug;   // logical slug (e.g., "slider")
    private $plugin_folder; // folder slug (dirname of plugin basename)
    private $remote_url;

    public function __construct($plugin_file, $plugin_slug, $remote_url) {
        $this->plugin_file   = $plugin_file;
        $this->plugin_slug   = $plugin_slug;
        $this->plugin_folder = dirname(plugin_basename($plugin_file));
        $this->remote_url    = $remote_url;

        add_filter('pre_set_site_transient_update_plugins', [$this, 'check_for_update']);
        add_filter('plugins_api',                           [$this, 'plugin_info'], 20, 3);
        add_filter('plugin_row_meta',                       [$this, 'add_view_details_link'], 10, 4);
    }

    private function fetch_json() {
        $res = wp_remote_get($this->remote_url, ['timeout' => 12]);
        if (is_wp_error($res) || wp_remote_retrieve_response_code($res) !== 200) return null;
        $body = wp_remote_retrieve_body($res);
        $json = json_decode($body);
        return (is_object($json) || is_array($json)) ? $json : null;
    }

    public function check_for_update($checked_data) {
        if (empty($checked_data->checked)) return $checked_data;

        $plugin_basename = plugin_basename($this->plugin_file);
        if (!isset($checked_data->checked[$plugin_basename])) return $checked_data;

        $plugin_data    = get_plugin_data($this->plugin_file);
        $plugin_version = $plugin_data['Version'];

        $remote = $this->fetch_json();
        if (!$remote) return $checked_data;

        // Accept either "version" (new) or "new_version" (old)
        $remote_version = $remote->version ?? $remote->new_version ?? null;
        if (!$remote_version) return $checked_data;

        if (version_compare($plugin_version, $remote_version, '<')) {
            $checked_data->response[$plugin_basename] = (object)[
                'slug'        => $this->plugin_folder,                         // WP expects folder slug here
                'plugin'      => $plugin_basename,
                'new_version' => $remote_version,
                'package'     => $remote->download_url ?? $remote->package ?? '',
                'url'         => $remote->homepage    ?? $remote->url     ?? '',
            ];
        }
        return $checked_data;
    }

    public function plugin_info($false, $action, $args) {
        if ($action !== 'plugin_information') return $false;

        // WordPress passes the folder slug to this handler
        $slug = $args->slug ?? '';
        if ($slug !== $this->plugin_folder && $slug !== $this->plugin_slug) return $false;

        $remote = $this->fetch_json();
        if (!$remote) return $false;

		$sections = [];
		if (!empty($remote->sections) && is_object($remote->sections)) {
			foreach (['description','installation','faq','changelog','screenshots'] as $k) {
				if (isset($remote->sections->$k)) $sections[$k] = (string)$remote->sections->$k;
			}
		} else {
			$sections['description']  = (string)($remote->description  ?? '');
			$sections['installation'] = (string)($remote->installation ?? '');
			$sections['faq']          = (string)($remote->faq          ?? '');
			$sections['changelog']    = (string)($remote->changelog    ?? '');
			$sections['screenshots']  = (string)($remote->screenshots  ?? '');
		}

        // --- Banners: accept nested or flat keys ---
        $banners = [];
        if (!empty($remote->banners) && is_object($remote->banners)) {
            $banners['low']  = $remote->banners->low  ?? '';
            $banners['high'] = $remote->banners->high ?? '';
        } else {
            $banners['low']  = $remote->banner_low  ?? '';
            $banners['high'] = $remote->banner_high ?? '';
        }

        // --- Icons: accept nested or flat keys ---
        $icons = [];
        if (!empty($remote->icons) && is_object($remote->icons)) {
            $icons['1x'] = $remote->icons->{'1x'} ?? '';
            $icons['2x'] = $remote->icons->{'2x'} ?? '';
            if (!empty($remote->icons->svg)) $icons['svg'] = $remote->icons->svg;
        } else {
            $icons['1x'] = $remote->icon_1x ?? '';
            $icons['2x'] = $remote->icon_2x ?? '';
            if (!empty($remote->icon_svg)) $icons['svg'] = $remote->icon_svg;
        }

        $obj = (object)[
            'name'           => (string)($remote->name           ?? 'Slider'),
            'slug'           => $this->plugin_folder, // use folder slug for modal routing
            'version'        => (string)($remote->version        ?? $remote->new_version ?? ''),
            'author'         => (string)($remote->author         ?? ''),
            'author_profile' => (string)($remote->author_profile ?? ''),
            'homepage'       => (string)($remote->homepage       ?? ''),
            'download_link'  => (string)($remote->download_url   ?? $remote->package ?? ''),
            'requires'       => (string)($remote->requires       ?? ''),
            'tested'         => (string)($remote->tested         ?? ''),
            'requires_php'   => (string)($remote->requires_php   ?? ''),
            'last_updated'   => (string)($remote->last_updated   ?? ''),
            'sections'       => $sections,
            'banners'        => $banners,
            'icons'          => $icons,
            'plugin'         => plugin_basename($this->plugin_file),
            // harmless defaults if your JSON doesn’t provide these
            'rating'         => (int)($remote->rating          ?? 100),
            'num_ratings'    => (int)($remote->num_ratings     ?? 1),
            'active_installs'=> (int)($remote->active_installs ?? 1)
        ];

        return $obj;
    }

    public function add_view_details_link($plugin_meta, $plugin_file, $plugin_data, $status) {
        if ($plugin_file !== plugin_basename($this->plugin_file)) return $plugin_meta;

        $details_url = add_query_arg(
            [
                'tab'       => 'plugin-information',
                'plugin'    => $this->plugin_folder, // must match plugin_info slug handling
                'TB_iframe' => 'true',
                'width'     => '772',
                'height'    => '949'
            ],
            admin_url('plugin-install.php')
        );

        $plugin_meta[] = sprintf(
            '<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
            esc_url($details_url),
            esc_attr(sprintf(__('More information about %s'), $plugin_data['Name'])),
            esc_attr($plugin_data['Name']),
            __('View details')
        );
        return $plugin_meta;
    }
}
