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

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

// Get admin info from session
$admin_id = $_SESSION['admin_id'] ?: $_SESSION['user_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: $_SESSION['first_name'] ?: 'System Administrator';
$admin_role = $_SESSION['admin_role'] ?: 'admin';
$ip_address = $_SERVER['REMOTE_ADDR'] ?: '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?: '';

// Get admin email for notification
$adminQuery = mysqli_query($conn, "SELECT email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Get user details before update
$user_sql = "SELECT username, email, first_name, last_name, phone, country, created_at, last_login, referral_balance FROM users WHERE id = $id";
$user_result = mysqli_query($conn, $user_sql);
$user_data = mysqli_fetch_assoc($user_result);
$username = $user_data['username'] ?: 'Unknown';
$email = $user_data['email'] ?: 'Unknown';
$first_name = $user_data['first_name'] ?: 'Unknown';
$last_name = $user_data['last_name'] ?: '';
$phone = $user_data['phone'] ?: 'Not provided';
$country = $user_data['country'] ?: 'Not specified';
$account_age = round((time() - strtotime($user_data['created_at'])) / (60 * 60 * 24), 1);
$last_login = $user_data['last_login'] ? date('F j, Y g:i A', strtotime($user_data['last_login'])) : 'Never logged in';
$referral_balance = $user_data['referral_balance'] ?? 0;

// Get user's active bots count
$bot_sql = "SELECT COUNT(*) as bot_count FROM user_bot_subscriptions WHERE user_id = $id AND status = 'active'";
$bot_result = mysqli_query($conn, $bot_sql);
$bot_data = mysqli_fetch_assoc($bot_result);
$active_bots = $bot_data['bot_count'] ?? 0;

// Get user's total deposits
$deposit_sql = "SELECT SUM(amount) as total_deposits FROM transactions WHERE user_id = $id AND type = 'deposit' AND status = 'completed'";
$deposit_result = mysqli_query($conn, $deposit_sql);
$deposit_data = mysqli_fetch_assoc($deposit_result);
$total_deposits = $deposit_data['total_deposits'] ?? 0;

// Update user status to verified
$sql = "UPDATE users SET status = 'verified', verification_date = NOW() WHERE id = $id AND status = 'pending'";

if (mysqli_query($conn, $sql)) {
    // Log admin activity
    $log_sql = "INSERT INTO admin_activities (admin_id, admin_name, admin_role, action, description, module, ip_address, user_agent, affected_id, affected_table) 
                VALUES ('$admin_id', '$admin_name', '$admin_role', 'User Verified', 
                'Verified user $username ($email)', 
                'Users', '$ip_address', '$user_agent', $id, 'users')";
    mysqli_query($conn, $log_sql);
    
    // Also log in activity_logs table
    $log_sql2 = "INSERT INTO activity_logs (user_id, action, description, ip_address, user_agent, created_at) 
                VALUES ($id, 'User verified', 'User manually verified by admin $admin_name', '$ip_address', '$user_agent', NOW())";
    mysqli_query($conn, $log_sql2);
    
    // NOTIFICATION: User Verified (USER)
    $mail_subject = "Account Verified Successfully!";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Congratulations <span class='user-name'>" . $first_name . "</span>! 🎉</h2>
                        
                        <p class='message'>
                            Great news! Your " . $sitename . " account has been <strong>successfully verified</strong> by our admin team!
                        </p>

                        <!-- Verification Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Account Status:</strong> <span style='color: #28a745; font-weight: bold;'>VERIFIED ✅</span><br>
                                <strong>Verification Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Verified By:</strong> " . $sitename . " Admin Team<br>
                                <strong>Account Username:</strong> " . $username . "<br>
                                <strong>Full Access Granted:</strong> All platform features now available
                            </div>
                        </div>

                        <!-- New Features Unlocked -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🚀 Features Now Available</h3>
                            <p style='color: #6c757d;'>With your verified account, you can now:</p>
                            <ul style='color: #6c757d;'>
                                <li>Subscribe to AI trading bots</li>
                                <li>Make deposits and withdrawals</li>
                                <li>Access advanced trading tools</li>
                                <li>Join our referral program</li>
                                <li>Receive priority support</li>
                                <li>Participate in platform promotions</li>
                                <li>Access full account analytics</li>
                            </ul>
                        </div>

                        <!-- Quick Start Guide -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>💡 Quick Start Guide</h4>
                            <p style='color: #0056b3;'>
                                <strong>1. Fund Your Account:</strong> <a href='" . $myUrl . "/deposit.php' style='color: #0056b3;'>Make your first deposit</a><br>
                                <strong>2. Choose a Bot:</strong> <a href='" . $myUrl . "/trading_bots.php' style='color: #0056b3;'>Select AI trading bot</a><br>
                                <strong>3. Start Trading:</strong> Bot will begin trading automatically<br>
                                <strong>4. Monitor:</strong> Track performance in real-time dashboard
                            </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;'>
                                Explore Trading Bots
                            </a>
                            <a href='" . $myUrl . "/deposit.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Make First Deposit
                            </a>
                        </div>

                        <!-- Security Reminder -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Account Security</h4>
                            <p style='color: #856404;'>
                                <strong>Keep your account secure:</strong><br>
                                • Never share your login credentials<br>
                                • Enable two-factor authentication<br>
                                • Use strong, unique passwords<br>
                                • Monitor account activity regularly
                            </p>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help getting started?</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: User Verified (ADMIN)
    $admin_mail_subject = "User Account Verified - " . $username;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>User Account Verified</h2>
                            
                            <p class='message'>
                                A user account has been manually verified by an administrator.
                            </p>

                            <!-- Verification Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>User ID:</strong> " . $id . "<br>
                                    <strong>Username:</strong> " . $username . "<br>
                                    <strong>Full Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>Email:</strong> " . $email . "<br>
                                    <strong>Phone:</strong> " . $phone . "<br>
                                    <strong>Country:</strong> " . $country . "<br>
                                    <strong>Verified By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                    <strong>Verification Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>IP Address:</strong> " . $ip_address . "<br>
                                    <strong>Previous Status:</strong> Pending<br>
                                    <strong>New Status:</strong> <span style='color: #28a745; font-weight: bold;'>Verified</span>
                                </div>
                            </div>

                            <!-- User Account Statistics -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>📊 Account Statistics</h4>
                                <p style='color: #495057;'>
                                    <strong>Account Age:</strong> " . $account_age . " days<br>
                                    <strong>Last Login:</strong> " . $last_login . "<br>
                                    <strong>Active Trading Bots:</strong> " . $active_bots . "<br>
                                    <strong>Total Deposits:</strong> $" . number_format($total_deposits, 2) . "<br>
                                    <strong>Referral Balance:</strong> $" . number_format($referral_balance, 2) . "<br>
                                    <strong>Verification Method:</strong> Manual Admin Approval
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/users.php?id=" . $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 User Profile
                                </a>
                                <a href='" . $myUrl . "/admin/user-transactions.php?id=" . $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 Transactions
                                </a>
                            </div>

                            <!-- Verification Notes -->
                            <div class='support-section'>
                                <p class='support-text'>Verification completed successfully.</p>
                                <p style='color: #6c757d; font-size: 12px;'>
                                    User has been notified via email about their account verification.
                                </p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    echo json_encode(array('success' => true, 'message' => 'User verified successfully'));
} else {
    echo json_encode(array('success' => false, 'message' => 'Failed to verify user'));
}
?>