<?php
// auto_bid_script.php - Manual Auto Bid Script
// File location: /bidwheels.net/admin/auto_bid_script.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/mailer.php';
require_once 'includes/admin_header.php';

requireAdmin();

$message = '';
$error = '';

// Get all active products (not reserved, not ended)
$active_products = fetchAll("
    SELECT p.*, 
           (SELECT MAX(amount) FROM bids WHERE product_id = p.id) as current_highest
    FROM products p
    WHERE p.is_reserved = 0 
    AND p.end_time > NOW()
    ORDER BY p.id
");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['run_auto_bid'])) {
    $bids_placed = 0;
    $products_updated = 0;
    
    // Get dummy users for system bids
    $dummy_users = fetchAll("SELECT id FROM users WHERE is_dummy = 1");
    
    if (count($dummy_users) == 0) {
        $error = 'No dummy users found. Please create dummy users first.';
    } else {
        foreach ($active_products as $product) {
            $current_highest = $product['current_highest'] ?? $product['starting_price'];
            $max_allowed = $product['starting_price'] * (1 + MAX_BID_PERCENTAGE_CAP / 100);
            
            // Check if we can place a bid (not exceeding max cap)
            if ($current_highest < $max_allowed) {
                // Random increment between MIN and MAX
                $increment = rand(MIN_BID_INCREMENT, MAX_BID_INCREMENT);
                $new_bid = $current_highest + $increment;
                
                // Don't exceed max cap
                if ($new_bid > $max_allowed) {
                    $new_bid = $max_allowed;
                }
                
                // Get previous highest bidder for outbid email
                $previous_highest = fetchOne("
                    SELECT user_id, amount FROM bids 
                    WHERE product_id = {$product['id']} 
                    ORDER BY amount DESC 
                    LIMIT 1
                ");
                
                // Select random dummy user
                $random_user = $dummy_users[array_rand($dummy_users)];
                
                // Place system bid
                $bid_id = insert('bids', [
                    'product_id' => $product['id'],
                    'user_id' => $random_user['id'],
                    'amount' => $new_bid,
                    'is_system_bid' => 1
                ]);
                
                if ($bid_id) {
                    $bids_placed++;
                    $products_updated++;
                    
                    // Send outbid email to previous highest bidder (if real user)
                    if ($previous_highest && $previous_highest['user_id'] > 0) {
                        $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'],
                                $new_bid,
                                $product['id']
                            );
                        }
                    }
                }
            }
        }
        
        $message = "Auto bid script completed! $bids_placed bids placed on $products_updated products.";
    }
}

// Get count of active products
$active_count = count($active_products);
?>

<div class="admin-page">
    <h1 class="page-title">Auto Bid Script</h1>
    
    <?php if ($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="info-box">
        <h3><i class="fas fa-info-circle"></i> How It Works</h3>
        <p>This script will automatically place higher bids on all active (non-reserved) listings. Each bid will be placed by a random dummy user, making it look like real user activity.</p>
        <ul>
            <li><strong>Bid increment:</strong> Between $<?php echo MIN_BID_INCREMENT; ?> and $<?php echo MAX_BID_INCREMENT; ?> (random)</li>
            <li><strong>Maximum cap:</strong> <?php echo MAX_BID_PERCENTAGE_CAP; ?>% above starting price</li>
            <li><strong>Bidders:</strong> Random dummy user accounts</li>
            <li><strong>Email notifications:</strong> Real users will be notified if they are outbid</li>
        </ul>
    </div>
    
    <div class="stats-box">
        <div class="stat">
            <span class="stat-label">Active Products</span>
            <span class="stat-value"><?php echo $active_count; ?></span>
        </div>
    </div>
    
    <form method="POST" action="" onsubmit="return confirm('Are you sure you want to run the auto bid script? This will place new bids on all active listings.');">
        <button type="submit" name="run_auto_bid" class="btn btn-primary btn-large" <?php echo $active_count == 0 ? 'disabled' : ''; ?>>
            <i class="fas fa-magic"></i> Run Auto Bid Script
        </button>
    </form>
    
    <div class="active-products">
        <h3>Active Products (<?php echo $active_count; ?>)</h3>
        <?php if ($active_count > 0): ?>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Product Name</th>
                        <th>Starting Price</th>
                        <th>Current Bid</th>
                        <th>Max Allowed</th>
                        <th>End Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($active_products as $product): ?>
                        <?php
                        $current = $product['current_highest'] ?? $product['starting_price'];
                        $max_allowed = $product['starting_price'] * (1 + MAX_BID_PERCENTAGE_CAP / 100);
                        ?>
                        <tr>
                            <td><?php echo $product['id']; ?></td>
                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                            <td><?php echo formatPrice($product['starting_price']); ?></td>
                            <td><?php echo formatPrice($current); ?></td>
                            <td><?php echo formatPrice($max_allowed); ?></td>
                            <td><?php echo date('M d, Y g:i A', strtotime($product['end_time'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p>No active products available for auto bidding.</p>
        <?php endif; ?>
    </div>
</div>

<style>
.admin-page {
    max-width: 1200px;
}
.info-box {
    background: #e3f2fd;
    border-left: 4px solid #2196f3;
    padding: 20px;
    border-radius: 5px;
    margin-bottom: 25px;
}
.info-box h3 {
    margin-bottom: 10px;
}
.info-box ul {
    margin-top: 10px;
    margin-left: 20px;
}
.stats-box {
    background: white;
    padding: 20px;
    border-radius: 5px;
    margin-bottom: 25px;
    text-align: center;
}
.stat {
    display: inline-block;
    padding: 10px 30px;
}
.stat-label {
    display: block;
    font-size: 14px;
    color: #666;
}
.stat-value {
    display: block;
    font-size: 36px;
    font-weight: bold;
    color: #e63946;
}
.btn-large {
    padding: 15px 30px;
    font-size: 18px;
    width: 100%;
    margin-bottom: 30px;
}
.btn-primary:disabled {
    background: #ccc;
    cursor: not-allowed;
}
.active-products {
    background: white;
    padding: 20px;
    border-radius: 5px;
}
.active-products h3 {
    margin-bottom: 20px;
}
.admin-table {
    width: 100%;
    border-collapse: collapse;
}
.admin-table th, .admin-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}
.admin-table th {
    background: #f8f9fa;
}
@media (max-width: 768px) {
    .admin-table {
        font-size: 12px;
    }
}
</style>

<?php require_once 'includes/admin_footer.php'; ?>