<?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: users.php?error=Invalid PIN. User not added.');
    exit();
}

// Get form data
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$confirm_password = mysqli_real_escape_string($conn, $_POST['confirm_password']);
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$id_number = mysqli_real_escape_string($conn, $_POST['id_number']);
$initial_balance = floatval($_POST['initial_balance']);
$status = mysqli_real_escape_string($conn, $_POST['status']);

// Validate passwords
if ($password !== $confirm_password) {
    header('Location: users.php?error=Passwords do not match.');
    exit();
}

// Check if username or email already exists
$check_sql = "SELECT id FROM users WHERE username = '$username' OR email = '$email'";
$check_result = mysqli_query($conn, $check_sql);
if (mysqli_num_rows($check_result) > 0) {
    header('Location: users.php?error=Username or email already exists.');
    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';
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Hash password (using md5 for compatibility with your existing users table)
$hashed_password = md5($password);

// Insert user
$sql = "INSERT INTO users (username, email, password, first_name, last_name, id_number, phone, date_of_birth, address, city, province, postal_code, fund_balance, available_balance, status, registration_date) 
        VALUES ('$username', '$email', '$hashed_password', '$first_name', '$last_name', '$id_number', '$phone', '1990-01-01', 'Not provided', 'Not provided', 'Not provided', '0000', $initial_balance, $initial_balance, '$status', NOW())";

if (mysqli_query($conn, $sql)) {
    $user_id = mysqli_insert_id($conn);
    
    // Create wallet for the user
    $wallet_sql = "INSERT INTO wallets (user_id, balance, currency, created_at) 
                   VALUES ('$user_id', '$initial_balance', 'USDT', NOW())";
    mysqli_query($conn, $wallet_sql);
    
    // Log activity
    logAdminActivity(
        'User Added',
        "Added new user: $username ($email) with status: $status",
        'Users',
        $user_id,
        'users'
    );
    
    // NOTIFICATION: New User Created by Admin (USER)
    $mail_subject = "Welcome to " . $sitename . " - Your Account Has Been Created";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Welcome to " . $sitename . ", <span class='user-name'>" . $first_name . "</span>! 🎉</h2>
                        
                        <p class='message'>
                            Your trading account has been created by our admin team and is ready for you to start trading!
                        </p>

                        <!-- Account Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Account Created By:</strong> " . $sitename . " Admin Team<br>
                                <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Username:</strong> " . $username . "<br>
                                <strong>Account Status:</strong> <span style='color: " . ($status == 'verified' ? '#28a745' : '#ffc107') . "; font-weight: bold;'>" . ucfirst($status) . "</span><br>
                                <strong>Initial Balance:</strong> $" . number_format($initial_balance, 2) . "<br>
                                <strong>Account Type:</strong> Admin-Created Account
                            </div>
                        </div>

                        <!-- Login Instructions -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>🔑 Login Credentials</h4>
                            <p style='color: #0056b3;'>
                                <strong>Login URL:</strong> <a href='" . $myUrl . "/login.php' style='color: #0056b3;'>" . $myUrl . "/login.php</a><br>
                                <strong>Username:</strong> " . $username . "<br>
                                <strong>Email:</strong> " . $email . "<br>
                                <strong>Password:</strong> [The password you provided to admin]<br>
                                <strong>Security Tip:</strong> Change your password after first login
                            </p>
                        </div>

                        <!-- Next Steps -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🚀 Getting Started</h3>
                            <p style='color: #6c757d;'>Here's how to begin your trading journey:</p>
                            <ol style='color: #6c757d;'>
                                <li><strong>Login</strong> to your account using credentials above</li>
                                <li><strong>Complete Profile</strong> - Add missing information</li>
                                <li><strong>Explore Bots</strong> - Check available trading bots</li>
                                <li><strong>Start Trading</strong> - Subscribe to an AI trading bot</li>
                                <li><strong>Monitor</strong> - Track your profits in real-time</li>
                            </ol>
                        </div>

                        <!-- Platform Features -->
                        <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #155724;'>✨ Platform Features</h4>
                            <p style='color: #155724;'>
                                • <strong>AI Trading Bots</strong> - Automated cryptocurrency trading<br>
                                • <strong>Real-time Analytics</strong> - Track performance dashboard<br>
                                • <strong>Secure Wallet</strong> - Multi-layer security protection<br>
                                • <strong>Referral Program</strong> - Earn from referring friends<br>
                                • <strong>24/7 Support</strong> - Dedicated customer assistance
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/login.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;'>
                                Login to Your Account
                            </a>
                            <a href='" . $myUrl . "/trading_bots.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;'>
                                View Trading Bots
                            </a>
                        </div>

                        <!-- Security Reminder -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Important Security Notice</h4>
                            <p style='color: #856404;'>
                                <strong>" . $sitename . " staff will NEVER ask for your password.</strong><br>
                                • Always login through official website only<br>
                                • Enable two-factor authentication for extra security<br>
                                • Never share your login credentials<br>
                                • Contact support if you notice suspicious activity
                            </p>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need assistance with your new account?</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 Created by Admin (ADMIN)
    $admin_mail_subject = "New User Created by Admin - " . $username;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>New User Created by Admin</h2>
                            
                            <p class='message'>
                                A new user account has been created manually by an administrator.
                            </p>

                            <!-- User Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>Username:</strong> " . $username . "<br>
                                    <strong>Email:</strong> " . $email . "<br>
                                    <strong>Full Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>Phone:</strong> " . $phone . "<br>
                                    <strong>ID Number:</strong> " . $id_number . "<br>
                                    <strong>Initial Balance:</strong> $" . number_format($initial_balance, 2) . "<br>
                                    <strong>Account Status:</strong> <span style='color: " . ($status == 'verified' ? '#28a745' : '#ffc107') . "; font-weight: bold;'>" . ucfirst($status) . "</span><br>
                                    <strong>Created By:</strong> " . $admin_name . " (Admin ID: " . $admin_id . ")<br>
                                    <strong>Creation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Creation Method:</strong> Manual Admin Creation<br>
                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                </div>
                            </div>

                            <!-- Account Setup -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>⚙️ Account Setup</h4>
                                <p style='color: #495057;'>
                                    <strong>Wallet Created:</strong> Yes ($" . number_format($initial_balance, 2) . " USDT)<br>
                                    <strong>Password Method:</strong> MD5 Hash<br>
                                    <strong>Profile Completion:</strong> 40% (basic info only)<br>
                                    <strong>Verification Needed:</strong> " . ($status == 'verified' ? 'No' : 'Yes') . "<br>
                                    <strong>Welcome Email:</strong> Sent to user<br>
                                    <strong>Admin Notes:</strong> Manually created account
                                </p>
                            </div>

                            <!-- User Access Information -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>🔐 User Access Information</h3>
                                <p style='color: #6c757d;'>
                                    The user has been provided with login credentials via email.<br>
                                    Password has been securely hashed using MD5 algorithm.
                                </p>
                            </div>

                            <!-- Recommended Next Steps -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>📋 Recommended Admin Actions</h4>
                                <ul style='color: #0c5460;'>
                                    <li>Review user profile for completeness</li>
                                    <li>Monitor initial account activity</li>
                                    <li>Verify documents if required</li>
                                    <li>Check if user needs onboarding assistance</li>
                                    <li>Follow up in 24-48 hours</li>
                                </ul>
                            </div>

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

                            <!-- System Information -->
                            <div class='support-section'>
                                <p class='support-text'>System Information:</p>
                                <p style='color: #6c757d; font-size: 12px;'>
                                    <strong>Database Table:</strong> users<br>
                                    <strong>Record ID:</strong> " . $user_id . "<br>
                                    <strong>Creation Method:</strong> Manual Admin Panel<br>
                                    <strong>Activity Logged:</strong> Yes (Admin Activities)<br>
                                    <strong>Notifications Sent:</strong> User & Admin
                                </p>
                            </div>
                        </div>";

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