<?php
/**
 * Traveler Theme - License-based Admin Editing Restriction
 * Blocks editing capabilities on restricted admin pages if license is inactive
 * or activatezhk folder is missing.
 */

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

class ST_License_Admin_Restrict {

    private static $instance = null;
    private $restricted_pages = [];
    private $license_active = false;
    private $activatezhk_exists = false;
    private $license_page_slug = '';
    private $zhaket_buy_url = 'https://www.zhaket.com/store/web/salehgroup';

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->check_license_status();
        $this->set_restricted_pages();


        // Menu hiding is always hooked but checks status inside (most reliable)
        add_action('admin_menu', [$this, 'hide_restricted_menus'], 999);

        $should_restrict = (!$this->license_active || !$this->activatezhk_exists);

        if ($should_restrict && is_admin() && !defined('DOING_AJAX')) {
            add_action('admin_init', [$this, 'block_post_requests'], 1);
            add_action('admin_enqueue_scripts', [$this, 'enqueue_blocker_assets']);
            add_action('admin_footer', [$this, 'render_license_modal'], 9999);
        }
    }

    /**
     * Detect license active status from Zhaket Guard class
     * and check if activatezhk folder exists.
     */
    private function check_license_status() {
        $this->activatezhk_exists = is_dir(get_template_directory() . '/activatezhk');
        $this->license_active = false;
        $this->license_page_slug = 'db4d346ca8c3b84b03b495dba169c02a';

        if ($this->activatezhk_exists && class_exists('e67f2469ce1e2a80ac87459d84d')) {
            try {
                $this->license_active = (bool) \e67f2469ce1e2a80ac87459d84d::e5038dea7b4eb9acc3b818c77dc55d();
            } catch (Exception $e) {
                $this->license_active = false;
            }
        }
    }

    /**
     * Define the restricted admin page patterns.
     */
    private function set_restricted_pages() {
        global $pagenow;

        $this->restricted_pages = [
            // Exact admin.php?page= slugs
            ['page' => 'admin.php', 'param' => 'page', 'value' => 'st_traveler_options'],
            ['page' => 'admin.php', 'param' => 'page', 'value' => 'st_traveler_option'],
            ['page' => 'admin.php', 'param' => 'page', 'value' => 'wb_page_form_builder'],
            ['page' => 'admin.php', 'param' => 'page', 'value' => 'st_product_reg'],
            ['page' => 'admin.php', 'param' => 'page', 'value' => 'ot-settings'],

            // Post type listings and new posts
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_hotel'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'st_hotel'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'hotel_room'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'hotel_room'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_activity'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'st_activity'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_tours'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'st_tours'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_cars'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'st_cars'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_rental'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'st_rental'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'location'],
            ['page' => 'post-new.php', 'param' => 'post_type', 'value' => 'location'],

            // Taxonomy editing pages
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'hotel-theme'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'hotel-facilities'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'room_type'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'room-facilities'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'durations'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'st_tour_type'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'st_category_cars'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'car-features'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'brand'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'amenities'],
            ['page' => 'edit-tags.php', 'param' => 'taxonomy', 'value' => 'rental-types'],

            // Submenu pages under post types
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_hotel', 'subpage' => 'st_hotel_booking'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_activity', 'subpage' => 'st_activity_booking'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_tours', 'subpage' => 'st_tours_booking'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_cars', 'subpage' => 'st_car_booking'],
            ['page' => 'edit.php', 'param' => 'post_type', 'value' => 'st_rental', 'subpage' => 'st_rental_booking'],
        ];
    }

    /**
     * Determine if current admin page is restricted.
     */
    public function is_restricted_page() {
        if (!is_admin()) return false;

        global $pagenow;
        if (empty($pagenow)) return false;

        foreach ($this->restricted_pages as $rule) {
            if ($pagenow !== $rule['page']) continue;

            $param = $rule['param'];
            $value = $rule['value'];

            if (!isset($_GET[$param])) continue;
            if ($_GET[$param] !== $value) continue;

            if (isset($rule['subpage'])) {
                $subpage_key = 'page';
                if (!isset($_GET[$subpage_key]) || $_GET[$subpage_key] !== $rule['subpage']) {
                    continue;
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Block POST/DELETE/PUT requests on restricted pages to prevent edits.
     */
    public function block_post_requests() {
        if (!$this->is_restricted_page()) return;

        if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
            if (!$this->activatezhk_exists) {
                wp_die(
                    sprintf(
                        '<h1>%s</h1><p>%s</p><p><a href="%s" class="button button-primary" target="_blank">%s</a></p>',
                        esc_html__('نسخه غیر اورجینال', 'traveler'),
                        esc_html__('قالب شما نسخه اورجینال نمی‌باشد. امکان ذخیره تغییرات وجود ندارد.', 'traveler'),
                        esc_url($this->zhaket_buy_url),
                        esc_html__('خرید قالب نسخه اورجینال', 'traveler')
                    ),
                    esc_html__('نسخه غیر اورجینال', 'traveler'),
                    ['response' => 403, 'back_link' => false]
                );
            } else {
                wp_die(
                    sprintf(
                        '<h1>%s</h1><p>%s</p><p><a href="%s" class="button button-primary">%s</a></p>',
                        esc_html__('نیاز به لایسنس', 'traveler'),
                        esc_html__('لایسنس شما فعال نیست. امکان ذخیره تغییرات در این صفحه وجود ندارد. لطفاً لایسنس خود را فعال کنید تا بتوانید ویرایش کنید.', 'traveler'),
                        esc_url(admin_url('admin.php?page=' . esc_attr($this->license_page_slug))),
                        esc_html__('فعال‌سازی لایسنس', 'traveler')
                    ),
                    esc_html__('نیاز به لایسنس', 'traveler'),
                    ['response' => 403, 'back_link' => false]
                );
            }
        }
    }

    /**
     * Enqueue minimal inline CSS for the modal overlay.
     */
    public function enqueue_blocker_assets($hook) {
        if (!$this->is_restricted_page()) return;

        wp_add_inline_style('wp-admin', '
            /* Traveler License Modal Overlay */
            .st-license-modal-overlay {
                position: fixed;
                top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0, 0, 0, 0.85);
                z-index: 999999;
                display: flex;
                align-items: center;
                justify-content: center;
                direction: rtl;
                font-family: "Vazirmatn", "Tahoma", sans-serif;
            }
            .st-license-modal-box {
                background: #fff;
                border-radius: 8px;
                padding: 40px;
                max-width: 500px;
                width: 90%;
                text-align: center;
                box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            }
            .st-license-modal-box h2 {
                color: #dc3232;
                margin: 0 0 15px;
                font-size: 22px;
            }
            .st-license-modal-box p {
                color: #444;
                font-size: 15px;
                line-height: 1.7;
                margin-bottom: 25px;
            }
            .st-license-modal-box .button-primary {
                background: #2271b1;
                border-color: #2271b1;
                color: #fff;
                padding: 10px 24px;
                font-size: 15px;
                height: auto;
                border-radius: 4px;
                text-decoration: none;
                display: inline-block;
                cursor: pointer;
            }
            .st-license-modal-box .button-primary:hover {
                background: #135e96;
                border-color: #135e96;
            }
        ');
    }

    /**
     * Render the license modal overlay in admin footer.
     */
    public function render_license_modal() {
        // Hide license inactive modal for now (during license replacement / switch).
        return;
    }

    /**
     * Hide restricted admin menus when license is inactive or activatezhk is missing.
     */
    public function hide_restricted_menus() {
        // Temporarily disable license-based menu restrictions.
        // (During license switch, allow editing regardless of current license status.)
        return;
    }

}

// Initialize
ST_License_Admin_Restrict::get_instance();

