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

class VS_Setup {

    public static function init() {
        register_activation_hook(VS_PATH . 'vendor-space.php', [__CLASS__, 'activate_plugin']);
        add_action('init', [__CLASS__, 'fix_shop_page']);
        add_action('init', [__CLASS__, 'register_category_requests_cpt']);
        add_action('init', [__CLASS__, 'fix_woocommerce_pages']);
        add_action('init', [__CLASS__, 'ensure_stores_page_and_menu'], 25);
        add_action('init', [__CLASS__, 'ensure_customer_notifications_page'], 26);
        
        // Fix: Force DB creation if tables missing
        add_action('init', function() {
            if(isset($_GET['vs_fix_db'])) {
                self::create_chat_table();
                self::create_withdrawals_table();
                self::create_user_modules_table();
                self::create_license_keys_table();
                if (class_exists('VS_Ads')) {
                    VS_Ads::create_tables();
                }
                echo "<div style='background:green;color:white;padding:20px;z-index:99999;position:fixed;top:0;'>✅ Chat & Withdrawal & License Tables Created!</div>";
            }
        });
    }

    public static function register_category_requests_cpt() {
        $labels = [
            'name' => __('Category Requests', 'vendor-space'),
            'singular_name' => __('Category Request', 'vendor-space'),
        ];

        $args = [
            'labels' => $labels,
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => false,
            'supports' => ['title','editor','author'],
            'capability_type' => 'post',
        ];

        register_post_type('vs_category_request', $args);
    }

    public static function fix_shop_page() {
        if (!function_exists('wc_get_page_id')) return;

        $shop_page_id = wc_get_page_id('shop');
        if ($shop_page_id <= 0) return;

        $page = get_post($shop_page_id);
        if (!$page) return;

        $content = isset($page->post_content) ? trim($page->post_content) : '';
        $needs_fix = ($content === '' || strpos($content, 'Great things are on the horizon') !== false);
        if (!$needs_fix) return;

        wp_update_post([
            'ID'           => $shop_page_id,
            'post_content' => '<!-- wp:shortcode -->[products limit="12" columns="4"]<!-- /wp:shortcode -->',
        ]);

        if (isset($_GET['vs_fix_shop'])) {
            echo "<div style='position:fixed;top:50px;left:50%;transform:translateX(-50%);background:green;color:white;padding:20px;z-index:9999;'>??? Shop has been repaired! <a href='".get_permalink($shop_page_id)."' style='color:yellow;'>Click here to view Shop</a></div>";
            exit;
        }
    }


    public static function fix_woocommerce_pages() {
        if (!function_exists('wc_get_page_id')) return;

        // Fix Cart
        $cart_page_id = wc_get_page_id('cart');
        if ($cart_page_id > 0) {
            $page = get_post($cart_page_id);
            if ($page && (empty($page->post_content) || strpos($page->post_content, 'Great things are on the horizon') !== false)) {
                wp_update_post([
                    'ID' => $cart_page_id,
                    'post_content' => '<!-- wp:shortcode -->[woocommerce_cart]<!-- /wp:shortcode -->',
                ]);
            }
        }

        // Fix Checkout
        $checkout_page_id = wc_get_page_id('checkout');
        if ($checkout_page_id > 0) {
            $page = get_post($checkout_page_id);
            if ($page && (empty($page->post_content) || strpos($page->post_content, 'Great things are on the horizon') !== false)) {
                wp_update_post([
                    'ID' => $checkout_page_id,
                    'post_content' => '<!-- wp:shortcode -->[woocommerce_checkout]<!-- /wp:shortcode -->',
                ]);
            }
        }
    }

    public static function activate_plugin() {
        self::create_vendor_role();
        self::create_dashboard_page();
        self::create_dashboard_page();
        $stores_page_id = self::create_stores_page();
        self::maybe_add_stores_menu_item($stores_page_id);
        self::create_customer_notifications_page();
        self::create_chat_table();
        self::create_withdrawals_table();
        self::create_user_modules_table();
        self::create_license_keys_table();
        if (class_exists('VS_Ads')) {
            VS_Ads::create_tables();
        }
        flush_rewrite_rules();
    }

   private static function create_vendor_role() {
        $caps = [
            'read'            => true,
            'upload_files'    => true,   // ÙŠØ±ÙØ¹ ØµÙˆØ±
            'edit_products'   => true,
            'edit_shop_products' => true,
            'delete_products' => true,
        ];

        $role = get_role('vendor');
        if (!$role) {
            add_role('vendor', 'Vendor', $caps);
            return;
        }

        // Ensure existing role gets missing caps on update/activation.
        foreach ($caps as $cap => $grant) {
            if ($grant) {
                $role->add_cap($cap);
            }
        }
    }


    private static function create_dashboard_page() {
        $slug = 'vendor-dashboard';
        if (!get_page_by_path($slug)) {
            wp_insert_post([
                'post_title'   => 'Vendor Dashboard',
                'post_name'    => $slug,
                'post_content' => '[vendor_dashboard]',
                'post_status'  => 'publish',
                'post_type'    => 'page'
            ]);
        }
    }

    public static function ensure_stores_page_and_menu() {
        if (!is_admin() || !current_user_can('manage_options')) {
            return;
        }

        $stores_page_id = self::create_stores_page();
        if ($stores_page_id > 0) {
            self::maybe_add_stores_menu_item($stores_page_id);
        }
    }

    public static function ensure_customer_notifications_page() {
        if (!is_admin() || !current_user_can('manage_options')) {
            return;
        }
        self::create_customer_notifications_page();
    }

    private static function create_stores_page() {
        $slug = 'stores';
        $page = get_page_by_path($slug);
        if ($page && !empty($page->ID)) {
            return (int) $page->ID;
        }

        $page_id = wp_insert_post([
            'post_title'   => 'Stores',
            'post_name'    => $slug,
            'post_content' => '[vendor_stores]',
            'post_status'  => 'publish',
            'post_type'    => 'page',
        ]);

        if (is_wp_error($page_id)) {
            return 0;
        }

        return (int) $page_id;
    }

    private static function create_customer_notifications_page() {
        $slug = 'customer-notifications';
        $page = get_page_by_path($slug);
        if ($page && !empty($page->ID)) {
            return (int) $page->ID;
        }

        $page_id = wp_insert_post([
            'post_title'   => 'Customer Notifications',
            'post_name'    => $slug,
            'post_content' => '[custemor_notification]',
            'post_status'  => 'publish',
            'post_type'    => 'page',
        ]);

        if (is_wp_error($page_id)) {
            return 0;
        }

        return (int) $page_id;
    }

    private static function maybe_add_stores_menu_item($stores_page_id = 0) {
        if ($stores_page_id <= 0) {
            return;
        }

        if ((int) get_option('vs_stores_menu_item_added', 0) === 1) {
            return;
        }

        $menu_id = 0;
        $locations = get_nav_menu_locations();
        if (is_array($locations)) {
            foreach ($locations as $location_menu_id) {
                if (!empty($location_menu_id)) {
                    $menu_id = (int) $location_menu_id;
                    break;
                }
            }
        }

        if ($menu_id <= 0) {
            $menus = wp_get_nav_menus();
            if (!empty($menus) && !empty($menus[0]->term_id)) {
                $menu_id = (int) $menus[0]->term_id;
            }
        }

        if ($menu_id <= 0) {
            return;
        }

        $items = wp_get_nav_menu_items($menu_id);
        if (is_array($items)) {
            foreach ($items as $item) {
                if ((int) ($item->object_id ?? 0) === (int) $stores_page_id) {
                    update_option('vs_stores_menu_item_added', 1, false);
                    return;
                }
            }
        }

        $item_id = wp_update_nav_menu_item($menu_id, 0, [
            'menu-item-title'     => 'Stores',
            'menu-item-object'    => 'page',
            'menu-item-object-id' => (int) $stores_page_id,
            'menu-item-type'      => 'post_type',
            'menu-item-status'    => 'publish',
        ]);

        if (!is_wp_error($item_id)) {
            update_option('vs_stores_menu_item_added', 1, false);
        }
    }

    public static function create_chat_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'vs_chat';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            order_id bigint(20) NOT NULL,
            sender_id bigint(20) NOT NULL,
            message text NOT NULL,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            is_read tinyint(1) DEFAULT 0 NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    public static function create_withdrawals_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'vs_withdrawals';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            vendor_id bigint(20) NOT NULL,
            amount decimal(10,2) NOT NULL,
            status varchar(20) DEFAULT 'pending' NOT NULL,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            updated_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create user_modules table: tracks which PRO modules each user has purchased.
     */
    public static function create_user_modules_table() {
        global $wpdb;
        $table_name      = $wpdb->prefix . 'vs_user_modules';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table_name} (
            id          bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id     bigint(20) UNSIGNED NOT NULL,
            module_id   varchar(100)        NOT NULL,
            status      varchar(20)         NOT NULL DEFAULT 'active',
            purchased_at datetime            NOT NULL DEFAULT '0000-00-00 00:00:00',
            expires_at  datetime                      DEFAULT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY user_module (user_id, module_id),
            KEY user_id   (user_id),
            KEY module_id (module_id)
        ) {$charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    /**
     * Create license_keys table: stores generated license keys after payment.
     */
    public static function create_license_keys_table() {
        global $wpdb;
        $table_name      = $wpdb->prefix . 'vs_license_keys';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table_name} (
            id               bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id          bigint(20) UNSIGNED NOT NULL,
            license_key      varchar(64)         NOT NULL,
            module_id        varchar(100)        NOT NULL,
            payment_intent   varchar(255)        NOT NULL DEFAULT '',
            status           varchar(20)         NOT NULL DEFAULT 'active',
            created_at       datetime            NOT NULL DEFAULT '0000-00-00 00:00:00',
            activated_at     datetime                     DEFAULT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY license_key (license_key),
            KEY user_id (user_id)
        ) {$charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }
}

