<?php
/*
 * Plugin Name: AuctionForge
 * Description: Auction Integration for BidSpirit by SmoothByte IT
 * Version: 2.5.1.0
 * Requires at least: 5.2
 * Requires PHP: 7.2
 * Author: SmoothByte IT
 * Author URI: https://smoothbyteit.dev
 * Text Domain: auctionforge
 **/

use auctionforge\inc\abs\Importer;
use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\CurlRequest;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\Conditions;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\import\AuctionList;
use auctionforge\inc\import\InsertLotsBS;
use auctionforge\inc\import\LotList;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\FirebaseLog;
use auctionforge\inc\model\FirebaseUser;
use auctionforge\inc\model\LotMetaData;
use auctionforge\inc\model\SubmissionFormData;
// use YahnisElsts\PluginUpdateChecker\v5\PucFactory; // Disabled - update checker removed

if (!defined('ABSPATH')) {
    die('You shouldnt be here');
}

function auctionforge_plugin_info() {
    return get_file_data(__FILE__, ['ver' => 'Version']);
}

function auctionforge_plugin_file_info($relPath) {
    if (file_exists($relPath)) {
        return get_file_data($relPath, ['ver' => 'Version']);
    } else {
        return null;
    }
}

$data = auctionforge_plugin_info();

define('AUCTIONFORGE_VERSION', $data['ver']);
define('AUCTIONFORGE_DB_VERSION', 18);
define('AUCTIONFORGE_DB_OPTION_NAME', 'auctionforge_db_version');
define('AUCTIONFORGE_DB_UPDATE_VERSION', 6);
define('AUCTIONFORGE_DB_UPDATE_OPTION_NAME', 'auctionforge_db_update_version');
define('AUCTIONFORGE_CONFIG_OPTION_NAME', 'auctionforge_config_version');
define('AUCTIONFORGE_CONFIG_VERSION', 4);

define('AUCTIONFORGE_SYNC_START', '_auctionforge_sync_start');
define('AUCTIONFORGE_SYNC_ARCHIVE_START', '_auctionforge_sync_archive_start');
define('AUCTIONFORGE_SYNC_DATA_START', '_auctionforge_sync_data_start');
define('BASE_PATH', __DIR__);
define('AUCTIONFORGE_PLUGIN_SLUG', basename(__DIR__));

/** Sentry error reporting - DISABLED */

/**
 * Limit for the InsertLots task
 */
if (!defined('RAW_LOT_LIMIT')) {
    define('RAW_LOT_LIMIT', 10);
}
if (!defined('TRY_LOT_LIMIT')) {
    define('TRY_LOT_LIMIT', 3);
}
if (!defined('RECORDS_EXPIRE')) {
    define('RECORDS_EXPIRE', 3);
}
if (!defined('BP_HOURLY')) {
    define('BP_HOURLY', 3600);
}
if (!defined('BP_MINUTELY')) {
    define('BP_MINUTELY', 60);
}
if (!defined('BP_24_HOURLY')) {
    define('BP_24_HOURLY', 86400 * 5);
}

function getDirAuctionForgePlugins() {
    return plugin_dir_path( __FILE__ );
}

require_once plugin_dir_path( __FILE__ ) . 'inc/coreIncludes.php';
require_once plugin_dir_path( __FILE__ ) . 'inc/ip-logger.php';

// AuctionForge Site Statistics
require_once plugin_dir_path( __FILE__ ) . 'inc/stats/class-stats-init.php';
AF_Stats_Init::init();

register_activation_hook(__FILE__, 'activatePlugin');
register_deactivation_hook(__FILE__, 'deactivatePlugin');
register_uninstall_hook(__FILE__, 'uninstallPlugin');

function activatePlugin() {
    createTableImportHistoryTable();
    createBpFirebaseTables();
    createBpLotDataTable();
    createBpSubmissonDataTable();
    createBpMetaTableIndexes();
    createBpViewHistoryTable();
    AF_Stats_Init::activate();
    auctionforge_create_ip_log_table();

    delete_option('rewrite_rules');
    update_option('rewrite_rules', '');
}

function auctionforge_upgrade_action($upgraderObject, $hookExtra) {
    delete_option('rewrite_rules');
    update_option('rewrite_rules', '');
    auctionforge_create_ip_log_table();
}
add_action('upgrader_process_complete', 'auctionforge_upgrade_action', 10, 2);

/**
 * AuctionForge Auto Updater - managed by WP Plugin Deployer
 */
require_once plugin_dir_path(__FILE__) . 'inc/class-auto-updater.php';

define('AUCTIONFORGE_PLUGIN_BASENAME', plugin_basename(__FILE__));

$auctionforge_updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);

// AJAX handlers and admin menu for update settings and sync status (admin only)
if (is_admin()) {
    add_action('admin_menu', 'auctionforge_register_updates_page');
    add_action('admin_menu', 'auctionforge_register_sync_status_page');
    add_action('admin_menu', 'auctionforge_register_ip_log_page');
    add_action('wp_ajax_auctionforge_search_ip_logs', 'auctionforge_ajax_search_ip_logs');
    add_action('wp_ajax_auctionforge_export_ip_logs', 'auctionforge_ajax_export_ip_logs');
    add_action('wp_ajax_auctionforge_lookup_linked', 'auctionforge_ajax_lookup_linked');
    add_action('wp_ajax_auctionforge_test_update_connection', 'auctionforge_ajax_test_update_connection');
    add_action('wp_ajax_auctionforge_check_updates_now', 'auctionforge_ajax_check_updates_now');
    add_action('wp_ajax_auctionforge_report_health_now', 'auctionforge_ajax_report_health_now');
    add_action('wp_ajax_auctionforge_save_update_settings', 'auctionforge_ajax_save_update_settings');
    add_action('wp_ajax_auctionforge_register_site', 'auctionforge_ajax_register_site');
    add_action('wp_ajax_auctionforge_request_access', 'auctionforge_ajax_request_access');
    add_action('wp_ajax_auctionforge_clear_registration', 'auctionforge_ajax_clear_registration');
    add_action('wp_ajax_auctionforge_run_cron_task', 'auctionforge_ajax_run_cron_task');
    add_action('wp_ajax_auctionforge_run_wpcron_task', 'auctionforge_ajax_run_wpcron_task');
    add_action('wp_ajax_auctionforge_sync_tracking_now', 'auctionforge_ajax_sync_tracking_now');
    add_action('wp_ajax_auctionforge_sync_enforcement_now', 'auctionforge_ajax_sync_enforcement_now');
}

// IP logging AJAX - available to both logged-in and non-logged-in users
add_action('wp_ajax_auctionforge_log_ip', 'auctionforge_ajax_log_ip');
add_action('wp_ajax_nopriv_auctionforge_log_ip', 'auctionforge_ajax_log_ip');

// Fraud check AJAX - available to both logged-in and non-logged-in users
add_action('wp_ajax_auctionforge_check_fraud', 'auctionforge_ajax_check_fraud');
add_action('wp_ajax_nopriv_auctionforge_check_fraud', 'auctionforge_ajax_check_fraud');

function auctionforge_register_updates_page() {
    add_submenu_page(
        'edit.php?post_type=lot',
        __('AuctionForge Updates', 'auctionforge'),
        __('Updates', 'auctionforge'),
        'manage_options',
        'auctionforge-updates',
        'auctionforge_render_updates_page'
    );
}

function auctionforge_render_updates_page() {
    require_once plugin_dir_path(__FILE__) . 'admin/view/updates.php';
}

function auctionforge_register_sync_status_page() {
    add_submenu_page(
        'edit.php?post_type=lot',
        __('Sync Status', 'auctionforge'),
        __('Sync Status', 'auctionforge'),
        'manage_options',
        'auctionforge-sync-status',
        'auctionforge_render_sync_status_page'
    );
}

function auctionforge_render_sync_status_page() {
    require_once plugin_dir_path(__FILE__) . 'admin/view/sync-status.php';
}

function auctionforge_ajax_run_cron_task() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }

    $allowed_tasks = array('importBidSpirit', 'importData', 'lotBidSpiritOld', 'cleaner', 'cleanerTrashMeta');
    $task = isset($_POST['task']) ? sanitize_text_field($_POST['task']) : '';

    if (!in_array($task, $allowed_tasks)) {
        wp_send_json_error('Invalid task: ' . $task);
        return;
    }

    // Run task directly via PHP classes (exec/shell_exec disabled in PHP-FPM)
    $result = array('success' => true, 'details' => '');

    try {
        switch ($task) {
            case 'importBidSpirit':
                $auctionList = new \auctionforge\inc\import\AuctionList();
                $auctionList->init();
                $lotList = new \auctionforge\inc\import\LotList();
                $lotList->setPriority(4);
                $lotList->init();
                $result['details'] = 'Auction list + lot list synced (upcoming)';
                break;

            case 'importData':
                $insertLots = new \auctionforge\inc\import\InsertLotsBS();
                $insertLots->init();
                $result['details'] = 'Import queue processed';
                break;

            case 'lotBidSpiritOld':
                $auctionList = new \auctionforge\inc\import\AuctionList();
                $auctionList->init();
                $lotList = new \auctionforge\inc\import\LotList();
                $lotList->setPriority(5);
                $lotList->init(false);
                $result['details'] = 'Auction list + lot list synced (archived)';
                break;

            case 'cleaner':
                $deleted = 0;
                $lots = get_posts(array(
                    'post_type' => 'lot',
                    'numberposts' => 100,
                    'post_status' => array('draft', 'trash'),
                    'lang' => '',
                ));
                foreach ($lots as $lot) {
                    wp_delete_post($lot->ID, true);
                    $deleted++;
                }
                $result['details'] = sprintf('%d draft/trash lots deleted', $deleted);
                break;

            case 'cleanerTrashMeta':
                \auctionforge\inc\helpers\CleanerTrashMetaFields::run();
                $result['details'] = 'Orphaned meta fields cleaned';
                break;
        }
    } catch (\Exception $e) {
        wp_send_json_error('Task failed: ' . $e->getMessage());
        return;
    } catch (\Error $e) {
        wp_send_json_error('Task error: ' . $e->getMessage());
        return;
    }

    wp_send_json_success(array(
        'message' => sprintf('Task "%s" completed. %s', $task, $result['details']),
    ));
}

function auctionforge_ajax_run_wpcron_task() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }

    $hook = isset($_POST['hook']) ? sanitize_text_field($_POST['hook']) : '';
    $allowed_hooks = array('bidspirit_import', 'data_import', 'bidspirit_archive_import');

    if (!in_array($hook, $allowed_hooks)) {
        wp_send_json_error('Invalid hook: ' . $hook);
        return;
    }

    $server = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';

    // Fire the action directly
    do_action($hook, $server);

    wp_send_json_success(array(
        'message' => sprintf('WP-Cron hook "%s" executed successfully', $hook)
    ));
}

function auctionforge_ajax_test_update_connection() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $server_url = isset($_POST['server_url']) ? esc_url_raw($_POST['server_url']) : '';
    $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
    
    if (empty($server_url) || empty($api_key)) {
        wp_send_json_error('Server URL and API Key are required');
        return;
    }
    
    $url = rtrim($server_url, '/') . '/api.php/info';
    $response = wp_remote_get($url, array(
        'headers' => array('X-API-Key' => $api_key),
        'timeout' => 15
    ));
    
    if (is_wp_error($response)) {
        wp_send_json_error('Connection failed: ' . $response->get_error_message());
        return;
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if (isset($body['app_version'])) {
        wp_send_json_success(array('message' => 'Connection successful!', 'version' => $body['app_version']));
    } else {
        wp_send_json_error('Invalid response from server');
    }
}

function auctionforge_ajax_check_updates_now() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    delete_site_transient('update_plugins');
    wp_update_plugins();
    
    $updates = get_site_transient('update_plugins');
    $has_update = isset($updates->response[AUCTIONFORGE_PLUGIN_BASENAME]);
    
    if ($has_update) {
        $update_data = $updates->response[AUCTIONFORGE_PLUGIN_BASENAME];
        wp_send_json_success(array(
            'has_update' => true,
            'new_version' => $update_data->new_version,
            'message' => 'Update available: version ' . $update_data->new_version
        ));
    } else {
        wp_send_json_success(array('has_update' => false, 'message' => 'Plugin is up to date'));
    }
}

function auctionforge_ajax_report_health_now() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);
    $updater->report_health();
    
    wp_send_json_success(array(
        'message' => 'Health report sent successfully',
        'wp_version' => get_bloginfo('version'),
        'php_version' => PHP_VERSION,
        'plugin_version' => AUCTIONFORGE_VERSION
    ));
}

function auctionforge_ajax_sync_enforcement_now() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);
    $updater->sync_fraud_enforcement();
    
    $enforcement = get_option('auctionforge_fraud_enforcement', false);
    $synced_at = get_option('auctionforge_fraud_enforcement_synced_at', '');
    
    wp_send_json_success(array(
        'message' => 'Enforcement synced: ' . ($enforcement ? 'ENFORCING' : 'DRY RUN'),
        'enforcement' => $enforcement,
        'synced_at' => $synced_at
    ));
}

function auctionforge_ajax_save_update_settings() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $server_url = isset($_POST['server_url']) ? esc_url_raw($_POST['server_url']) : '';
    $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
    $auto_update = isset($_POST['auto_update']) ? (bool) $_POST['auto_update'] : false;
    $fraud_enforcement = isset($_POST['fraud_enforcement']) ? (bool) $_POST['fraud_enforcement'] : null;
    
    update_option('auctionforge_update_server_url', $server_url);
    update_option('auctionforge_update_api_key', $api_key);
    update_option('auctionforge_auto_update', $auto_update);
    
    if ($fraud_enforcement !== null) {
        update_option('auctionforge_fraud_enforcement', $fraud_enforcement);
    }
    
    wp_send_json_success(array('message' => 'Settings saved successfully!'));
}

function auctionforge_ajax_register_site() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $server_url = isset($_POST['server_url']) ? esc_url_raw($_POST['server_url']) : '';
    $master_key = isset($_POST['master_key']) ? sanitize_text_field($_POST['master_key']) : '';
    
    if (empty($server_url) || empty($master_key)) {
        wp_send_json_error('Server URL and Master Key are required');
        return;
    }
    
    update_option('auctionforge_update_server_url', $server_url);
    
    $updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);
    $result = $updater->register_site($master_key);
    
    if ($result['success']) {
        wp_send_json_success($result);
    } else {
        wp_send_json_error($result['message']);
    }
}

function auctionforge_ajax_request_access() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $server_url = isset($_POST['server_url']) ? esc_url_raw($_POST['server_url']) : '';
    
    if (empty($server_url)) {
        wp_send_json_error('Deployment Server URL is required');
        return;
    }
    
    update_option('auctionforge_update_server_url', $server_url);
    
    $updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);
    $result = $updater->request_access();
    
    if ($result['success']) {
        wp_send_json_success($result);
    } else {
        wp_send_json_error($result['message']);
    }
}

function auctionforge_ajax_clear_registration() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    delete_option('auctionforge_update_api_key');
    wp_send_json_success(array('message' => 'Registration cleared successfully'));
}

function auctionforge_ajax_check_fraud() {
    check_ajax_referer('auctionforge_fraud_check', 'nonce');
    
    $email = sanitize_email(isset($_POST['email']) ? $_POST['email'] : '');
    if (empty($email)) {
        wp_send_json_error('No email provided');
        return;
    }
    
    $deviceId = sanitize_text_field(isset($_POST['device_id']) ? $_POST['device_id'] : '');
    $fingerprint = sanitize_text_field(isset($_POST['device_fingerprint']) ? $_POST['device_fingerprint'] : '');
    $ipAddress = auctionforge_get_client_ip();
    
    $enforcement = get_option('auctionforge_fraud_enforcement', false);
    
    // Cache key includes device info so different devices get separate checks
    $cacheKey = 'af_fraud_' . md5($email . $deviceId . $fingerprint . $ipAddress);
    $cached = get_transient($cacheKey);
    
    if ($cached !== false) {
        $cached['enforcement'] = (bool) $enforcement;
        wp_send_json_success($cached);
        return;
    }
    
    // Query central server
    $serverUrl = get_option('auctionforge_update_server_url', '');
    $apiKey = get_option('auctionforge_update_api_key', '');
    
    if (empty($serverUrl) || empty($apiKey)) {
        wp_send_json_success(array(
            'is_flagged' => false,
            'risk_level' => 'none',
            'enforcement' => (bool) $enforcement,
            'source' => 'not_configured',
        ));
        return;
    }
    
    $queryParams = array('email' => $email);
    if ($deviceId) $queryParams['device_id'] = $deviceId;
    if ($fingerprint) $queryParams['device_fingerprint'] = $fingerprint;
    if ($ipAddress) $queryParams['ip_address'] = $ipAddress;
    
    $url = rtrim($serverUrl, '/') . '/api.php/check-fraud?' . http_build_query($queryParams);
    $response = wp_remote_get($url, array(
        'timeout' => 10,
        'headers' => array('X-API-Key' => $apiKey),
    ));
    
    if (is_wp_error($response)) {
        wp_send_json_success(array(
            'is_flagged' => false,
            'risk_level' => 'none',
            'enforcement' => (bool) $enforcement,
            'source' => 'api_error',
        ));
        return;
    }
    
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    $result = array(
        'is_flagged' => !empty($body['is_flagged']),
        'risk_level' => $body['risk_level'] ?? 'none',
        'reason' => isset($body['fraud_record']['reason']) ? $body['fraud_record']['reason'] : '',
        'match_type' => $body['match_type'] ?? 'email',
        'linked_to' => $body['linked_to'] ?? null,
        'enforcement' => (bool) $enforcement,
        'source' => 'central_server',
    );
    
    // Cache for 10 minutes
    set_transient($cacheKey, $result, 600);
    
    wp_send_json_success($result);
}

function auctionforge_ajax_sync_tracking_now() {
    check_ajax_referer('auctionforge_admin', 'nonce');
    if (!current_user_can('manage_options')) { wp_send_json_error('Unauthorized'); return; }
    
    $updater = new AuctionForge_Auto_Updater(AUCTIONFORGE_PLUGIN_BASENAME, AUCTIONFORGE_VERSION);
    $result = $updater->sync_user_tracking();
    
    if ($result) {
        $count = get_option('auctionforge_last_tracking_sync_count', 0);
        $alerts = get_option('auctionforge_last_tracking_sync_alerts', 0);
        wp_send_json_success(array(
            'message' => "Tracking sync completed. {$count} records synced, {$alerts} alerts generated.",
            'synced' => $count,
            'alerts' => $alerts,
        ));
    } else {
        $status = get_option('auctionforge_last_tracking_sync_status', 'unknown');
        wp_send_json_error("Sync failed: {$status}");
    }
}

function auctionforge_db_update() {
    add_option(AUCTIONFORGE_DB_OPTION_NAME, 1);
    $dbVersion = get_option(AUCTIONFORGE_DB_OPTION_NAME);

    if ((int)$dbVersion < AUCTIONFORGE_DB_VERSION && dropImportHistoryTable()) {
        createTableImportHistoryTable();
        createBpFirebaseTables();
        createBpLotDataTable();
        createBpSubmissonDataTable();
        createBpMetaTableIndexes();
        createBpViewHistoryTable();
        AF_Stats_Init::activate();

        update_option(AUCTIONFORGE_DB_OPTION_NAME, AUCTIONFORGE_DB_VERSION, 'no');
    }
}
add_action('plugins_loaded', 'auctionforge_db_update');

function auctionforge_db_fixes_update() {
    $dbVersion = get_option(AUCTIONFORGE_DB_UPDATE_OPTION_NAME, 0);

    if ((int)$dbVersion < AUCTIONFORGE_DB_UPDATE_VERSION) {
        updateImagesListStrField();
        addCriminalContentFieldInMeta();
        addCriminalContentFieldInHistory();
        addImportHistoryIndexes();

        update_option(AUCTIONFORGE_DB_UPDATE_OPTION_NAME, AUCTIONFORGE_DB_UPDATE_VERSION, 'no');
    }
}
add_action('init', 'auctionforge_db_fixes_update', 20);

function updateImagesListStrField() {
    $wpdb = InstanceDB::getInstanceDB();
    $table_name = LotMetaData::getTableName();
    $column_name = 'imagesListStr';

    $column_info = $wpdb->get_row(
        $wpdb->prepare(
            "SHOW COLUMNS FROM $table_name LIKE %s",
            $column_name
        )
    );

    if ($column_info && $column_info->Type !== 'varchar(2048)') {
        $result = $wpdb->query(
            "ALTER TABLE $table_name MODIFY $column_name VARCHAR(2048) NOT NULL"
        );

        if ($result === false) {
            Debug::errorLog("An error of adding a field $column_name: " . $wpdb->last_error);
        } else {
            Debug::errorLog("Field $column_name successfully added");
        }
    }
}

function addCriminalContentFieldInMeta() {
    global $wpdb;
    $table_name = LotMetaData::getTableName();
    $column_name = 'criminalContent';

    $column_exists = $wpdb->get_row(
        $wpdb->prepare(
            "SHOW COLUMNS FROM $table_name LIKE %s",
            $column_name
        )
    );

    if (!$column_exists) {
        $sql = "ALTER TABLE $table_name 
                ADD COLUMN $column_name TINYINT(1) NOT NULL DEFAULT 0 
                AFTER eroticContent";

        $result = $wpdb->query($sql);

        if ($result === false) {
            Debug::errorLog("An error of adding a field $column_name: " . $wpdb->last_error);
        } else {
            Debug::errorLog("Field $column_name successfully added");
        }
    }
}

function addCriminalContentFieldInHistory() {
    global $wpdb;

    $db = InstanceDB::getInstanceDB();
    $table_name = $db->prefix . Importer::TABLE_NAME;
    $column_name = 'criminalContent';

    $column_exists = $wpdb->get_row(
        $wpdb->prepare(
            "SHOW COLUMNS FROM $table_name LIKE %s",
            $column_name
        )
    );

    if (!$column_exists) {
        $sql = "ALTER TABLE $table_name 
                ADD COLUMN $column_name TINYINT(1) NOT NULL DEFAULT 0 
                AFTER eroticContent";

        $result = $wpdb->query($sql);

        if ($result === false) {
            Debug::errorLog("An error of adding a field $column_name: " . $wpdb->last_error);
        } else {
            Debug::errorLog("Field $column_name successfully added");
        }
    }
}

function addImportHistoryIndexes() {
    $db = InstanceDB::getInstanceDB();
    $table_name = $db->prefix . Importer::TABLE_NAME;

    $lotSyncIndex = $db->get_var(
        $db->prepare("SHOW INDEX FROM {$table_name} WHERE Key_name = %s", 'idx_lot_sync')
    );
    if (!$lotSyncIndex) {
        $db->query("ALTER TABLE {$table_name} ADD INDEX idx_lot_sync (lotId, syncFinished)");
    }

    $syncStatusIndex = $db->get_var(
        $db->prepare("SHOW INDEX FROM {$table_name} WHERE Key_name = %s", 'idx_sync_status')
    );
    if (!$syncStatusIndex) {
        $db->query("ALTER TABLE {$table_name} ADD INDEX idx_sync_status (syncFinished, createDatetime)");
    }

    $primaryKey = $db->get_var("SHOW KEYS FROM {$table_name} WHERE Key_name = 'PRIMARY'");
    if (!$primaryKey) {
        $db->query("ALTER TABLE {$table_name} ADD PRIMARY KEY (id)");
    }

    $uniqueIdIndex = $db->get_var(
        $db->prepare("SHOW INDEX FROM {$table_name} WHERE Key_name = %s", 'id')
    );
    if ($uniqueIdIndex) {
        $db->query("ALTER TABLE {$table_name} DROP INDEX id");
    }
}

function auctionforge_config_update() {
    add_option(AUCTIONFORGE_CONFIG_OPTION_NAME, 1);
    $configVersion = get_option(AUCTIONFORGE_CONFIG_OPTION_NAME);

    if (intval($configVersion) < AUCTIONFORGE_CONFIG_VERSION) {
        flush_rewrite_rules();
        update_option(AUCTIONFORGE_CONFIG_OPTION_NAME, AUCTIONFORGE_CONFIG_VERSION, 'no');
    }
}
add_action('plugins_loaded', 'auctionforge_config_update');

function deactivatePlugin() {
    dropImportHistoryTable();
    flush_rewrite_rules();
}

function dropImportHistoryTable() {
    delete_option(AUCTIONFORGE_DB_OPTION_NAME);
    $db = InstanceDB::getInstanceDB();
    $sql = 'DROP TABLE IF EXISTS `' . $db->prefix . Importer::TABLE_NAME . "`;";
    $db->query($sql);

    return $db->query($sql);
}

function dropBidspiritTables() {
    $db = InstanceDB::getInstanceDB();
    $sql = 'DROP TABLE IF EXISTS `' . $db->prefix . FirebaseUser::TABLE_APP_USERS . "`;";
    $db->query($sql);
    $sql = 'DROP TABLE IF EXISTS `' . $db->prefix . FirebaseLog::TABLE_APP_LOGS . "`;";
    $db->query($sql);
    $sql = 'DROP TABLE IF EXISTS `' . $db->prefix . LotMetaData::TABLE_LOT_META . "`;";
    return $db->query($sql);
}

function createTableImportHistoryTable() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $db = InstanceDB::getInstanceDB();
    $table_name = $db->prefix . Importer::TABLE_NAME;
    if ($db->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE `".$table_name."` (
        id int(11) unsigned NOT NULL AUTO_INCREMENT,
        lotId int(11) unsigned NOT NULL,
        postId int(11) unsigned NULL,
        paddedIndex varchar(15) NULL,
        auctionSlug varchar(55) NOT NULL,
        lang varchar(55) NOT NULL,
        itemIndex varchar(55) NOT NULL,
        name varchar(255),
        nameL2 varchar(255),
        description text,
        descriptionL2 text,
        author varchar(255),
        authorL2 varchar(255),
        mlFields text,
        details text,
        startPrice integer(11),
        leadingBid integer(11),
        soldBid integer(11),
        auctionId integer(11),
        imagesListStr varchar(2048),
        categoryId integer(11),
        estimatedPrice varchar(55),
        tags varchar(255),
        videoUrl varchar(255),
        extraInfo text,
        params text,
        postSaleDisabled tinyint(1),
        imagesBase varchar(255),
        imagesCloned tinyint(1),
        buyoutPrice integer(11),
        lastUpdate bigint(15),
        fullPriceVat tinyint(1),
        largeDisplay tinyint(1),
        viewOnly tinyint(1),
        hidden tinyint(1),
        hiddenInPortal tinyint(1),
        removedFromAuction tinyint(1),
        eroticContent tinyint(1),
        criminalContent tinyint(1),
        isGem tinyint(1),
        priority integer(1),
        createDatetime varchar(55),
        syncStart tinyint(1) default 0,
        syncFinished tinyint(1) default 0,
        syncDatetime varchar(55),
        syncErrors text,
        syncTimes integer(1),";

        $sql = apply_filters('auctionforge_query_history_table', $sql);

        $sql .= "PRIMARY KEY (id),
        KEY idx_lot_sync (lotId, syncFinished),
        KEY idx_sync_status (syncFinished, createDatetime)\r\n)
        CHARACTER SET utf8mb4
        COLLATE utf8mb4_unicode_ci;\r\n";

        dbDelta($sql);
    }

    addImportHistoryIndexes();
}

function createBpFirebaseTables() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $db = InstanceDB::getInstanceDB();
    $table_name = $db->prefix . FirebaseUser::TABLE_APP_USERS;
    $table_name_logs = $db->prefix . FirebaseLog::TABLE_APP_LOGS;

    if ($db->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE IF NOT EXISTS `".$table_name."` (
        id int(11) unsigned NOT NULL AUTO_INCREMENT,
        firebase_id varchar(255) NOT NULL,
        created DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated DATETIME ON UPDATE CURRENT_TIMESTAMP,
        bidspirit_user_email varchar(55) UNIQUE,
        UNIQUE KEY (id)\r\n)
        CHARACTER SET utf8mb4
        COLLATE utf8mb4_unicode_ci;\r\n";
        dbDelta($sql);

        $sql = "CREATE UNIQUE INDEX bp_firebase_users_bidspirit_user_email_uindex  ON `" . $db->prefix . $table_name . "` (`bidspirit_user_email`);";
        dbDelta($sql);
    }

    if ($db->get_var("SHOW TABLES LIKE '$table_name_logs'") != $table_name_logs) {
        $sql = "CREATE TABLE IF NOT EXISTS `".$table_name_logs."` (
        id int(11) unsigned NOT NULL AUTO_INCREMENT,
        firebase_id varchar(255) NOT NULL,
        created DATETIME DEFAULT CURRENT_TIMESTAMP,
        bidspirit_user_email varchar(55),
        bidspirit_lot_id varchar(55),
        request_from_bidspirit text,
        request_to_firebase text,
        response_from_firebase text,
        response_to_bidspirit text,
        status enum('none', 'sent', 'error') default 'none',
        UNIQUE KEY (id)\r\n)
        CHARACTER SET utf8mb4
        COLLATE utf8mb4_unicode_ci;\r\n";
        dbDelta($sql);
    }
}

function createBpLotDataTable() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $db = InstanceDB::getInstanceDB();
    $table_name = LotMetaData::getTableName();

    if ($db->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE IF NOT EXISTS `".$table_name."` (
        postId bigint(20) unsigned NOT NULL,
        termId bigint(20) unsigned NOT NULL,
        id int(11) unsigned NOT NULL,
        featured tinyint(1) DEFAULT 0,
        lang varchar(2) DEFAULT 'en',
        paddedIndex varchar(15) NULL,
        itemIndex varchar(55) NOT NULL,
        name varchar(255),        
        author varchar(255),
        details text,
        startPrice integer(11),
        leadingBid integer(11),
        soldBid integer(11),
        auctionId integer(11),
        imagesListStr varchar(2048),
        categoryId integer(11),
        estimatedPrice varchar(55),
        estimatedPriceInt varchar(55),
        tags varchar(255),
        videoUrl varchar(255),
        extraInfo text,
        params text,
        postSaleDisabled tinyint(1),
        imagesBase varchar(255),
        imagesCloned tinyint(1),
        buyoutPrice integer(11),
        lastUpdate bigint(15),
        fullPriceVat tinyint(1),
        largeDisplay tinyint(1),
        viewOnly tinyint(1),
        hidden tinyint(1),
        hiddenInPortal tinyint(1),
        removedFromAuction tinyint(1),
        eroticContent tinyint(1),
        isGem tinyint(1),
        createDatetime varchar(55),
        updateDatetime TIMESTAMP DEFAULT now() ON UPDATE now(),";

        $sql = apply_filters('auctionforge_query_meta_table', $sql);

        $sql .= "PRIMARY KEY postId (postId)\r\n)
        CHARACTER SET utf8mb4
        COLLATE utf8mb4_unicode_ci;\r\n";
        dbDelta($sql);
    }
}

function createBpSubmissonDataTable() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $db = InstanceDB::getInstanceDB();
    $table_name = SubmissionFormData::getTableName();

    if ($db->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE `$table_name`
                (
                    `id`          bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                    `email`       varchar(125),
                    `data`        text               null,
                    `is_exported` tinyint  default 0 not null,
                    `ip`          varchar(55),
                    `created`     DATETIME DEFAULT now() ON UPDATE now(),
                ";
        $sql = apply_filters('auctionforge_query_bp_submission_data', $sql);

        $sql .= "\r\nPRIMARY KEY `id` (id)
                ) CHARACTER SET utf8mb4
                  COLLATE utf8mb4_unicode_ci COMMENT 'SubmissionFormData';\r\n";

        dbDelta($sql);
    }
}

function createBpMetaTableIndexes() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $table_name = LotMetaData::getTableName();
    $sql = "CREATE INDEX bp_meta_data_indexes ON " . $table_name . " (id, termId, paddedIndex, itemIndex, startPrice, leadingBid, soldBid, categoryId, estimatedPriceInt, buyoutPrice);";
    dbDelta($sql);
}

function createBpViewHistoryTable() {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    $db = InstanceDB::getInstanceDB();
    $table_name = \auctionforge\inc\model\ViewHistory::getTableName();

    if ($db->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE IF NOT EXISTS `" . $table_name . "` (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        user_email varchar(125) NOT NULL,
        post_id bigint(20) unsigned NOT NULL,
        term_id bigint(20) unsigned NOT NULL DEFAULT 0,
        viewed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY user_lot (user_email, post_id),
        KEY user_viewed (user_email, viewed_at)
        ) CHARACTER SET utf8mb4
        COLLATE utf8mb4_unicode_ci;\r\n";
        dbDelta($sql);
    }
}

function uninstallPlugin() {
    dropBidspiritTables();
    return true;
}

add_action('wp_enqueue_scripts', function () {
    global $post;
    $sourceVersion = AUCTIONFORGE_VERSION;

    $cssFile = ".min.css";
    $jsFile = ".js";
    if (WP_DEBUG) {
        $sourceVersion = time();
        $cssFile = ".css";
        $jsFile = ".js";
    }
    $appLibsJsFile = "libs.min.js";

    wp_enqueue_script('bitspirit_front_libs_app', plugin_dir_url(__FILE__).'assets/js/'.$appLibsJsFile, array('jquery'),
        $sourceVersion, true);

    // Enqueue AuctionForgeModal - custom modal library with nested modals support
    wp_enqueue_script('auctionforge_modal', plugin_dir_url(__FILE__).'assets/js/auctionforge-modal.js', array('jquery'), $sourceVersion, true);
    
    // Enable AuctionForgeModal as MicroModal replacement (for nested modals support)
    wp_add_inline_script('auctionforge_modal', 'window.USE_AUCTIONFORGE_MODAL = true;', 'before');

    wp_enqueue_script('bitspirit_front_app', plugin_dir_url(__FILE__).'assets/js/app' . $jsFile, array('jquery', 'bitspirit_front_libs_app', 'auctionforge_modal'),
        $sourceVersion, true);

    // Enqueue password validation script
    wp_enqueue_script('bitspirit_password_validation', plugin_dir_url(__FILE__).'assets/js/password-validation' . $jsFile, array('jquery', 'bitspirit_front_app'),
        $sourceVersion, true);

    wp_enqueue_style('bitspirit_frontend_vendors_style', plugin_dir_url(__FILE__).'assets/css/vendor' . $cssFile, [], $sourceVersion, 'all');
    wp_enqueue_style('bitspirit_frontend_libs_style', plugin_dir_url(__FILE__).'assets/css/libs' . $cssFile, [], $sourceVersion, 'all');

    // Enqueue password validation styles
    wp_enqueue_style('bitspirit_password_validation_style', plugin_dir_url(__FILE__).'assets/css/password-validation' . $cssFile, [], $sourceVersion, 'all');

    // Enqueue minimal layout styles if layout style is set to minimal
    $layoutStyle = \auctionforge\inc\helpers\SettingsHelper::getOption(\auctionforge\inc\controllers\Settings::LAYOUT_STYLE, 'classic');
    if ($layoutStyle === 'minimal') {
        wp_enqueue_style('auctionforge_minimal_layout', plugin_dir_url(__FILE__).'assets/css/minimal-layout.css', [], $sourceVersion, 'all');

        // Add inline CSS for minimal template custom colors
        $minHdrBg = \auctionforge\inc\helpers\SettingsHelper::getOption('minimal_header_bg', '#f5f5f5');
        $minTitleColor = \auctionforge\inc\helpers\SettingsHelper::getOption('minimal_title_color', '#333333');
        $minDateColor = \auctionforge\inc\helpers\SettingsHelper::getOption('minimal_datetime_color', '#666666');
        $minBtnBg = \auctionforge\inc\helpers\SettingsHelper::getOption('minimal_btn_bg', '#333333');
        $minBtnText = \auctionforge\inc\helpers\SettingsHelper::getOption('minimal_btn_text', '#ffffff');
        $minimalInlineCss = "";
        $minimalInlineCss .= ".bp-header__content-minimal, .bp-header__content-profile-page { background-color: {$minHdrBg}; }";
        $minimalInlineCss .= ".bp-header__content-minimal h1.title, .bp-header__content-minimal h1.title-sm, .item-header-title { color: {$minTitleColor}; }";
        $minimalInlineCss .= ".bp-item-header__time { color: {$minDateColor}; }";
        $minimalInlineCss .= ".bp-back-to-catalog-button { background-color: {$minBtnBg} !important; color: {$minBtnText} !important; }";
        $minimalInlineCss .= ".bp-back-to-catalog-button:hover { background-color: {$minBtnBg} !important; color: {$minBtnText} !important; opacity: 0.85; }";
        $minimalInlineCss .= "@media (max-width: 768px) { .navigation-bar .nav-item { background-color: {$minBtnBg} !important; color: {$minBtnText} !important; } }";

        wp_add_inline_style('auctionforge_minimal_layout', $minimalInlineCss);
    }

    // Hide profile fields (applies to both Classic and Minimal layouts)
    $hideHonorific = \auctionforge\inc\helpers\SettingsHelper::getOption('hide_profile_honorific', 'off');
    $hideId = \auctionforge\inc\helpers\SettingsHelper::getOption('hide_profile_id', 'off');
    $profileHideCss = '';
    if ($hideHonorific === 'on') {
        $profileHideCss .= "#addressFieldhonorific { display: none !important; }";
    }
    if ($hideId === 'on') {
        $profileHideCss .= "#addressFieldid { display: none !important; }";
    }
    if ($profileHideCss !== '') {
        wp_add_inline_style('bitspirit_frontend_libs_style', $profileHideCss);
    }
    
    // Enqueue profile modal styles if experimental features and option are enabled
    if (method_exists(\auctionforge\inc\helpers\SettingsHelper::class, 'isProfileModalEnabled')
        && \auctionforge\inc\helpers\SettingsHelper::isProfileModalEnabled()) {
        wp_enqueue_style('bitspirit_profile_modal_style', plugin_dir_url(__FILE__).'assets/css/profile-modal' . $cssFile, [], $sourceVersion, 'all');
        wp_enqueue_style('bitspirit_profile_modal_nav_style', plugin_dir_url(__FILE__).'assets/css/profile-modal-nav'. $cssFile, [], $sourceVersion, 'all');
    }
}, 1);

add_action('wp_enqueue_scripts', function () {
    wp_localize_script('bitspirit_front_app', 'ScoreSettings', [
        'nonce' => wp_create_nonce('wp_rest')
    ]);

    wp_localize_script('bitspirit_front_app', 'AuctionForgePlugin', [
        'pluginUrl' => plugin_dir_url(__FILE__),
        'imageBlank' => plugin_dir_url(__FILE__) . 'img/not_found.jpg',
    ]);

    wp_localize_script('bitspirit_front_app', 'AuctionForgeIPLog', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('auctionforge_ip_log'),
    ]);

    wp_localize_script('bitspirit_front_app', 'AuctionForgeFraud', [
        'ajaxUrl'     => admin_url('admin-ajax.php'),
        'nonce'       => wp_create_nonce('auctionforge_fraud_check'),
        'enforcement' => (bool) get_option('auctionforge_fraud_enforcement', false),
    ]);

    $auctionSettings = apply_filters('bidspirit_api_settings_override', []);
    $auctionInfo = apply_filters('bidspirit_api_info_override', []);
    $auctionHouse = apply_filters('bidspirit_api_house_override', []);
    $auctionItemInfo = apply_filters('bidspirit_api_item_info_override', []);
    
    wp_localize_script('bitspirit_front_app', 'API_Settings', [
        'auctionSettings' => $auctionSettings,
        'auctionInfo' => $auctionInfo,
        'auctionHouse' => $auctionHouse,
        'auctionItemInfo' => $auctionItemInfo,
        'settings' => apply_filters('bitspirit_api_settings_configure', [])
    ]);

    /*wp_localize_script('bitspirit_front_app', 'auctionforgeData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('auctionforge-nonce'),
        'stripePublicKey' => get_option('auctionforge_stripe_public_key', ''),
        'currency' => get_option('auctionforge_currency', 'USD'),
        'locale' => get_locale(),
        'timezone' => wp_timezone_string()
    ));*/
});
//require_once plugin_dir_path( __FILE__ ) . '/AuctionForge.php';

// Add defer attribute to scripts
function defer_scripts($tag, $handle, $src) {
    unset($src);
    $handleList = apply_filters('auctionforge_defer_scripts_list', array(
        'bitspirit_front_libs_app',
        'bitspirit_front_app',
        'stripe_js'
    ));

    if (in_array($handle, $handleList)) {
        return str_replace(' src', ' defer src', $tag);
    }

    return $tag;
}
add_filter('script_loader_tag', 'defer_scripts', 10, 3);

// Add the preload attribute to the style files.
function preload_style($tag, $handle, $href, $media) {
    $handleList = apply_filters('auctionforge_defer_styles_list', array(
        'bitspirit_frontend_fonts',
        'bitspirit_frontend_libs_style',
    ));
    $preloadTag = "";

    if (in_array($handle, $handleList)) {
        $preloadTag = "<link rel=\"preload\" href=\"" . $href . "\" as=\"style\" media=\"" . $media . "\" />";
    }

    return $preloadTag . $tag;
}
add_filter('style_loader_tag', 'preload_style', 10, 4);

function auctionforge_admin_scripts() {
    $data = auctionforge_plugin_info();
    wp_enqueue_script('bitspirit_admin_sweet_alert_2', plugin_dir_url( __FILE__ ) . 'admin/assets/js/sweetalert2.js', array(), '',
        true);
    wp_enqueue_script('bitspirit_admin_flatpickr_js', plugin_dir_url( __FILE__ ) . 'admin/assets/js/flatpickr.min.js', array(), '4.6.13', true);
    wp_enqueue_script('bitspirit_admin_swiper', plugin_dir_url( __FILE__ ) . 'admin/assets/js/swiper.min.js', array(), '', true);
    wp_enqueue_script('bitspirit_app_admin', plugin_dir_url( __FILE__ ) . 'admin/assets/js/bitspirit_admin-app.js',
        array('jquery'), $data['ver'], true);
    wp_enqueue_style('bitspirit_admin_flatpickr_css', '//cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css');
    wp_enqueue_style('bitspirit_app_admin_css', plugin_dir_url( __FILE__ ) . 'admin/assets/css/bitspirit_admin-app.css');
    wp_enqueue_style('bitspirit_app_admin_swiper', plugin_dir_url( __FILE__ ) . 'admin/assets/css/swiper.min.css');
}
add_action('admin_enqueue_scripts', 'auctionforge_admin_scripts');

function bp_templates() {
    $basePath = basename( __DIR__ ) . '/templates/';
    $templatePath = get_stylesheet_directory() . '/auctionforge/';
    $files = array(
        'single' => 'single-lot.php',
        'auction' => 'page_auction.php',
        'auction_list' => 'page_auction_list.php',
        'archive_list' => 'page_auction_list.php',
        'profile' => 'page_profile.php',
        'welcome_app_page' => 'page_welcome.php'
    );
    $files = apply_filters('bp_template_filter', $files);

    $templates = array();
    foreach ($files as $key => $file) {
        if (file_exists($templatePath . $file)) {
            $templates[$key] = $templatePath . $file;
        } else {
            $templates[$key] = WP_PLUGIN_DIR . "/" . $basePath . $file;
        }
    }
    return $templates;
}

function bp_template_include( $template ) {
    global $post;
    $templates = bp_templates();
    $auctionListKey = 'auction_list';
    $manualListKey = 'manual_auction_list';
    $archiveListKey = 'archive_list';
    $profileKey = 'profile';
    $welcomeKey = 'welcome_app_page';
    $auctionPolylangId = 0;
    $archivePolylangId = 0;
    $manualPolylangId = 0;
    $profilePolylangId = 0;
    $welcomePolylangId = 0;
    $pageAuctionListKey = SettingsHelper::getOption($auctionListKey, 0);
    $pageManualListKey = SettingsHelper::getOption($manualListKey, 0);
    $pageArchiveListKey = SettingsHelper::getOption($archiveListKey, 0);
    $pageProfileKey = SettingsHelper::getOption($profileKey, 0);
    $pageWelcomeKey = SettingsHelper::getOption($welcomeKey, 0);

    if (PolylangSupport::isPolylangActive()) {
        $lang = pll_current_language();
        $auctionPolylangId = pll_get_post($pageAuctionListKey, $lang);
        $archivePolylangId = pll_get_post($pageArchiveListKey, $lang);
        $manualPolylangId = pll_get_post($pageManualListKey, $lang);
        $profilePolylangId = pll_get_post($pageProfileKey, $lang);
        $welcomePolylangId = pll_get_post($pageWelcomeKey, $lang);
    }

    if (Conditions::isTaxTemplate()) {
        $path_file = wp_normalize_path($templates['auction']);
    }

    if (Conditions::isSingleLotTemplate($post)) {
        $path_file = wp_normalize_path($templates['single']);
    }

    if (Conditions::isAuctionListTemplate($post, $pageAuctionListKey, $auctionPolylangId)) {
        $path_file = wp_normalize_path($templates[$auctionListKey]);
    }

    if (Conditions::isManualAuctionListTemplate($post, $pageManualListKey, $manualPolylangId)) {
        $path_file = wp_normalize_path($templates[$auctionListKey]);
    }

    if (Conditions::isArchiveListTemplate($post, $pageArchiveListKey, $archivePolylangId)) {
        $path_file = wp_normalize_path($templates[$auctionListKey]);
    }

    if (Conditions::isProfileTemplate($post, $pageProfileKey, $profilePolylangId)) {
        $path_file = wp_normalize_path($templates[$profileKey]);
    }

    if (Conditions::isPageTemplate($post, $pageWelcomeKey, $welcomePolylangId)) {
        $path_file = wp_normalize_path($templates[$welcomeKey]);
    }

    $template = apply_filters('bp_template_action', $template);
    if (key_exists($template, $templates)) {
        $path_file = wp_normalize_path($templates[$template]);
    }

    if (!empty($path_file)) {
        $path_file = apply_filters('bp_template_include_action', $path_file, $templates);
    }

    if ( !empty($path_file) && file_exists( $path_file ) ) {
        return $path_file;
    }

    return $template;
}
add_filter( 'template_include', 'bp_template_include', 99 );

function auctionforge_pre_get_lot_sort($query) {
    if( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    if(Conditions::isAuctionPage($query)) {
        /** @var WP_Query $query */

        $query->set(LotMetaData::BP_QUERY, array("order" => 1));
        $fieldQuery = LotMetaData::BP_QUERY;
        $meta_query = [];
        $part = get_query_var('part');
        if (!empty($part) && intval($part) > 0) {
            $meta_query = (array)$query->get('meta_query');
            $auction = get_queried_object();

            $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
            if (!empty($auctionDays[intval($part) - 1])) {
                $auctionDay = $auctionDays[intval($part) - 1];
            } else {
                $auctionDay = null;
                $query->set_404();
                status_header(404);
            }

            if (isset($auctionDay->firstLotIndex) && isset($auctionDay->lastLotIndex)) {
                $meta_query = array(
                    "bp_index" => array(
                        "between" => array(
                            array(
                                "compare" => ">=",
                                "value" => intval($auctionDay->firstLotIndex),
                            ),
                            array(
                                "compare" => "<=",
                                "value" => intval($auctionDay->lastLotIndex),
                            ),
                        ),
                    ),
                );
            }

            $meta_query = apply_filters('auctionforge_before_main_meta_query', $meta_query, $auction, $auctionDays, $auctionDay, $part);
            $query->set($fieldQuery, $meta_query);
        } elseif (!empty($part)) {
            $meta_query = (array)$query->get('meta_query');
            $auction = get_queried_object();

            $meta_query = apply_filters('auctionforge_before_main_part_meta_query', $meta_query, $auction, $part);
            $query->set($fieldQuery, $meta_query);
        }

        $orderByFields = BidspiritLots::sort_order();

        if (isset($orderByFields['orderBy']) && $orderByFields['orderBy'] == 'soldBid') {
            $compare = ">";
            $data["bp_field"][] = [
                "field" => "soldBid",
                "value" => 0,
                "compare" => $compare
            ];
            $query->set(LotMetaData::BP_QUERY, array_merge($data, $meta_query));
        }

        $query->set('bp_orderby', $orderByFields['orderBy']);
        $query->set('order', $orderByFields['order']);
    }
}
add_action('pre_get_posts' ,'auctionforge_pre_get_lot_sort', 1, 1);

/** Phone-home ping - DISABLED */

function sortAuctionASC($a, $b)
{
    $auctionDaysA = SettingsHelper::getTermOption($a->term_id, 'auction_days');
    $auctionDaysB = SettingsHelper::getTermOption($b->term_id, 'auction_days');

    if (empty($auctionDaysA) || empty($auctionDaysB)) {
        return 1;
    }

    if (!empty($auctionDaysA[0]->auctionStarted) && !empty($auctionDaysB[0]->auctionStarted)) {
        $dateTimeA = $auctionDaysA[0]->auctionStarted;
        $dateTimeB = $auctionDaysB[0]->auctionStarted;
    } else {
        $dateTimeA = $auctionDaysA[0]->date . " " . $auctionDaysA[0]->time;
        $dateTimeB = $auctionDaysB[0]->date . " " . $auctionDaysB[0]->time;
    }

    if ($dateTimeA == $dateTimeB) {
        return 0;
    }
    return ($dateTimeA < $dateTimeB) ? -1 : 1;
}

function sortAuctionDESC($a, $b)
{
    $auctionDaysA = SettingsHelper::getTermOption($a->term_id, 'auction_days');
    $auctionDaysB = SettingsHelper::getTermOption($b->term_id, 'auction_days');

    if (empty($auctionDaysA) || empty($auctionDaysB)) {
        return -1;
    }

    if (!empty($auctionDaysA[0]->auctionStarted) && !empty($auctionDaysB[0]->auctionStarted)) {
        $dateTimeA = $auctionDaysA[0]->auctionStarted;
        $dateTimeB = $auctionDaysB[0]->auctionStarted;
    } else {
        $dateTimeA = $auctionDaysA[0]->date . " " . $auctionDaysA[0]->time;
        $dateTimeB = $auctionDaysB[0]->date . " " . $auctionDaysB[0]->time;
    }

    if ($dateTimeA == $dateTimeB) {
        return 0;
    }
    return ($dateTimeA > $dateTimeB) ? -1 : 1;
}

function cron_add_minutely( $schedules ) {
    $schedules['bp_minutely'] = array(
        'interval' => BP_MINUTELY,
        'display' => 'Minutely'
    );
    return $schedules;
}
add_filter('cron_schedules', 'cron_add_minutely');

function cron_add_ten_minutely( $schedules ) {
    $schedules['bp_ten_minutely'] = array(
        'interval' => BP_MINUTELY * 10,
        'display' => 'Every 10 minutes'
    );
    return $schedules;
}
add_filter('cron_schedules', 'cron_add_ten_minutely');

function cron_add_hourly( $schedules ) {
    $schedules['bp_hourly'] = array(
        'interval' => BP_HOURLY,
        'display' => 'Hourly'
    );
    return $schedules;
}
add_filter('cron_schedules', 'cron_add_hourly');

function cron_add_24_hourly( $schedules ) {
    $schedules['bp_24_hourly'] = array(
        'interval' => BP_24_HOURLY,
        'display' => 'Every 24 hours'
    );
    return $schedules;
}
add_filter('cron_schedules', 'cron_add_24_hourly');

if (SettingsHelper::getOption('sync_cheduled', 'off') === 'on' && !empty($_SERVER['SERVER_NAME'])) {
    $attr = array($_SERVER['SERVER_NAME']);
    if(!wp_next_scheduled('bidspirit_import', $attr)) {
        wp_schedule_event(time(), 'bp_hourly', 'bidspirit_import', $attr);
    }
    function bidspirit_import_action($host) {
        unset($host);
        $auctionList = new AuctionList();
        $auctionList->init();

        $lotList = new LotList();
        $lotList->init();
    }
    add_action('bidspirit_import', 'bidspirit_import_action', 10, 1);

    if(!wp_next_scheduled('data_import', $attr)) {
        wp_schedule_event(time(), 'bp_minutely', 'data_import', $attr);
    }
    function data_import_action($host) {
        unset($host);
        $insertLots = new InsertLotsBS();
        $insertLots->init();
    }
    add_action('data_import', 'data_import_action', 10, 1);

    if(!wp_next_scheduled('bidspirit_archive_import', $attr)) {
        wp_schedule_event(time(), 'bp_24_hourly', 'bidspirit_archive_import', $attr);
    }
    function bidspirit_archive_import_action($host) {
        unset($host);
        $auctionList = new AuctionList();
        $auctionList->init();

        $lotList = new LotList();
        $lotList->init(false);
    }
    add_action('bidspirit_archive_import', 'bidspirit_archive_import_action', 10, 1);
}

function auctionforge_locale() {
    unload_textdomain('auctionforge');
    unload_textdomain('auctionforge');
    load_plugin_textdomain('auctionforge', false, dirname(plugin_basename(__FILE__ )) . '/language/');
    load_plugin_textdomain('auctionforge', false, dirname(plugin_basename(__FILE__)) . '/language/');
}
add_action('init', 'auctionforge_locale', 0);

add_image_size(BidspiritLots::$imageSizes[0], 185, 0, false);
add_image_size(BidspiritLots::$imageSizes[1], 280, 0, false);
add_image_size(BidspiritLots::$imageSizes[2], 770, 0, false);

// init plugin update checker - DISABLED to prevent site tracking
// require_once __DIR__ . '/plugin-update-checker/plugin-update-checker.php';

/**
 * Disable Debug Bar integration to prevent conflicts with Query Monitor
 * @todo Need test
 * @see #947
 */
// add_filter('puc_v5_debug_bar_enabled', '__return_false');



/** Legacy update checker - DISABLED (replaced by AuctionForge auto-updater) */
