<?php
// bid_functions.php - Bid Helper Functions
// File location: /bidwheels.net/includes/bid_functions.php

<?php
// bid_functions.php - Bid Helper Functions
// File location: /bidwheels.net/includes/bid_functions.php

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/mailer.php';

/**
 * Place a bid on a product
 */
function placeBid($product_id, $user_id, $amount, $is_system = false) {
    // Check if product exists and is active
    $product = fetchOne("SELECT * FROM products WHERE id = $product_id AND is_reserved = 0 AND end_time > NOW()");
    if (!$product) {
        return ['success' => false, 'message' => 'Product is not available for bidding'];
    }
    
    // Check minimum bid
    $current_highest = fetchOne("SELECT MAX(amount) as max FROM bids WHERE product_id = $product_id");
    $min_bid = $current_highest['max'] ? $current_highest['max'] + 1 : $product['starting_price'];
    
    if ($amount < $min_bid) {
        return ['success' => false, 'message' => 'Bid amount must be at least $' . number_format($min_bid, 2)];
    }
    
    // Get previous highest bidder for notification
    $previous_highest = fetchOne("
        SELECT user_id, amount FROM bids 
        WHERE product_id = $product_id 
        ORDER BY amount DESC 
        LIMIT 1
    ");
    
    // Place bid
    $bid_id = insert('bids', [
        'product_id' => $product_id,
        'user_id' => $user_id,
        'amount' => $amount,
        'is_system_bid' => $is_system ? 1 : 0
    ]);
    
    if ($bid_id) {
        // Update product current highest bid
        update('products', ['current_highest_bid' => $amount], "id = $product_id");
        
        // Send outbid notification to previous highest bidder
        if ($previous_highest && $previous_highest['user_id'] != $user_id) {
            $previous_user = fetchOne("SELECT * FROM users WHERE id = {$previous_highest['user_id']}");
            if ($previous_user && $previous_user['is_dummy'] == 0) {
                sendOutbidEmail(
                    $previous_user['email'],
                    $previous_user['name'],
                    $product['name'],
                    $amount,
                    $product_id
                );
            }
        }
        
        return ['success' => true, 'message' => 'Bid placed successfully!', 'bid_id' => $bid_id];
    }
    
    return ['success' => false, 'message' => 'Failed to place bid'];
}

/**
 * Get user's bids for a product
 */
function getUserBidsForProduct($user_id, $product_id) {
    return fetchAll("
        SELECT * FROM bids 
        WHERE user_id = $user_id AND product_id = $product_id 
        ORDER BY amount DESC
    ");
}

/**
 * Check if user is winning a product
 */
function isUserWinning($user_id, $product_id) {
    $highest = fetchOne("
        SELECT user_id FROM bids 
        WHERE product_id = $product_id 
        ORDER BY amount DESC 
        LIMIT 1
    ");
    return $highest && $highest['user_id'] == $user_id;
}

/**
 * Get bid statistics for a product
 */
function getBidStatistics($product_id) {
    return fetchOne("
        SELECT 
            COUNT(*) as total_bids,
            MIN(amount) as min_bid,
            MAX(amount) as max_bid,
            AVG(amount) as avg_bid,
            COUNT(DISTINCT user_id) as unique_bidders,
            SUM(CASE WHEN is_system_bid = 1 THEN 1 ELSE 0 END) as system_bids,
            SUM(CASE WHEN is_system_bid = 0 THEN 1 ELSE 0 END) as real_bids
        FROM bids 
        WHERE product_id = $product_id
    ");
}

/**
 * Get bidding history for a user
 */
function getUserBiddingHistory($user_id, $limit = 20) {
    return fetchAll("
        SELECT b.*, p.name as product_name, p.id as product_id,
               (SELECT MAX(amount) FROM bids WHERE product_id = p.id) as current_highest
        FROM bids b
        LEFT JOIN products p ON b.product_id = p.id
        WHERE b.user_id = $user_id
        ORDER BY b.created_at DESC
        LIMIT $limit
    ");
}
?>