<?php
session_start();
include 'session.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = 'Invalid request method';
    header('Location: trading-bots.php');
    exit();
}

// Validate required parameters
if (!isset($_POST['bot_plan_id']) || empty($_POST['bot_plan_id'])) {
    $_SESSION['error'] = 'Please select a bot plan';
    header('Location: trading-bots.php');
    exit();
}

$bot_plan_id = intval($_POST['bot_plan_id']);
$user_id = $_SESSION['user_id'];

// Start transaction
mysqli_begin_transaction($conn);

try {
    // 1. Get bot plan details
    $plan_sql = "SELECT * FROM trading_bot_plans WHERE id = '$bot_plan_id' AND is_active = 1";
    $plan_result = mysqli_query($conn, $plan_sql);
    
    if (!$plan_result || mysqli_num_rows($plan_result) == 0) {
        throw new Exception('Selected bot plan not found or inactive');
    }
    
    $bot_plan = mysqli_fetch_assoc($plan_result);
    
    // 2. Check if user has enough available balance
    $user_sql = "SELECT available_balance, fund_balance FROM users WHERE id = '$user_id'";
    $user_result = mysqli_query($conn, $user_sql);
    $user = mysqli_fetch_assoc($user_result);
    
    $subscription_fee = floatval($bot_plan['subscription_fee']);
    $min_balance = floatval($bot_plan['min_trading_balance']);
    $max_balance = $bot_plan['max_trading_balance'] ? floatval($bot_plan['max_trading_balance']) : null;
    
    $available_balance = floatval($user['available_balance']);
    $current_fund_balance = floatval($user['fund_balance']);
    
    // Check if user has enough available balance for subscription fee
    if ($available_balance < $subscription_fee) {
        throw new Exception('Insufficient available balance. Please add funds first.');
    }
    
    // 3. Calculate trading balance (user can choose how much to allocate)
    $trading_balance = $available_balance - $subscription_fee;
    
    // Apply min/max limits
    if ($trading_balance < $min_balance) {
        throw new Exception("Minimum trading balance required: $" . number_format($min_balance, 2));
    }
    
    if ($max_balance !== null && $trading_balance > $max_balance) {
        $trading_balance = $max_balance;
    }
    
    // 4. Check for existing active subscription
    $active_sub_sql = "SELECT id FROM user_bot_subscriptions WHERE user_id = '$user_id' AND status = 'active'";
    $active_sub_result = mysqli_query($conn, $active_sub_sql);
    
    if (mysqli_num_rows($active_sub_result) > 0) {
        // User has active subscription - check if it's the same plan
        $active_sub = mysqli_fetch_assoc($active_sub_result);
        $active_plan_sql = "SELECT bot_plan_id FROM user_bot_subscriptions WHERE id = '{$active_sub['id']}'";
        $active_plan_result = mysqli_query($conn, $active_plan_sql);
        $active_plan = mysqli_fetch_assoc($active_plan_result);
        
        if ($active_plan['bot_plan_id'] == $bot_plan_id) {
            throw new Exception('You are already subscribed to this bot plan');
        }
        
        // Check if it's an upgrade or downgrade
        $current_plan_sql = "SELECT sort_order FROM trading_bot_plans WHERE id = '{$active_plan['bot_plan_id']}'";
        $current_plan_result = mysqli_query($conn, $current_plan_sql);
        $current_plan = mysqli_fetch_assoc($current_plan_result);
        
        $new_plan_sql = "SELECT sort_order FROM trading_bot_plans WHERE id = '$bot_plan_id'";
        $new_plan_result = mysqli_query($conn, $new_plan_sql);
        $new_plan = mysqli_fetch_assoc($new_plan_result);
        
        // Expire current subscription
        $expire_sql = "UPDATE user_bot_subscriptions SET status = 'expired', updated_at = NOW() 
                      WHERE user_id = '$user_id' AND status = 'active'";
        if (!mysqli_query($conn, $expire_sql)) {
            throw new Exception('Failed to update existing subscription');
        }
        
        // Record subscription change
        $change_type = ($new_plan['sort_order'] > $current_plan['sort_order']) ? 'upgrade' : 'downgrade';
    }
    
    // 5. Calculate subscription dates
    $subscription_start = date('Y-m-d');
    $subscription_end = date('Y-m-d', strtotime('+30 days'));
    
    // 6. Insert new subscription
    $insert_sql = "INSERT INTO user_bot_subscriptions 
                  (user_id, bot_plan_id, trading_balance, subscription_start, subscription_end, 
                   status, auto_renew, created_at, updated_at) 
                  VALUES ('$user_id', '$bot_plan_id', '$trading_balance', '$subscription_start', 
                          '$subscription_end', 'active', 1, NOW(), NOW())";
    
    if (!mysqli_query($conn, $insert_sql)) {
        throw new Exception('Failed to create subscription: ' . mysqli_error($conn));
    }
    
    $subscription_id = mysqli_insert_id($conn);
    
    // 7. Update user balances
    $new_available_balance = $available_balance - $subscription_fee - $trading_balance;
    $new_fund_balance = $current_fund_balance + $trading_balance;
    
    $update_user_sql = "UPDATE users SET 
                       available_balance = '$new_available_balance',
                       fund_balance = '$new_fund_balance'
                       WHERE id = '$user_id'";
    
    if (!mysqli_query($conn, $update_user_sql)) {
        throw new Exception('Failed to update user balance: ' . mysqli_error($conn));
    }
    
    // 8. Record subscription fee transaction
    $fee_description = "Monthly subscription fee for {$bot_plan['plan_name']}";
    $fee_sql = "INSERT INTO transactions 
               (user_id, type, amount, description, status, currency, created_at) 
               VALUES ('$user_id', 'debit', '$subscription_fee', '$fee_description', 
                       'completed', 'USDT', NOW())";
    
    if (!mysqli_query($conn, $fee_sql)) {
        throw new Exception('Failed to record subscription fee: ' . mysqli_error($conn));
    }
    
    // 9. Record fund transfer to trading balance
    $transfer_description = "Funds transferred to trading balance for {$bot_plan['plan_name']}";
    $transfer_sql = "INSERT INTO transactions 
                    (user_id, type, amount, description, status, currency, created_at) 
                    VALUES ('$user_id', 'transfer', '$trading_balance', '$transfer_description', 
                            'completed', 'USDT', NOW())";
    
    if (!mysqli_query($conn, $transfer_sql)) {
        throw new Exception('Failed to record fund transfer: ' . mysqli_error($conn));
    }
    
    // 10. Record bot transaction for subscription
    $bot_transaction_sql = "INSERT INTO bot_transactions 
                           (subscription_id, transaction_date, transaction_type, amount, description, created_at) 
                           VALUES ('$subscription_id', '$subscription_start', 'fee', '$subscription_fee', 
                                   'Monthly subscription fee', NOW())";
    
    if (!mysqli_query($conn, $bot_transaction_sql)) {
        throw new Exception('Failed to record bot transaction: ' . mysqli_error($conn));
    }
    
    // 11. Create initial profit tracking record
    $profit_sql = "UPDATE user_bot_subscriptions SET 
                  total_profit = 0.00,
                  total_trades = 0,
                  success_rate = 0.00,
                  updated_at = NOW()
                  WHERE id = '$subscription_id'";
    
    if (!mysqli_query($conn, $profit_sql)) {
        throw new Exception('Failed to initialize profit tracking: ' . mysqli_error($conn));
    }
    
    // Commit transaction
    mysqli_commit($conn);
    
    // 12. Send confirmation email (optional)
    sendSubscriptionConfirmation($user_id, $bot_plan, $subscription_id, $subscription_fee, $trading_balance);
    
    // 13. Set success message and redirect
    $change_message = isset($change_type) ? 
        "You have successfully {$change_type}d to " : 
        "You have successfully subscribed to ";
    
    $_SESSION['success'] = $change_message . $bot_plan['plan_name'] . '! ' .
                          "Subscription fee: $" . number_format($subscription_fee, 2) . ". " .
                          "Trading balance: $" . number_format($trading_balance, 2) . ". " .
                          "Your bot will start trading immediately.";
    
    // 14. Log subscription activity
    logSubscriptionActivity($user_id, $bot_plan_id, $subscription_id, $subscription_fee, $trading_balance);
    
    header('Location: dashboard.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    mysqli_rollback($conn);
    
    $_SESSION['error'] = $e->getMessage();
    header('Location: trading-bots.php');
    exit();
}

// Function to send subscription confirmation email
function sendSubscriptionConfirmation($user_id, $bot_plan, $subscription_id, $subscription_fee, $trading_balance) {
    global $conn;
    
    // Get user email
    $user_sql = "SELECT email, first_name FROM users WHERE id = '$user_id'";
    $user_result = mysqli_query($conn, $user_sql);
    $user = mysqli_fetch_assoc($user_result);
    
    if (!$user) return;
    
    $to = $user['email'];
    $subject = "Bot Subscription Confirmation - " . $bot_plan['plan_name'];
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px 10px 0 0; }
            .content { background: #f9f9f9; padding: 20px; }
            .details { background: white; border: 1px solid #ddd; border-radius: 5px; padding: 15px; margin: 15px 0; }
            .footer { background: #f1f1f1; padding: 15px; text-align: center; font-size: 12px; color: #666; }
            .highlight { color: #667eea; font-weight: bold; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Bot Subscription Activated!</h2>
            </div>
            <div class='content'>
                <p>Hello " . htmlspecialchars($user['first_name']) . ",</p>
                <p>Your subscription to <strong>" . htmlspecialchars($bot_plan['plan_name']) . "</strong> has been successfully activated.</p>
                
                <div class='details'>
                    <h3>Subscription Details:</h3>
                    <p><strong>Subscription ID:</strong> #$subscription_id</p>
                    <p><strong>Bot Plan:</strong> " . htmlspecialchars($bot_plan['plan_name']) . "</p>
                    <p><strong>Subscription Fee:</strong> $" . number_format($subscription_fee, 2) . " (monthly)</p>
                    <p><strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "</p>
                    <p><strong>Daily ROI:</strong> " . $bot_plan['daily_roi_percentage'] . "%</p>
                    <p><strong>Subscription Start:</strong> " . date('F d, Y') . "</p>
                    <p><strong>Subscription End:</strong> " . date('F d, Y', strtotime('+30 days')) . "</p>
                    <p><strong>Auto-renew:</strong> Enabled</p>
                </div>
                
                <p>Your trading bot will start analyzing the markets and executing trades immediately.</p>
                <p>You can monitor your bot's performance from your dashboard.</p>
                
                <p><strong>Important Notes:</strong></p>
                <ul>
                    <li>Profits are credited to your available balance daily</li>
                    <li>You can withdraw profits at any time</li>
                    <li>The subscription will auto-renew in 30 days</li>
                    <li>You can cancel auto-renewal from your dashboard</li>
                    <li>Contact support if you have any questions</li>
                </ul>
            </div>
            <div class='footer'>
                <p>This is an automated message. Please do not reply to this email.</p>
                <p>If you have any questions, contact our support team.</p>
                <p>&copy; " . date('Y') . " Your Trading Platform. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: Trading Platform <noreply@yourplatform.com>" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    // Send email (in production, use a proper email library)
    @mail($to, $subject, $message, $headers);
}

// Function to log subscription activity
function logSubscriptionActivity($user_id, $bot_plan_id, $subscription_id, $fee, $trading_balance) {
    global $conn;
    
    $log_sql = "INSERT INTO activity_logs 
               (user_id, action_type, description, ip_address, user_agent, created_at) 
               VALUES ('$user_id', 'bot_subscription', 
                       'Subscribed to bot plan #$bot_plan_id (Subscription #$subscription_id) - Fee: $$fee, Trading Balance: $$trading_balance',
                       '" . $_SERVER['REMOTE_ADDR'] . "',
                       '" . mysqli_real_escape_string($conn, $_SERVER['HTTP_USER_AGENT']) . "',
                       NOW())";
    
    @mysqli_query($conn, $log_sql);
}

// Close database connection
mysqli_close($conn);
?>