<?php
/*
Plugin Name: Vendora Free
 * Description: Marketplace plugin for WordPress
Version: 1.0 
 * Requires Plugins: woocommerce

Text Domain: vendor-space
Domain Path: /languages
*/

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


add_action('admin_init', 'vendora_plugin_check_theme');

function vendora_plugin_check_theme()
{

    $theme = wp_get_theme();


    $active_theme = $theme->get_stylesheet();

    if ($active_theme !== 'Vendora') {

        add_action('admin_notices', function () {
            echo '<div class="notice notice-error is-dismissible">
                <p><strong>Vendora Plugin:</strong> You need to install and activate the <strong>Vendora Theme</strong> to use this plugin properly.</p>
            </div>';
        });

    }
}

define('VS_PATH', plugin_dir_path(__FILE__));
define('VS_URL', plugin_dir_url(__FILE__));
define('VS_TEXT_DOMAIN', 'vendor-space');

/**
 * Ensure vendor role has necessary capabilities for product management and uploads.
 * Added on plugin activation and removed on deactivation.
 */
function vs_add_vendor_caps()
{
    $role = get_role('vendor');
    if (!$role)
        return;
    $caps = [
        'edit_shop_products',
        'edit_products',
        'delete_products',
        'upload_files',
    ];
    foreach ($caps as $cap) {
        if (!$role->has_cap($cap)) {
            $role->add_cap($cap);
        }
    }
}



function vs_remove_vendor_caps()
{
    $role = get_role('vendor');
    if (!$role)
        return;
    $caps = [
        'edit_shop_products',
        'edit_products',
        'delete_products',
        'upload_files',
    ];
    foreach ($caps as $cap) {
        if ($role->has_cap($cap)) {
            $role->remove_cap($cap);
        }
    }
}

register_activation_hook(__FILE__, 'vs_add_vendor_caps');
register_deactivation_hook(__FILE__, 'vs_remove_vendor_caps');

/**
 * Store currency: if saved in Vendor Space → Settings → General, use it;
 * otherwise WooCommerce → Settings → General (woocommerce_currency).
 */
function vs_get_store_currency()
{
    $saved = get_option('vs_settings', []);
    if (is_array($saved) && !empty($saved['general']['currency'])) {
        $code = strtoupper(preg_replace('/[^A-Za-z]/', '', (string) $saved['general']['currency']));
        if (strlen($code) === 3) {
            return $code;
        }
    }
    return (string) get_option('woocommerce_currency', 'USD');
}

add_filter('woocommerce_currency', function ($currency) {
    return vs_get_store_currency();
}, 20, 1);

add_filter('woocommerce_currency_pos', function ($pos) {
    $saved = get_option('vs_settings', []);
    if (!is_array($saved) || empty($saved['general']['currency_position'])) {
        return $pos;
    }
    $p = (string) $saved['general']['currency_position'];
    if (in_array($p, ['left', 'right', 'left_space', 'right_space'], true)) {
        return $p;
    }
    return $pos;
}, 20, 1);

// Inclure les classes
require_once VS_PATH . 'includes/class-vs-setup.php';
require_once VS_PATH . 'includes/class-vs-orders.php';
require_once VS_PATH . 'includes/class-vs-dashboard.php';
require_once VS_PATH . 'includes/class-vs-profile.php';
require_once VS_PATH . 'includes/class-vs-stores.php';
require_once VS_PATH . 'includes/class-vs-core.php';
require_once VS_PATH . 'includes/class-vs-categories.php';
require_once VS_PATH . 'includes/class-vs-settings.php';
require_once VS_PATH . 'includes/class-vs-commission.php';
require_once VS_PATH . 'includes/class-vs-wallet.php';
require_once VS_PATH . 'includes/class-vs-admin-menu-badge-v2.php';
require_once VS_PATH . 'login/login.php';
require_once VS_PATH . 'includes/class-vs-vendors.php';
require_once VS_PATH . 'includes/class-vs-admin-settings.php';
require_once VS_PATH . 'includes/class-vs-admin-moderation.php';
require_once VS_PATH . 'includes/class-vs-restore.php';
require_once VS_PATH . 'includes/class-vs-ajax-pagination.php';

require_once VS_PATH . 'includes/class-vs-reports.php';
require_once VS_PATH . 'includes/class-vs-admin-pages.php';
require_once VS_PATH . 'includes/class-vs-modules.php';
require_once VS_PATH . 'includes/class-vs-withdrawals.php';

add_action('wp_ajax_save_vendor_iban', function () {

    if (!is_user_logged_in()) {
        wp_send_json_error('Not logged in');
    }

    $user_id = get_current_user_id();

    $iban = sanitize_text_field($_POST['iban']);

    update_user_meta($user_id, 'vendor_iban', $iban);

    wp_send_json_success('IBAN saved');
});
function vs_create_withdrawal_table()
{
    global $wpdb;

    $table = $wpdb->prefix . 'vs_withdrawals';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        vendor_id BIGINT NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        status VARCHAR(20) DEFAULT 'pending',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    ) $charset";

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

register_activation_hook(__FILE__, 'vs_create_withdrawal_table');
function vs_create_license_table()
{
    global $wpdb;

    $table = $wpdb->prefix . "vs_licenses";

    $sql = "CREATE TABLE $table (
        id INT AUTO_INCREMENT PRIMARY KEY,
        license_key VARCHAR(255),
        order_id INT,
        product_id INT,
        status VARCHAR(20) DEFAULT 'inactive',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'vs_create_license_table');
add_action('wp_ajax_request_withdrawal', function () {

    global $wpdb;

    $user_id = get_current_user_id();
    $amount = floatval($_POST['amount']);

    $wpdb->insert($wpdb->prefix . 'vs_withdrawals', [
        'vendor_id' => $user_id,
        'amount' => $amount,
        'status' => 'pending'
    ]);

    wp_send_json_success('Request sent');
});

// Classes already registered on plugins_loaded below or manually on init

function vs_load_textdomain()
{
    load_plugin_textdomain(VS_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/languages');
}
// Do not hook to init separately; we'll call it in the main initialization function

// Log wp_mail failures to help debug local SMTP issues (XAMPP/localhost often can't send mail).
function vs_log_wp_mail_failed($wp_error)
{
    try {
        if (!($wp_error instanceof WP_Error)) {
            return;
        }
        $data = $wp_error->get_error_data();
        $msg = $wp_error->get_error_message();
        error_log('VS wp_mail_failed: ' . $msg . ' | data=' . wp_json_encode($data));
    } catch (\Throwable $t) {
        // ignore
    }
}
add_action('wp_mail_failed', 'vs_log_wp_mail_failed', 10, 1);



add_action('init', function () {
    // 🔥 هذا هو الرابط مع Pro
    do_action('vs_pro_init_modules');

});




function vs_get_enabled_locales()
{
    $locales = array_merge(['en_US'], get_available_languages());
    return array_values(array_unique(array_filter(array_map('sanitize_text_field', $locales))));
}

function vs_get_requested_locale()
{
    $saved = '';
    if (function_exists('is_user_logged_in') && is_user_logged_in()) {
        $saved = (string) get_user_meta(get_current_user_id(), 'vs_locale', true);
    }

    if ($saved && in_array($saved, vs_get_enabled_locales(), true)) {
        return $saved;
    }

    return '';
}

function vs_filter_runtime_locale($locale)
{
    if (is_admin() && !wp_doing_ajax()) {
        return $locale;
    }

    $requested = vs_get_requested_locale();
    return $requested ?: $locale;
}
add_filter('locale', 'vs_filter_runtime_locale', 20);
add_filter('determine_locale', 'vs_filter_runtime_locale', 20);

function vs_set_locale_ajax()
{
    check_ajax_referer('vs_nonce', 'security');

    if (!is_user_logged_in()) {
        wp_send_json_error(__('You must be logged in.', VS_TEXT_DOMAIN));
    }

    $locale = sanitize_text_field((string) ($_POST['locale'] ?? ''));
    $allowed = vs_get_enabled_locales();

    if (!in_array($locale, $allowed, true)) {
        wp_send_json_error(__('Invalid language.', VS_TEXT_DOMAIN));
    }

    update_user_meta(get_current_user_id(), 'vs_locale', $locale);

    if (current_user_can('manage_options')) {
        update_option('WPLANG', $locale);
    }

    wp_send_json_success([
        'message' => __('Language updated successfully.', VS_TEXT_DOMAIN),
        'locale' => $locale,
    ]);
}
add_action('wp_ajax_vs_set_locale', 'vs_set_locale_ajax');

function vs_get_dashboard_i18n_strings()
{
    return [
        'loading' => __('Loading...', VS_TEXT_DOMAIN),
        'warning' => __('Warning', VS_TEXT_DOMAIN),
        'error' => __('Error', VS_TEXT_DOMAIN),
        'success' => __('Success', VS_TEXT_DOMAIN),
        'info' => __('Info', VS_TEXT_DOMAIN),
        'request_failed' => __('Request failed', VS_TEXT_DOMAIN),
        'request_failed_status' => __('Request failed: %s', VS_TEXT_DOMAIN),
        'server_error_try_again' => __('Server error. Please try again.', VS_TEXT_DOMAIN),
        'connection_failed' => __('Connection failed', VS_TEXT_DOMAIN),
        'tab_not_found' => __('Tab not found:', VS_TEXT_DOMAIN),
        'edit' => __('Edit', VS_TEXT_DOMAIN),
        'delete' => __('Delete', VS_TEXT_DOMAIN),
        'view' => __('View', VS_TEXT_DOMAIN),
        'quick_edit' => __('Quick Edit', VS_TEXT_DOMAIN),
        'save' => __('Save', VS_TEXT_DOMAIN),
        'cancel' => __('Cancel', VS_TEXT_DOMAIN),
        'actions' => __('Actions', VS_TEXT_DOMAIN),
        'image' => __('Image', VS_TEXT_DOMAIN),
        'name' => __('Name', VS_TEXT_DOMAIN),
        'categories' => __('Categories', VS_TEXT_DOMAIN),
        'price' => __('Price', VS_TEXT_DOMAIN),
        'vendor' => __('Vendor', VS_TEXT_DOMAIN),
        'stock' => __('Stock', VS_TEXT_DOMAIN),
        'no_image' => __('No Image', VS_TEXT_DOMAIN),
        'add_category' => __('Add Category', VS_TEXT_DOMAIN),
        'edit_category' => __('Edit Category', VS_TEXT_DOMAIN),
        'delete_category' => __('Delete category?', VS_TEXT_DOMAIN),
        'delete_category_confirm' => __('Delete this category permanently?', VS_TEXT_DOMAIN),
        'confirm_delete' => __('Delete', VS_TEXT_DOMAIN),
        'deleting' => __('Deleting...', VS_TEXT_DOMAIN),
        'creating' => __('Creating...', VS_TEXT_DOMAIN),
        'saving' => __('Saving...', VS_TEXT_DOMAIN),
        'missing_name' => __('Missing name', VS_TEXT_DOMAIN),
        'category_name_required' => __('Category name is required.', VS_TEXT_DOMAIN),
        'prev' => __('Prev', VS_TEXT_DOMAIN),
        'next' => __('Next', VS_TEXT_DOMAIN),
        'missing_attributes' => __('Missing attributes', VS_TEXT_DOMAIN),
        'add_attribute_values' => __('Add at least one attribute with values.', VS_TEXT_DOMAIN),
        'adding_product' => __('Adding Product...', VS_TEXT_DOMAIN),
        'product_added_successfully' => __('Product added successfully', VS_TEXT_DOMAIN),
        'failed_to_add_product' => __('Failed to add product', VS_TEXT_DOMAIN),
        'failed_to_add_product_with_error' => __('Failed to add product: %s', VS_TEXT_DOMAIN),
        'product_updated_successfully' => __('Product updated successfully', VS_TEXT_DOMAIN),
        'update_failed' => __('Update failed.', VS_TEXT_DOMAIN),
        'ajax_request_failed' => __('AJAX request failed.', VS_TEXT_DOMAIN),
        'delete_permanently' => __('Delete Permanently?', VS_TEXT_DOMAIN),
        'yes_delete_forever' => __('Yes, Delete Forever', VS_TEXT_DOMAIN),
        'delete_product' => __('Delete Product?', VS_TEXT_DOMAIN),
        'delete_permanently_action' => __('Delete Permanently', VS_TEXT_DOMAIN),
        'pending_approval' => __('Pending Approval', VS_TEXT_DOMAIN),
        'published' => __('Published', VS_TEXT_DOMAIN),
        'draft' => __('Draft', VS_TEXT_DOMAIN),
        'processing' => __('Processing', VS_TEXT_DOMAIN),
        'completed' => __('Completed', VS_TEXT_DOMAIN),
        'move_to_trash' => __('Move to Trash', VS_TEXT_DOMAIN),
        'move_product_to_trash_or_delete' => __('Do you want to move this product to the trash or delete it permanently?', VS_TEXT_DOMAIN),
        'moved_to_trash' => __('Moved to Trash!', VS_TEXT_DOMAIN),
        'deleted' => __('Deleted!', VS_TEXT_DOMAIN),
        'product_moved_to_trash' => __('Product has been moved to trash.', VS_TEXT_DOMAIN),
        'product_deleted_permanently' => __('Product has been permanently deleted.', VS_TEXT_DOMAIN),
        'trashing' => __('Trashing...', VS_TEXT_DOMAIN),
        'please_wait' => __('Please wait', VS_TEXT_DOMAIN),
        'failed_to_delete' => __('Failed to delete', VS_TEXT_DOMAIN),
        'failed_to_delete_product' => __('Failed to delete product', VS_TEXT_DOMAIN),
        'restored' => __('Restored!', VS_TEXT_DOMAIN),
        'product_restored' => __('Product has been restored.', VS_TEXT_DOMAIN),
        'restoring' => __('Restoring...', VS_TEXT_DOMAIN),
        'restoring_selected' => __('Restoring Selected...', VS_TEXT_DOMAIN),
        'failed_to_restore' => __('Failed to restore', VS_TEXT_DOMAIN),
        'failed_to_restore_product' => __('Failed to restore product', VS_TEXT_DOMAIN),
        'select_products_to_restore' => __('Please select products to restore', VS_TEXT_DOMAIN),
        'select_products_to_delete' => __('Please select products to delete', VS_TEXT_DOMAIN),
        'products_restored_count' => __('%s products have been restored.', VS_TEXT_DOMAIN),
        'restore_selected_products_count' => __('Do you want to restore %s selected products?', VS_TEXT_DOMAIN),
        'yes_restore_all' => __('Yes, Restore All', VS_TEXT_DOMAIN),
        'failed_to_restore_products' => __('Failed to restore products', VS_TEXT_DOMAIN),
        'failed_to_delete_products' => __('Failed to delete products', VS_TEXT_DOMAIN),
        'delete_selected_products' => __('Delete Selected Products?', VS_TEXT_DOMAIN),
        'yes_delete_permanently' => __('Yes, Delete Permanently', VS_TEXT_DOMAIN),
        'delete_selected_products_permanently_count' => __('Do you want to permanently delete %s selected products?', VS_TEXT_DOMAIN),
        'move_selected_products_to_trash_or_delete' => __('Do you want to move %s products to the trash or delete them permanently?', VS_TEXT_DOMAIN),
        'products_moved_to_trash_count' => __('%s products moved to trash.', VS_TEXT_DOMAIN),
        'products_deleted_permanently_count' => __('%s products permanently deleted.', VS_TEXT_DOMAIN),
        'no_products_table_found' => __('No products table found', VS_TEXT_DOMAIN),
        'no_products_found_to_export' => __('No products found to export', VS_TEXT_DOMAIN),
        'orders' => __('Orders', VS_TEXT_DOMAIN),
        'order_number' => __('Order #', VS_TEXT_DOMAIN),
        'customer' => __('Customer', VS_TEXT_DOMAIN),
        'email' => __('Email', VS_TEXT_DOMAIN),
        'date' => __('Date', VS_TEXT_DOMAIN),
        'status' => __('Status', VS_TEXT_DOMAIN),
        'vendor_total' => __('Vendor Total', VS_TEXT_DOMAIN),
        'order_deleted' => __('Order has been deleted.', VS_TEXT_DOMAIN),
        'failed_to_delete_order' => __('Failed to delete order', VS_TEXT_DOMAIN),
        'failed_to_update_status' => __('Failed to update status', VS_TEXT_DOMAIN),
        'status_updated_to' => __('Status updated to %s', VS_TEXT_DOMAIN),
        'no_messages_yet' => __('No messages yet. Start the conversation!', VS_TEXT_DOMAIN),
        'failed_to_send_message' => __('Failed to send message', VS_TEXT_DOMAIN),
        'connection_error' => __('Connection error', VS_TEXT_DOMAIN),
        'account_updated_successfully' => __('Account updated successfully', VS_TEXT_DOMAIN),
        'reset_email_sent' => __('Reset email sent', VS_TEXT_DOMAIN),
        'verification_email_sent' => __('Verification email sent', VS_TEXT_DOMAIN),
        'store_settings_updated' => __('Store settings updated', VS_TEXT_DOMAIN),
        'failed_to_save_store_settings' => __('Failed to save store settings', VS_TEXT_DOMAIN),
        'extra_settings_updated' => __('Extra settings updated', VS_TEXT_DOMAIN),
        'visibility_saved' => __('Visibility saved', VS_TEXT_DOMAIN),
        'notifications_updated' => __('Notifications updated', VS_TEXT_DOMAIN),
        'landing_page_created' => __('Landing page created', VS_TEXT_DOMAIN),
        'edit_landing_page' => __('Edit Landing Page', VS_TEXT_DOMAIN),
        'preview' => __('Preview', VS_TEXT_DOMAIN),
        'vendor_promotion_landing_page' => __('Vendor Promotion Landing Page', VS_TEXT_DOMAIN),
        'bulk_quick_edit' => __('Bulk Quick Edit', VS_TEXT_DOMAIN),
        'select_category_or_status' => __('Select at least Category or Status to apply.', VS_TEXT_DOMAIN),
        'selected_products_updated' => __('Selected products updated successfully.', VS_TEXT_DOMAIN),
        'partial_update' => __('Partial Update', VS_TEXT_DOMAIN),
        'partial_update_message' => __('%1$s updated, %2$s failed.', VS_TEXT_DOMAIN),
        'please_wait_selected_products_updated' => __('Please wait while the selected products are updated.', VS_TEXT_DOMAIN),
        'please_fill_all_fields' => __('Please fill all fields', VS_TEXT_DOMAIN),
        'done' => __('Done', VS_TEXT_DOMAIN),
        'language' => __('Language', VS_TEXT_DOMAIN),
        'change_language' => __('Change language', VS_TEXT_DOMAIN),
        'language_updated' => __('Language updated successfully.', VS_TEXT_DOMAIN),
        'invalid_language' => __('Invalid language.', VS_TEXT_DOMAIN),
        'select_products_to_edit' => __('Please select products to edit', VS_TEXT_DOMAIN),
    ];
}

function vs_enqueue_assets()
{
    wp_enqueue_style('dashicons');
    $css_ver = file_exists(VS_PATH . 'assets/dashboard.css') ? (string) filemtime(VS_PATH . 'assets/dashboard.css') : '1.0';
    $js_ver = file_exists(VS_PATH . 'assets/dashboard.js') ? (string) filemtime(VS_PATH . 'assets/dashboard.js') : '1.1';

    wp_enqueue_style(
        'vs-dashboard-css',
        plugin_dir_url(__FILE__) . 'assets/dashboard.css',
        [],
        $css_ver
    );

    // Mobile responsive CSS – loaded after dashboard.css so it takes priority
    $mobile_ver = file_exists(VS_PATH . 'assets/mobile.css') ? (string) filemtime(VS_PATH . 'assets/mobile.css') : '1.0';
    wp_enqueue_style(
        'vs-mobile-css',
        plugin_dir_url(__FILE__) . 'assets/mobile.css',
        ['vs-dashboard-css'],
        $mobile_ver
    );

    // SheetJS (xlsx) – used for clean Excel export
    wp_register_script(
        'vs-sheetjs',
        'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js',
        [],
        '0.18.5',
        true
    );
    wp_enqueue_script('vs-sheetjs');

    wp_register_script(
        'vs-dashboard-js',
        plugin_dir_url(__FILE__) . 'assets/dashboard.js',
        ['jquery', 'wp-i18n', 'vs-sheetjs'],
        $js_ver,
        true
    );
    // Ensure WP Media is available for media picker usage in dashboards/modals
    wp_enqueue_media();
    wp_enqueue_script('vs-dashboard-js');

    $tax = get_taxonomy('product_cat');
    $manage_terms_cap = ($tax && isset($tax->cap) && isset($tax->cap->manage_terms))
        ? $tax->cap->manage_terms
        : 'manage_product_terms';
    $default_product_cat = absint(get_option('default_product_cat'));
    $uncategorized_term = term_exists('uncategorized', 'product_cat');
    $uncategorized_term_id = 0;
    if (is_array($uncategorized_term) && !empty($uncategorized_term['term_id'])) {
        $uncategorized_term_id = (int) $uncategorized_term['term_id'];
    } elseif (is_int($uncategorized_term)) {
        $uncategorized_term_id = $uncategorized_term;
    }
    $is_vendor_user = is_user_logged_in() && (
        in_array('vendor', (array) wp_get_current_user()->roles, true)
        || current_user_can('edit_products')
    );

    wp_localize_script('vs-dashboard-js', 'vs_vars', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('vs_nonce'),
        'orders_nonce' => wp_create_nonce('vs_orders_nonce'),
        'chat_nonce' => wp_create_nonce('vs_chat_nonce'),
        'setup_nonce' => wp_create_nonce('vs_setup_nonce'),
        'i18n' => vs_get_dashboard_i18n_strings(),
        'current_locale' => determine_locale(),
        'enabled_locales' => vs_get_enabled_locales(),
        'moderation_mode' => get_option('vs_moderation_mode', 'manual'),
        'current_user_name' => (is_user_logged_in() ? wp_get_current_user()->display_name : ''),
        'current_user_email' => (is_user_logged_in() ? wp_get_current_user()->user_email : ''),
        'is_admin' => current_user_can('administrator'),
        // IMPORTANT: this flag is for taxonomy term management only (admins/managers).
        // Vendors (who often have edit_products) should not be treated as term managers;
        // they must create "category requests" instead.
        'can_manage_terms' => (current_user_can('administrator') || current_user_can($manage_terms_cap)),
        'is_vendor' => $is_vendor_user,
        'default_product_cat' => $default_product_cat,
        'uncategorized_term_id' => $uncategorized_term_id,
        'require_product_approval' => (bool) (((array) get_option('vs_settings', []))['products']['require_product_approval'] ?? false),
    ]);
    wp_set_script_translations('vs-dashboard-js', VS_TEXT_DOMAIN, VS_PATH . 'languages');
}
add_action('wp_enqueue_scripts', 'vs_enqueue_assets');

function enqueue_font_awesome()
{
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css', [], '6.4.2');
}
add_action('wp_enqueue_scripts', 'enqueue_font_awesome');

/**
 * Ensure the viewport meta tag is always present so mobile CSS works correctly.
 */
add_action('wp_head', function () {
    echo '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">' . "\n";
}, 1);

register_activation_hook(__FILE__, ['VS_Setup', 'activate_plugin']);
register_deactivation_hook(__FILE__, function () {
    if (!class_exists('VS_Ads')) {
        return;
    }
    $timestamp = wp_next_scheduled(VS_Ads::CRON_HOOK);
    while ($timestamp) {
        wp_unschedule_event($timestamp, VS_Ads::CRON_HOOK);
        $timestamp = wp_next_scheduled(VS_Ads::CRON_HOOK);
    }
});


add_action('wp_ajax_vs_become_vendor', 'vs_become_vendor_handler');

function vs_become_vendor_handler()
{

    // Ø§Ù…Ù†Ø¹ Ø£ÙŠ output Ø³Ø§Ø¨Ù‚
    if (ob_get_length()) {
        ob_clean();
    }

    check_ajax_referer('vs_nonce', 'security');

    if (!is_user_logged_in()) {
        wp_send_json_error(__('You must be logged in.', VS_TEXT_DOMAIN));
        wp_die();
    }

    $user_id = get_current_user_id();

    $store_name = sanitize_text_field($_POST['store_name'] ?? '');
    $store_location = sanitize_text_field($_POST['store_location'] ?? '');
    $store_phone = sanitize_text_field($_POST['store_phone'] ?? '');
    $store_desc = sanitize_textarea_field($_POST['store_desc'] ?? '');

    if (!$store_name || !$store_location) {
        wp_send_json_error(__('Store name and location required.', VS_TEXT_DOMAIN));
        wp_die();
    }

    update_user_meta($user_id, 'vs_store_name', $store_name);
    update_user_meta($user_id, 'vs_store_location', $store_location);
    update_user_meta($user_id, 'vs_store_phone', $store_phone);
    update_user_meta($user_id, 'vs_store_desc', $store_desc);

    // 1) Social Links
    $social_links = [
        'facebook' => esc_url_raw($_POST['social_facebook'] ?? ''),
        'instagram' => esc_url_raw($_POST['social_instagram'] ?? ''),
        'x' => esc_url_raw($_POST['social_x'] ?? ''),
        'linkedin' => esc_url_raw($_POST['social_linkedin'] ?? ''),
        'youtube' => esc_url_raw($_POST['social_youtube'] ?? ''),
    ];
    update_user_meta($user_id, 'vs_store_social_links', $social_links);

    // 2) Branding - Logo & Banner
    if (!empty($_FILES['store_logo']['name']) || !empty($_FILES['store_banner']['name'])) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

        if (!empty($_FILES['store_logo']['name'])) {
            $logo_id = media_handle_upload('store_logo', 0);
            if (!is_wp_error($logo_id)) {
                update_user_meta($user_id, 'vs_store_logo_id', (int) $logo_id);
            }
        }

        if (!empty($_FILES['store_banner']['name'])) {
            $banner_id = media_handle_upload('store_banner', 0);
            if (!is_wp_error($banner_id)) {
                update_user_meta($user_id, 'vs_store_banner_id', (int) $banner_id);
            }
        }
    }

    update_user_meta($user_id, 'vs_vendor_onboarded', 1);

    $approval_required = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval', 'yes') === 'yes';

    if ($approval_required) {
        // Step 1: Set Pending Status
        update_user_meta($user_id, 'vs_vendor_status', 'pending');

        

        wp_send_json_success([
            'message' => __('Your application has been submitted successfully and is pending administrator review.', 'vendor-space'),
            'status' => 'pending',
            'redirect' => site_url('/vendor-dashboard')
        ]);
    } else {
        // Step 2: Auto Approve
        $user = new WP_User($user_id);
        $user->set_role('vendor');
        update_user_meta($user_id, 'vs_vendor_status', 'active');

        // Notify Vendor
        $subject = sprintf(__('[%s] Welcome to our Marketplace!', 'vendor-space'), get_bloginfo('name'));
        $message = sprintf(
            __("Congratulations %s!\n\nYour store '%s' is now active. You can start adding products and selling right away.\n\nDashboard: %s", 'vendor-space'),
            $user->display_name,
            $store_name,
            site_url('/vendor-dashboard')
        );
        wp_mail($user->user_email, $subject, $message);

        wp_send_json_success([
            'message' => __('Congratulations! Your vendor account is now active.', 'vendor-space'),
            'status' => 'active',
            'redirect' => site_url('/vendor-dashboard')
        ]);
    }

    wp_die();
}

// Override WooCommerce new account email template + subject
add_filter('woocommerce_locate_template', function ($template, $template_name, $template_path) {
    if ($template_name === 'emails/customer-new-account.php') {
        $custom = VS_PATH . 'templates/emails/customer-new-account.php';
        if (file_exists($custom)) {
            return $custom;
        }
    }
    return $template;
}, 10, 3);

add_filter('woocommerce_email_subject_customer_new_account', function ($subject) {
    return __('Welcome to Our Marketplace', VS_TEXT_DOMAIN);
});

add_filter('woocommerce_email_heading_customer_new_account', function ($heading) {
    return __('Welcome to Our Marketplace', VS_TEXT_DOMAIN);
});



add_action('pre_get_posts', 'force_show_all_products_for_shop');
function force_show_all_products_for_shop($query)
{
    // للـ frontend
    if (
        !is_admin() && $query->is_main_query() &&
        ($query->get('post_type') === 'product' || is_shop() || is_product_category() || is_product_tag() || (is_search() && $query->get('post_type') === 'product'))
    ) {
        $query->set('post_status', 'publish');
        $query->set('post_type', 'product');
        $query->set('author', '');
        $blocked_vendors = get_users([
            'meta_key' => 'vs_vendor_status',
            'meta_value' => 'deleted',
            'fields' => 'ID'
        ]);
        if (!empty($blocked_vendors)) {
            $query->set('author__not_in', $blocked_vendors);
        }
    }

    if (is_admin() && $query->get('post_type') === 'product') {
        $blocked_vendors = get_users([
            'meta_key' => 'vs_vendor_status',
            'meta_value' => 'deleted',
            'fields' => 'ID'
        ]);
        if (!empty($blocked_vendors)) {
            $query->set('author__not_in', $blocked_vendors);
        }
    }
}


add_filter('woocommerce_product_query', 'exclude_blocked_vendors_products', 10, 2);
function exclude_blocked_vendors_products($query, $wc_query)
{
    $blocked_vendors = get_users([
        'meta_key' => 'vs_vendor_status',
        'meta_value' => 'deleted',
        'fields' => 'ID'
    ]);
    if (!empty($blocked_vendors)) {
        $query->set('author__not_in', $blocked_vendors);
    }
    return $query;
}

add_filter('manage_product_posts_columns', 'add_vendor_status_column');
function add_vendor_status_column($columns)
{
    $columns['vendor_or_price'] = __('Vendor / Price', 'vendor-space');
    $columns['vendor_status'] = __('Vendor Status', 'vendor-space');
    return $columns;
}

add_action('manage_product_posts_custom_column', 'show_vendor_status_column', 10, 2);
function show_vendor_status_column($column, $post_id)
{
    if ($column === 'vendor_status') {
        $vendor_id = get_post_field('post_author', $post_id);
        $vendor_status = get_user_meta($vendor_id, 'vs_vendor_status', true);

        if ($vendor_status === 'deleted') {
            echo '<span style="background: #dc2626; color: #fff; padding: 2px 6px; border-radius: 3px; font-size: 12px;">' . esc_html__('Blocked Vendor', 'vendor-space') . '</span>';
        } elseif ($vendor_status === 'active' || empty($vendor_status)) {
            echo '<span style="background: #22c55e; color: #fff; padding: 2px 6px; border-radius: 3px; font-size: 12px;">' . esc_html__('Active Vendor', 'vendor-space') . '</span>';
        } else {
            echo '<span style="background: #f59e0b; color: #fff; padding: 2px 6px; border-radius: 3px; font-size: 12px;">' . esc_html__('Inactive', 'vendor-space') . '</span>';
        }
    }

    if ($column === 'vendor_or_price') {
        $vendor_id = get_post_field('post_author', $post_id);

        if (current_user_can('manage_options')) {
            $vendor = get_userdata($vendor_id);
            echo $vendor ? esc_html($vendor->display_name) : esc_html__('—', 'vendor-space');
            return;
        }

        // For non-admin users show product price (vendors and customers)
        if (function_exists('wc_get_product')) {
            $product = wc_get_product($post_id);
            if ($product) {
                echo wp_kses_post($product->get_price_html());
                return;
            }
        }

        echo esc_html__('—', 'vendor-space');
    }
}

/**
 * Filter products by vendor in Admin List
 */
add_action('restrict_manage_posts', 'vs_admin_products_vendor_filter');
function vs_admin_products_vendor_filter($post_type)
{
    if ($post_type !== 'product' || !current_user_can('manage_options')) {
        return;
    }

    $selected_vendor = isset($_GET['vs_vendor_filter']) ? intval($_GET['vs_vendor_filter']) : 0;

    $args = array(
        'show_option_all' => __('Filter by Vendor', 'vendor-space'),
        'name' => 'vs_vendor_filter',
        'selected' => $selected_vendor,
        'role__in' => array('vendor', 'administrator'),
        'show' => 'display_name',
        'value_field' => 'ID',
    );
    wp_dropdown_users($args);
}

add_filter('request', 'vs_admin_products_vendor_filter_query');
function vs_admin_products_vendor_filter_query($vars)
{
    global $pagenow, $typenow;

    if (is_admin() && $pagenow === 'edit.php' && $typenow === 'product' && !empty($_GET['vs_vendor_filter'])) {
        $vars['author'] = intval($_GET['vs_vendor_filter']);
    }

    return $vars;
}

// Initialise le plugin
add_action('init', function () {
    vs_load_textdomain();

    VS_Setup::init();
    VS_Dashboard::init();
    VS_Profile::init();
    VS_Stores::init();
    VS_Core::init(); // This registers register_custom_statuses()
    VS_Categories::init();
    VS_Orders::init();
    VS_Ajax_Pagination::init();
    VS_Settings::init();
    VS_Commission::init();
    VS_Vendors::init();
    VS_Admin_Settings::init();
    VS_Admin_Moderation::init();
    VS_Modules::init();
    // Auto-create new tables if missing (safe to run multiple times via dbDelta)
    VS_Setup::create_user_modules_table();
}, 1);



add_action('template_redirect', 'vs_check_vendor_status_global');

function vs_check_vendor_status_global()
{

    if (!is_user_logged_in()) {
        return;
    }

    $user = wp_get_current_user();

    $status = get_user_meta($user->ID, 'vs_vendor_status', true);
    if (!$status) {
        return; 
    }
    if ($status !== 'active') {

        wp_logout();

        wc_add_notice(__('Sorry, your account has been blocked. You cannot log in.', VS_TEXT_DOMAIN), 'error');

        wp_safe_redirect(wc_get_page_permalink('myaccount'));
        exit;
    }
}
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

add_action('phpmailer_init', function ($phpmailer) {

    $phpmailer->isSMTP();
    $phpmailer->Host = 'smtp.gmail.com';
    $phpmailer->SMTPAuth = true;
    $phpmailer->Username = 'mekkaouifouad32@gmail.com';
    $phpmailer->Password = 'tvzx ecgm ympw ppwo';
    $phpmailer->SMTPSecure = 'tls';
    $phpmailer->Port = 587;

    $phpmailer->SMTPOptions = [
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ];

    $phpmailer->setFrom('mekkaouifouad32@gmail.com', __('Vendor Space', VS_TEXT_DOMAIN));
});

add_filter('wp_mail_from', function ($email) {
    return 'mekkaouifouad32@gmail.com';
});

add_filter('wp_mail_from_name', function ($name) {
    return __('Vendor Space', 'vendor-space');
});

/**
 * Initialize and ensure all chat tables exist
 * Called on plugins_loaded to check and create tables if needed
 */
function vs_ensure_chat_tables_exist()
{
    global $wpdb;

    // Table name for chat messages
    $table_name = $wpdb->prefix . 'chat_vendor_customer';
    $charset_collate = $wpdb->get_charset_collate();

    // Check if table exists
    $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));

    if (!$table_exists) {
        // Table doesn't exist, create it
        $sql = "CREATE TABLE {$table_name} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            sender_id BIGINT UNSIGNED NOT NULL,
            receiver_id BIGINT UNSIGNED NOT NULL,
            message TEXT NOT NULL,
            is_read TINYINT(1) NOT NULL DEFAULT 0,
            created_at DATETIME NOT NULL,
            PRIMARY KEY (id),
            KEY sender_id (sender_id),
            KEY receiver_id (receiver_id),
            KEY is_read (is_read)
        ) {$charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    } else {
        // Table exists, check if it has all required columns
        $has_sender_id = $wpdb->get_var("SHOW COLUMNS FROM {$table_name} LIKE 'sender_id'");
        $has_receiver_id = $wpdb->get_var("SHOW COLUMNS FROM {$table_name} LIKE 'receiver_id'");
        $has_is_read = $wpdb->get_var("SHOW COLUMNS FROM {$table_name} LIKE 'is_read'");

        // Add missing columns if needed
        if (!$has_is_read) {
            $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN is_read TINYINT(1) NOT NULL DEFAULT 0 AFTER message");
            $wpdb->query("ALTER TABLE {$table_name} ADD KEY is_read (is_read)");
        }
    }
}

// Hook into plugins_loaded to ensure tables exist when plugin is loaded
add_action('plugins_loaded', 'vs_ensure_chat_tables_exist', 15);




// Ø¥Ø¶Ø§ÙØ© Ø²Ø± Share ØªØ­Øª Ø²Ø± Add to Cart
add_action('woocommerce_single_product_summary', 'vs_add_share_button', 35);
function vs_add_share_button()
{
    global $product;
    $product_url = get_permalink($product->get_id());
    ?>
    <button id="vs-share-button" data-url="<?php echo esc_url($product_url); ?>" style="
            background: #16a34a;      
            color: white;            
            padding: 10px 16px;     
            border: none;             
            border-radius: 6px;      
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.15);
            transition: background 0.3s, box-shadow 0.3s;
        " onmouseover="this.style.background='#15803d'; this.style.boxShadow='0 4px 6px rgba(0,0,0,0.2)'"
        onmouseout="this.style.background='#16a34a'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.15)'">
        <span style="font-size:16px;"><i class="fa fa-share-square"></i></span>
        <span><?php echo esc_html__('Share', VS_TEXT_DOMAIN); ?></span>
    </button>

    <span id="vs-share-msg"
        style="margin-left:10px;color:green;display:none;"><?php echo esc_html__('Copied!', VS_TEXT_DOMAIN); ?></span>
    <?php
}

add_action('wp_footer', 'vs_share_script');
function vs_share_script()
{
    if (!is_product())
        return;
    ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const shareBtn = document.getElementById('vs-share-button');
            const msg = document.getElementById('vs-share-msg');
            if (!shareBtn) return;

            shareBtn.addEventListener('click', function () {
                const url = this.dataset.url;

                if (navigator.share) {
                    navigator.share({
                        title: document.title,
                        url: url
                    }).then(() => {
                        console.log('<?php echo esc_js(__('Shared successfully', VS_TEXT_DOMAIN)); ?>');
                    }).catch(err => {
                        console.log('<?php echo esc_js(__('Share failed', VS_TEXT_DOMAIN)); ?>', err);
                    });
                } else {
                    navigator.clipboard.writeText(url).then(() => {
                        msg.style.display = 'inline';
                        setTimeout(() => msg.style.display = 'none', 2000);
                    }).catch(err => {
                        alert('<?php echo esc_js(__('Could not copy link:', VS_TEXT_DOMAIN)); ?>' + ' ' + err);
                    });
                }
            });
        });
    </script>
    <?php
}

