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

/**
 * Plugin activation
 */
function stakmv_free_plugin_activate() {

    global $wpdb;

    // -----------------------------
    // Create bids table
    // -----------------------------
    $charset = $wpdb->get_charset_collate();

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

    $ratings_sql = "CREATE TABLE " . STAKMV_VENDOR_RATINGS_TABLE . " (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        order_id BIGINT UNSIGNED NOT NULL,
        auction_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
        vendor_id BIGINT UNSIGNED NOT NULL,
        buyer_id BIGINT UNSIGNED NOT NULL,
        rating TINYINT UNSIGNED NOT NULL,
        review TEXT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NULL,
        PRIMARY KEY (id),
        UNIQUE KEY uniq_order_vendor_buyer (order_id, vendor_id, buyer_id),
        KEY vendor_id (vendor_id),
        KEY buyer_id (buyer_id),
        KEY order_id (order_id)
    ) $charset;";

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

    // -----------------------------
    // Schedule cron
    // -----------------------------
    if (!wp_next_scheduled('stakmv_auction_recovery_cron')) {
        wp_schedule_event(time(), 'hourly', 'stakmv_auction_recovery_cron');
    }

    // -----------------------------
    // Create Vendor role
    // -----------------------------
   // Create Vendor role
if (!get_role('stakmv_vendor')) {
    add_role(
        'stakmv_vendor',
        __('Vendor', 'stak-multivendor'),
        [
            'read'         => true,
            'upload_files' => true,
        ]
    );
}

}

/**
 * Plugin deactivation
 */
function stakmv_free_plugin_deactivate() {
    wp_clear_scheduled_hook('stakmv_auction_recovery_cron');
}

// ✅ ONE activation hook
register_activation_hook(
    dirname(__DIR__) . '/mv-auctions.php',
    'stakmv_free_plugin_activate'
);

register_deactivation_hook(
    dirname(__DIR__) . '/mv-auctions.php',
    'stakmv_free_plugin_deactivate'
);
