<?php
/**
 * Plugin Name: Stak Multivendor
 * Description: Stak Multivendor marketplace and auction features for WooCommerce
 * Version: 0.1.0
 * Author: Stak.ng
 * Requires at least: 6.2
 * Requires PHP: 7.4
 * License: GPL-2.0-or-later
 * Text Domain: stak-multivendor
 */
if (!defined('STAKMV_PLUGIN_PATH')) {
    define('STAKMV_PLUGIN_PATH', plugin_dir_path(__FILE__));
}

if (!defined('STAKMV_PLUGIN_URL')) {
    define('STAKMV_PLUGIN_URL', plugin_dir_url(__FILE__));
}

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

/**
 * -------------------------------------------------
 * LOAD CONSTANTS (ONCE, FIRST, ONLY PLACE)
 * -------------------------------------------------
 */
require_once __DIR__ . '/includes/constants.php';
require_once STAKMV_PLUGIN_PATH . 'includes/activator.php';

/**
 * -------------------------------------------------
 * SAFE DATABASE CHECK
 * -------------------------------------------------
 */
add_action('plugins_loaded', 'stakmv_maybe_create_bid_table', 5);

function stakmv_maybe_create_bid_table() {
    global $wpdb;

    $table = STAKMV_AUCTION_BIDS_TABLE;

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time table existence check on plugin load.
    $existing_table = $wpdb->get_var(
        $wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))
    );
    if ($existing_table === $table) {
        return;
    }

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        auction_id BIGINT UNSIGNED NOT NULL,
        user_id BIGINT UNSIGNED NOT NULL,
        bid_amount DECIMAL(10,2) NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY auction_id (auction_id),
        KEY user_id (user_id)
    ) $charset;";

    dbDelta($sql);
}

/**
 * -------------------------------------------------
 * MAIN BOOTSTRAP
 * -------------------------------------------------
 */
add_action('plugins_loaded', function () {

    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function () {
            echo '<div class="notice notice-error"><p>
                Stak Multivendor requires WooCommerce to be installed and active.
            </p></div>';
        });
        return;
    }

    /* -----------------------------
       CORE
    ----------------------------- */
    require_once STAKMV_PLUGIN_PATH . 'includes/helpers.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/vendor-applications.php';
    /* -----------------------------
       ADMIN
    ----------------------------- */
    require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-appearance.php';

    if (is_admin()) {

        require_once STAKMV_PLUGIN_PATH . 'includes/admin/class-admin-menu.php';
        new StakMV_Admin_Menu();

        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-dashboard.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-general.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-form.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-api.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-bidding.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-pro-features.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/settings-integration.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/vendors-applications-tab.php';
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/management.php';

        // Admin: Sample Data (idempotent) — adds a "Sample Data" tab and insertion handler.
        require_once STAKMV_PLUGIN_PATH . 'includes/admin/class-mv-auctions-sample-data.php';
    }

    /* -----------------------------
       AUCTIONS CORE
    ----------------------------- */
    require_once STAKMV_PLUGIN_PATH . 'includes/products/auction-product.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/bidding/bidding.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/buy-now-hooks.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/shipping/live-rates.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/api/rest-core.php';

    /* -----------------------------
       RECOVERY / CRON
    ----------------------------- */
    require_once STAKMV_PLUGIN_PATH . 'includes/recovery/recovery.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/cron-auction-end.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/cron-auction-fallback.php';

    /* -----------------------------
       FRONTEND VENDOR
    ----------------------------- */
    require_once STAKMV_PLUGIN_PATH . 'includes/vendor/shortcodes.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/vendor/enqueue.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/handlers/listing-save.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/handlers/profile-save.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/access-control.php';
    // Public vendor profile (free): rewrite, loader, and helper.
    require_once STAKMV_PLUGIN_PATH . 'includes/public/vendor-profile.php';
    // Public browse listings (free) shortcode + AJAX.
    require_once STAKMV_PLUGIN_PATH . 'includes/public/browse-listings.php';
    // Buyer->vendor rating system.
    require_once STAKMV_PLUGIN_PATH . 'includes/ratings/ratings.php';

    /**
     * Free Escrow baseline
     * - store escrow records on orders (postmeta)
     * - admin can approve/refund via Vendors admin tab
     * - extensions may hook into the escrow lifecycle actions
     */
    require_once STAKMV_PLUGIN_PATH . 'includes/escrow/escrow.php';

    

    require_once STAKMV_PLUGIN_PATH . 'includes/roles.php';
    require_once STAKMV_PLUGIN_PATH . 'includes/vendor-role-switch.php';

});

/**
 * -------------------------------------------------
 * DASHICONS (FRONTEND)
 * -------------------------------------------------
 */
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('dashicons');
});

add_action('wp_enqueue_scripts', function () {
    if (is_admin()) {
        return;
    }

    $theme_colors = function_exists('stakmv_get_theme_colors') ? stakmv_get_theme_colors() : array();

    wp_enqueue_style(
        'stakmv-theme-colors',
        STAKMV_PLUGIN_URL . 'assets/css/theme-colors.css',
        array(),
        file_exists(STAKMV_PLUGIN_PATH . 'assets/css/theme-colors.css')
            ? (string) filemtime(STAKMV_PLUGIN_PATH . 'assets/css/theme-colors.css')
            : (defined('STAKMV_VERSION') ? STAKMV_VERSION : '1.0.0')
    );

    wp_enqueue_script(
        'stakmv-theme-colors',
        STAKMV_PLUGIN_URL . 'assets/js/theme-colors.js',
        array(),
        file_exists(STAKMV_PLUGIN_PATH . 'assets/js/theme-colors.js')
            ? (string) filemtime(STAKMV_PLUGIN_PATH . 'assets/js/theme-colors.js')
            : (defined('STAKMV_VERSION') ? STAKMV_VERSION : '1.0.0'),
        true
    );

    wp_localize_script(
        'stakmv-theme-colors',
        'STAKMV_THEME_COLORS',
        array(
            'colors' => $theme_colors,
        )
    );

    if (!empty($theme_colors) && is_array($theme_colors)) {
        $map = array(
            'page_bg_start' => '--wcmv-color-page-bg-start',
            'page_bg_end'   => '--wcmv-color-page-bg-end',
            'card_bg'       => '--wcmv-color-card-bg',
            'card_border'   => '--wcmv-color-card-border',
            'heading_text'  => '--wcmv-color-heading',
            'body_text'     => '--wcmv-color-body',
            'muted_text'    => '--wcmv-color-muted',
            'button_start'  => '--wcmv-color-button-start',
            'button_end'    => '--wcmv-color-button-end',
            'success'       => '--wcmv-color-success',
            'info'          => '--wcmv-color-info',
            'danger'        => '--wcmv-color-danger',
            'badge_bg'      => '--wcmv-color-badge',
        );

        $css = ':root{';
        foreach ($map as $source => $css_var) {
            if (!isset($theme_colors[$source])) {
                continue;
            }
            $hex = sanitize_hex_color((string) $theme_colors[$source]);
            if (!$hex) {
                continue;
            }
            $css .= $css_var . ':' . $hex . ';';
        }

        if (function_exists('stakmv_get_product_button_style_options')) {
            $btn = stakmv_get_product_button_style_options();
            $border = sanitize_hex_color((string) ($btn['border_color'] ?? ''));
            $text = sanitize_hex_color((string) ($btn['text_color'] ?? ''));
            $hover_bg = sanitize_hex_color((string) ($btn['hover_bg'] ?? ''));
            $hover_text = sanitize_hex_color((string) ($btn['hover_text'] ?? ''));
            $radius = (int) ($btn['radius'] ?? 10);
            $border_width = (int) ($btn['border_width'] ?? 1);

            if ($border) {
                $css .= '--wcmv-product-btn-border-color:' . $border . ';';
            }
            if ($text) {
                $css .= '--wcmv-product-btn-text-color:' . $text . ';';
            }
            if ($hover_bg) {
                $css .= '--wcmv-product-btn-hover-bg:' . $hover_bg . ';';
            }
            if ($hover_text) {
                $css .= '--wcmv-product-btn-hover-text:' . $hover_text . ';';
            }
            $css .= '--wcmv-product-btn-radius:' . max(0, min(24, $radius)) . 'px;';
            $css .= '--wcmv-product-btn-border-width:' . max(1, min(4, $border_width)) . 'px;';
        }
        $css .= '}';
        wp_add_inline_style('stakmv-theme-colors', wp_strip_all_tags($css));
    }
});

add_filter('body_class', function ($classes) {
    if (is_admin()) {
        return $classes;
    }

    $corner_style = function_exists('stakmv_get_corner_style') ? stakmv_get_corner_style() : 'flat';
    $classes[] = ($corner_style === 'flat') ? 'wcmv-corners-flat' : 'wcmv-corners-rounded';

    $tabs_layout = function_exists('stakmv_get_dashboard_tabs_layout') ? stakmv_get_dashboard_tabs_layout() : 'vertical';
    $classes[] = ($tabs_layout === 'vertical') ? 'wcmv-tabs-vertical' : 'wcmv-tabs-horizontal';

    $layout_mode = function_exists('stakmv_get_frontend_layout_mode') ? stakmv_get_frontend_layout_mode() : 'boxed';
    $classes[] = ($layout_mode === 'full_width') ? 'wcmv-layout-full-width' : 'wcmv-layout-boxed';

    if (is_product()) {
        $product_layout_mode = function_exists('stakmv_get_product_page_layout_mode') ? stakmv_get_product_page_layout_mode() : 'full_width';
        $classes[] = ($product_layout_mode === 'full_width') ? 'wcmv-product-layout-full-width' : 'wcmv-product-layout-contained';

        $product_corner_style = function_exists('stakmv_get_product_page_corner_style') ? stakmv_get_product_page_corner_style() : 'flat';
        $classes[] = ($product_corner_style === 'flat') ? 'wcmv-product-corners-flat' : 'wcmv-product-corners-rounded';
    }

    return $classes;
});


add_action('wp_enqueue_scripts', function () {

  if ( is_admin() ) {
    return;
  }

  global $post;

  // Enqueue assets whenever the shortcode is present in the current post content.
  if ( $post && isset( $post->post_content ) && has_shortcode( $post->post_content, 'stakmv-browse-listings' ) ) {

    wp_enqueue_style(
      'stakmv-browse-listings',
      STAKMV_PLUGIN_URL . 'assets/css/browse-listings.css',
      [],
      filemtime(STAKMV_PLUGIN_PATH . 'assets/css/browse-listings.css')
    );

    wp_enqueue_script(
      'stakmv-browse-listings',
      STAKMV_PLUGIN_URL . 'assets/js/browse-listings.js',
      array('jquery'),
      filemtime(STAKMV_PLUGIN_PATH . 'assets/js/browse-listings.js'),
      true
    );

    wp_localize_script(
      'stakmv-browse-listings',
      'STAKMV_BROWSE',
      array(
        'ajax' => admin_url('admin-ajax.php'),
      )
    );
  }
});
