<?php
session_start();
include('includes/head.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';

if ($submitted_pin !== $admin_pin) {
    header('Location: bot_subscriptions.php?error=Invalid PIN. Subscription not added.');
    exit();
}

// Get admin details for notification
$admin_id = $_SESSION['user_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'System Administrator';

// Get form data
$user_id = intval($_POST['user_id']);
$bot_plan_id = intval($_POST['bot_plan_id']);
$trading_balance = floatval($_POST['trading_balance']);
$duration_days = intval($_POST['duration_days']);
$status = mysqli_real_escape_string($conn, $_POST['status']);
$auto_renew = intval($_POST['auto_renew']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);

// Validate minimum balance
if ($trading_balance < 100) {
    header('Location: bot_subscriptions.php?error=Trading balance must be at least $100.');
    exit();
}

// Get bot plan details
$plan_sql = "SELECT plan_name, min_trading_balance, max_trading_balance, daily_roi_percentage, trading_accuracy FROM trading_bot_plans WHERE id = $bot_plan_id";
$plan_result = mysqli_query($conn, $plan_sql);
$plan = mysqli_fetch_assoc($plan_result);

if (!$plan) {
    header('Location: bot_subscriptions.php?error=Invalid bot plan selected.');
    exit();
}

// Validate balance against plan limits
if ($trading_balance < $plan['min_trading_balance']) {
    header('Location: bot_subscriptions.php?error=Trading balance below minimum for this plan.');
    exit();
}

if ($plan['max_trading_balance'] && $trading_balance > $plan['max_trading_balance']) {
    header('Location: bot_subscriptions.php?error=Trading balance above maximum for this plan.');
    exit();
}

// Get user details
$user_sql = "SELECT username, email, first_name, last_name FROM users WHERE id = $user_id";
$user_result = mysqli_query($conn, $user_sql);
$user = mysqli_fetch_assoc($user_result);

if (!$user) {
    header('Location: bot_subscriptions.php?error=Invalid user selected.');
    exit();
}

// Calculate dates
$start_date = date('Y-m-d');
$end_date = date('Y-m-d', strtotime("+$duration_days days"));

// Get user's current balance before subscription
$balance_sql = "SELECT fund_balance, available_balance FROM users WHERE id = $user_id";
$balance_result = mysqli_query($conn, $balance_sql);
$balance_data = mysqli_fetch_assoc($balance_result);
$old_fund_balance = $balance_data['fund_balance'] ?? 0;
$old_available_balance = $balance_data['available_balance'] ?? 0;

// Insert subscription
$sql = "INSERT INTO user_bot_subscriptions (user_id, bot_plan_id, trading_balance, subscription_start, subscription_end, auto_renew, status, status_note, created_at, updated_at) 
        VALUES ($user_id, $bot_plan_id, $trading_balance, '$start_date', '$end_date', $auto_renew, '$status', '$notes', NOW(), NOW())";

if (mysqli_query($conn, $sql)) {
    $subscription_id = mysqli_insert_id($conn);
    
    // Update user's fund balance (deduct trading balance)
    $new_fund_balance = $old_fund_balance - $trading_balance;
    if ($new_fund_balance < 0) $new_fund_balance = 0;
    
    $update_balance_sql = "UPDATE users SET fund_balance = '$new_fund_balance' WHERE id = $user_id";
    mysqli_query($conn, $update_balance_sql);
    
    // Log activity
    logAdminActivity(
        'Bot Subscription Added',
        "Added new subscription for user {$user['username']} ({$user['email']}). Plan ID: $bot_plan_id, Balance: $$trading_balance, Duration: $duration_days days",
        'Trading Bots',
        $subscription_id,
        'user_bot_subscriptions'
    );
    
    // Add initial transaction record
    $txn_sql = "INSERT INTO bot_transactions (subscription_id, transaction_date, transaction_type, amount, description, created_at) 
                VALUES ($subscription_id, CURDATE(), 'balance_lock', $trading_balance, 'Subscription created manually by admin. Notes: $notes', NOW())";
    mysqli_query($conn, $txn_sql);
    
    // Record transaction for user
    $user_txn_sql = "INSERT INTO transactions (user_id, type, amount, description, status, currency, created_at) 
                    VALUES ($user_id, 'debit', $trading_balance, 'Bot subscription created by admin for $trading_balance trading balance', 'completed', 'USDT', NOW())";
    mysqli_query($conn, $user_txn_sql);
    
    // NOTIFICATION: Admin Created Bot Subscription (USER)
    $mail_subject = "New Trading Bot Subscription Created";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $user['first_name'] . "</span>,</h2>
                        
                        <p class='message'>
                            Our admin team has created a new trading bot subscription for your account.
                        </p>

                        <!-- Subscription Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Subscription ID:</strong> SUB-" . $subscription_id . "<br>
                                <strong>Bot Plan:</strong> " . $plan['plan_name'] . "<br>
                                <strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                <strong>Daily ROI:</strong> " . $plan['daily_roi_percentage'] . "%<br>
                                <strong>Trading Accuracy:</strong> " . $plan['trading_accuracy'] . "%<br>
                                <strong>Subscription Period:</strong> " . $duration_days . " days (" . date('F j, Y', strtotime($start_date)) . " to " . date('F j, Y', strtotime($end_date)) . ")<br>
                                <strong>Status:</strong> <span style='color: " . ($status == 'active' ? '#28a745' : '#ffc107') . "; font-weight: bold;'>" . strtoupper($status) . "</span><br>
                                <strong>Auto Renewal:</strong> " . ($auto_renew == 1 ? 'Enabled' : 'Disabled') . "<br>
                                <strong>Created By:</strong> " . $admin_name . " (Admin)<br>
                                <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "
                            </div>
                        </div>

                        <!-- Balance Update -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #495057;'>💰 Balance Update</h4>
                            <p style='color: #495057;'>
                                <strong>Trading Balance Locked:</strong> $" . number_format($trading_balance, 2) . "<br>
                                <strong>Previous Fund Balance:</strong> $" . number_format($old_fund_balance, 2) . "<br>
                                <strong>New Fund Balance:</strong> $" . number_format($new_fund_balance, 2) . "<br>
                                <strong>Available Balance:</strong> $" . number_format($old_available_balance, 2) . " (unchanged)
                            </p>
                        </div>

                        <!-- What Happens Next -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>" . ($status == 'active' ? "🤖 Your Bot is Ready!" : "⚠️ Subscription Status") . "</h3>
                            <p style='color: #6c757d;'>
                                " . ($status == 'active' ? 
                                "Your bot will start trading immediately. Expect your first profits within 24 hours." : 
                                "Your subscription is currently <strong>" . $status . "</strong>. It will become active once approved.") . "
                            </p>
                            " . ($status == 'active' ? "
                            <ul style='color: #6c757d;'>
                                <li>AI will analyze market data in real-time</li>
                                <li>Trades executed based on AI signals</li>
                                <li>Profits added to available balance daily</li>
                                <li>Monitor performance in your dashboard</li>
                            </ul>" : "") . "
                        </div>

                        <!-- Admin Notes -->
                        " . (!empty($notes) ? "
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📝 Admin Notes</h4>
                            <p style='color: #0056b3;'><em>" . htmlspecialchars($notes) . "</em></p>
                        </div>" : "") . "

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/trading_bots.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Subscriptions
                            </a>
                            " . ($status != 'active' ? "
                            <a href='" . $myUrl . "/support.php?category=subscription' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Contact Support
                            </a>" : "") . "
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Questions about your new subscription?</p>
                            <a href='" . $myUrl . "/support.php' class='support-link'>Contact Our Support Team</a>
                        </div>
                    </div>";

    // Send user notification
    require_once("../proccess/mail_sender.php");

    // NOTIFICATION: Manual Bot Subscription Created (ADMIN)
    $admin_mail_subject = "Manual Bot Subscription Created - SUB-" . $subscription_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Manual Bot Subscription Created</h2>
                            
                            <p class='message'>
                                An administrator has manually created a new bot subscription for a user.
                            </p>

                            <!-- Subscription Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Subscription ID:</strong> SUB-" . $subscription_id . "<br>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $user['first_name'] . " " . $user['last_name'] . "<br>
                                    <strong>User Email:</strong> " . $user['email'] . "<br>
                                    <strong>Bot Plan:</strong> " . $plan['plan_name'] . "<br>
                                    <strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                    <strong>Duration:</strong> " . $duration_days . " days<br>
                                    <strong>Status:</strong> " . $status . "<br>
                                    <strong>Auto Renewal:</strong> " . ($auto_renew == 1 ? 'Yes' : 'No') . "<br>
                                    <strong>Created By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                    <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "
                                </div>
                            </div>

                            <!-- Financial Impact -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>💰 Financial Impact</h4>
                                <p style='color: #495057;'>
                                    <strong>User's Fund Balance:</strong><br>
                                    • Before: $" . number_format($old_fund_balance, 2) . "<br>
                                    • After: $" . number_format($new_fund_balance, 2) . "<br>
                                    • Change: -$" . number_format($trading_balance, 2) . "<br><br>
                                    <strong>Trading Balance Locked:</strong> $" . number_format($trading_balance, 2) . "
                                </p>
                            </div>

                            <!-- Admin Notes -->
                            " . (!empty($notes) ? "
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>📝 Admin Notes</h4>
                                <p style='color: #856404;'>" . htmlspecialchars($notes) . "</p>
                            </div>" : "") . "

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/bot_subscriptions.php?id=" . $subscription_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View Subscription
                                </a>
                                <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View User Profile
                                </a>
                            </div>

                            <!-- System Information -->
                            <div class='support-section'>
                                <p class='support-text'>System Information:</p>
                                <p style='color: #6c757d; font-size: 12px;'>
                                    <strong>Method:</strong> Manual Admin Creation<br>
                                    <strong>Transaction Recorded:</strong> Yes<br>
                                    <strong>User Notified:</strong> Yes<br>
                                    <strong>Activity Logged:</strong> Yes
                                </p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    header('Location: bot_subscriptions.php?success=Subscription added successfully!');
} else {
    header('Location: bot_subscriptions.php?error=Failed to add subscription.');
}
exit();
?>