<?php
session_start();
include "connection.php";






function generateRandomString($length = 12) {
    return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}
$trx_id = generateRandomString();

function hideEmail($email) {
           // Split the email into username and domain parts
           list($username, $domain) = explode('@', $email);
       
           // Keep the first character and replace the rest of the username with asterisks
           $hiddenUsername = substr($username, 0, 1) . str_repeat('*', strlen($username) - 1);
       
           // Combine the hidden username with the domain
           return $hiddenUsername . '@' . $domain;
       }



if (isset($_GET['login'])) {

    // Get the username and password (with fallback if they are not set)
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    // Basic validation (you can add more checks here for empty inputs)
    if (empty($username) || empty($password)) {
        echo json_encode(['success' => false, 'message' => 'Please enter both username and password.']);
        exit();
    }

    // Prepare and execute the query to check if the username exists
    $query = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1");
    $query->bind_param("ss", $username, $username); // "s" denotes the type (string) of the parameter
    $query->execute();
    $result = $query->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
          if (password_verify($password, $user['password'])) {
            // Successful login - Start session and store user data
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $to = $user['email'];
            $firstname = $user['firstname'];
            $email = $user['email'];
            $email_verification = $user['email_verification'];
            
            
            if($email_verification == 'Pending'){
              $_SESSION['email'] = $user['email'];
                echo json_encode([
                            'verificationerror' => true,
                            'message' => 'Your account is not verified yet! Enter the OTP sent to your email ('.hideEmail($to).').',
                        ]);
            }else{
            
          

            // Get user details for activity logging
            $user_id = $_SESSION['user_id'];
            $ip_address = $_SERVER['REMOTE_ADDR'];

            // Use cURL to get location information from IP
            $ch = curl_init('http://ip-api.com/json/' . $ip_address);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            $location_data = json_decode($response, true);

            // Fallback location if request failed
            if ($location_data['status'] == 'fail') {
                $country = 'Unknown';
                $region = 'Unknown';
                $city = 'Unknown';
                $latitude = 'Unknown';
                $longitude = 'Unknown';
            } else {
                $country = $location_data['country'];
                $region = $location_data['regionName'];
                $city = $location_data['city'];
                $latitude = $location_data['lat'];
                $longitude = $location_data['lon'];
            }

            // Get current time for activity log
            $time = date('Y-m-d H:i:s');

            // Function to detect browser and OS
            function getBrowserAndOS($userAgent) {
                $browser = "Unknown Browser";
                $os = "Unknown OS";

                // Browser detection
                if (preg_match("/MSIE/i", $userAgent) && !preg_match("/Opera/i", $userAgent)) {
                    $browser = "Internet Explorer";
                } elseif (preg_match("/Trident/i", $userAgent)) {
                    $browser = "Internet Explorer (Edge)";
                } elseif (preg_match("/Firefox/i", $userAgent)) {
                    $browser = "Mozilla Firefox";
                } elseif (preg_match("/Chrome/i", $userAgent)) {
                    $browser = "Google Chrome";
                } elseif (preg_match("/Safari/i", $userAgent)) {
                    $browser = "Safari";
                } elseif (preg_match("/Opera/i", $userAgent)) {
                    $browser = "Opera";
                } elseif (preg_match("/Edge/i", $userAgent)) {
                    $browser = "Microsoft Edge";
                }

                // OS detection
                if (preg_match("/win/i", $userAgent)) {
                    $os = "Windows";
                } elseif (preg_match("/macintosh|mac os x/i", $userAgent)) {
                    $os = "Mac OS";
                } elseif (preg_match("/linux/i", $userAgent)) {
                    $os = "Linux";
                } elseif (preg_match("/iphone/i", $userAgent)) {
                    $os = "iOS";
                } elseif (preg_match("/android/i", $userAgent)) {
                    $os = "Android";
                } elseif (preg_match("/webos/i", $userAgent)) {
                    $os = "WebOS";
                }

                return ['browser' => $browser, 'os' => $os];
            }

            // Get browser and OS from the user agent
            $userAgent = $_SERVER['HTTP_USER_AGENT'];
            $info = getBrowserAndOS($userAgent);
            $browser = $info['browser'];
            $os = $info['os'];
            $browser_info = $browser . ', ' . $os;

            // Format location
            $location = $city . ', ' . $region . ', ' . $country;

            // Prepare SQL query to insert data into `activities` table
            $sql = "INSERT INTO `activities` (`time`, `ip_address`, `location`, `browser`, `user_id`) 
                    VALUES (?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssssi", $time, $ip_address, $location, $browser_info, $user_id);
            $stmt->execute();
            
            
            
            // Subject of the email
            $subject = "Welcome Back to $sitename";

            $htmlMessage = '
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Login Welcome</title>
                 <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 0;
                        padding: 0;
                        background-color: #f9f9f9;
                        color: #333;
                    }
                    .email-container {
                        max-width: 600px;
                        margin: 0 auto;
                        background-color: #ffffff;
                        border: 1px solid #e0e0e0;
                        border-radius: 5px;
                        overflow: hidden;
                    }
                    .email-header {
                        background-color: #05445E;
                        color: white;
                        text-align: center;
                        padding: 20px;
                        font-size: 16px;
                        font-weight: bold;
                    }
                    .email-logo {
                        display: block;
                        margin: 0 auto 10px;
                        width: 200px
                    }
                    .email-body {
                        padding: 20px;
                        text-align: center;
                    }
                    .email-body h2 {
                        margin: 10px 0;
                        font-size: 24px;
                    }
                    .email-body p {
                        margin: 15px 0;
                        font-size: 16px;
                        line-height: 1.5;
                    }
                    .email-footer {
                        text-align: center;
                        padding: 15px;
                        font-size: 14px;
                        color: #888;
                        border-top: 1px solid #e0e0e0;
                    }
                    .email-footer a {
                        color: #05445E;
                        text-decoration: none;
                    }
                </style>
            </head>
            <body>
                <div class="email-container">
                    <div class="email-header">
                        This is a System Generated Email
                    </div>
                    <div class="email-body">
                        <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo">
                        <h2>Hello ' . $firstname . '</h2>
                        <p>Welcome back to <strong>' . $sitename . '</strong>.</p>
                        <p>We noticed a login to your account from:</p>
                        <ul>
                            <li>IP Address: ' . $ip_address . '</li>
                            <li>Location: ' . $location . '</li>
                            <li>Browser: ' . $browser_info . '</li>
                            <li>Time: ' . $time . '</li>
                        </ul>
                        <p>If this was you, no further action is required.</p>
                        <p>If you didn\'t log in, please secure your account immediately.</p>
                    </div>
                    <div class="email-footer">
                        &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All Rights Reserved.
                    </div>
                </div>
            </body>
            </html>';

             sendmail($email, $firstname, $subject, $htmlMessage);     
    
            echo json_encode(['success' => true, 'message' => 'Login successful', 'redirect_url' => 'dashboard.php']);
                
        }
        
        }else {
            // Incorrect password
            echo json_encode(['success' => false, 'message' => 'Invalid username or password']);
        }
    } else {
        // Username not found
        echo json_encode(['success' => false, 'message' => 'User not found']);
    }

} 


if (isset($_GET['forgot'])) {

    // Get the email from POST request
    $email = $_POST['email'] ?? '';

    if (empty($email)) {
        echo json_encode(['success' => false, 'message' => 'Please enter your registered email.']);
        exit();
    }

    // Look up user by email
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Email not found in our records.']);
        exit();
    }

    $user = $result->fetch_assoc();
    $firstname = $user['firstname'];
    $user_id = $user['id'];
    $token = bin2hex(random_bytes(32)); // Secure token
    $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

    // Save reset token in a `password_resets` table (create if needed)
    $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE token = VALUES(token), expires_at = VALUES(expires_at)");
    $stmt->bind_param("sss", $email, $token, $expires);
    $stmt->execute();

    // Prepare email
    $resetLink = $siteurl . "/app/reset-password?token=" . urlencode($token);
    $subject = "Reset Your Password - $sitename";

    $htmlMessage = '
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Reset Password</title>
        <style>
            body { font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px; }
            .container { background: #fff; border: 1px solid #ddd; padding: 30px; max-width: 600px; margin: auto; }
            .btn { background-color: #05445E; color: #fff; padding: 10px 20px; text-decoration: none; display: inline-block; border-radius: 5px; }
            .footer { font-size: 12px; color: #888; margin-top: 20px; }
        </style>
    </head>
    <body>
        <div class="container">
            <h2>Hello ' . htmlspecialchars($firstname) . ',</h2>
            <p>You recently requested to reset your password on <strong>' . $sitename . '</strong>.</p>
            <p>Click the button below to reset your password:</p>
            <p><a href="' . $resetLink . '" class="btn">Reset Password</a></p>
            <p>If you did not request a password reset, please ignore this email.</p>
            <div class="footer">
                &copy; ' . date('Y') . ' ' . $sitename . '. All rights reserved.
            </div>
        </div>
    </body>
    </html>';

    // Send email
    sendmail($email, $firstname, $subject, $htmlMessage);

    echo json_encode(['success' => true, 'message' => 'A password reset link has been sent to your email.']);
    exit();
}


if (isset($_GET['reset'])) {
    // Collect input
    $token = $_POST['token'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validate input
    if (empty($token) || empty($new_password) || empty($confirm_password)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        exit();
    }

    if ($new_password !== $confirm_password) {
        echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
        exit();
    }

    // Check token validity
    $stmt = $conn->prepare("SELECT * FROM password_resets WHERE token = ? AND expires_at > NOW() LIMIT 1");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid or expired reset token.']);
        exit();
    }

    $reset = $result->fetch_assoc();
    $email = $reset['email'];

    // Fetch user by email
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $user_result = $stmt->get_result();

    if ($user_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'User account not found.']);
        exit();
    }

    $user = $user_result->fetch_assoc();
    $user_id = $user['id'];
    $firstname = $user['firstname'];

    // Hash the new password
    $hashedPassword = password_hash($new_password, PASSWORD_DEFAULT);

    // Update password in users table
    $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $update->bind_param("si", $hashedPassword, $user_id);
    $update->execute();

    // Delete used token
    $delete = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
    $delete->bind_param("s", $email);
    $delete->execute();

    // Send confirmation email
    $subject = "Your Password Has Been Reset - $sitename";
    $htmlMessage = "
    <html>
    <body style='font-family: Arial, sans-serif;'>
        <h2>Hello {$firstname},</h2>
        <p>Your password for <strong>{$sitename}</strong> was successfully changed.</p>
        <p>If you didn’t request this change, please contact support immediately.</p>
        <br>
        <p>Thanks,<br><strong>{$sitename} Team</strong></p>
    </body>
    </html>";

    sendmail($email, $firstname, $subject, $htmlMessage);

    echo json_encode(['success' => true, 'message' => 'Password has been reset successfully. You can now log in.']);
    exit();
}



if (isset($_GET['register'])) {
    // Sanitize and validate inputs
    $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $country = filter_var($_POST['country'], FILTER_SANITIZE_STRING);
    $mobile = filter_var($_POST['mobile'], FILTER_SANITIZE_STRING);
    $password = $_POST['password'];
    $password_confirmation = $_POST['password_confirmation'];

    // Check if passwords match
    if ($password !== $password_confirmation) {
        echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
        exit;
    }

    // Check if email or mobile already exists
    $checkQuery = "SELECT * FROM users WHERE email = ? OR username = ?";
    $stmt = $conn->prepare($checkQuery);
    $stmt->bind_param('ss', $email, $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'Email or Username already exists. Please try again with different details.']);
        exit;
    }

    // Hash the password
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $otpcode = rand(100000, 999999);

    // Insert data into the database
    $query = "INSERT INTO users (username, email, country, mobile, password, otp) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    if ($stmt) {
        $stmt->bind_param('sssssi', $username, $email, $country, $mobile, $hashedPassword, $otpcode);

        if ($stmt->execute()) {
            $_SESSION['email'] = $email;
            
            $subject = 'Email Verification';

            $htmlMessage = '
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Email Verification</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        background-color: #f9f9f9;
                        margin: 0;
                        padding: 0;
                    }
                    .email-container {
                        max-width: 600px;
                        margin: 20px auto;
                        background-color: #ffffff;
                        border: 1px solid #ddd;
                        border-radius: 8px;
                        overflow: hidden;
                    }
                    .email-header {
                        background-color: #015a63;
                        color: #ffffff;
                        padding: 20px;
                        text-align: center;
                        font-size: 18px;
                        font-weight: bold;
                    }
                    .email-logo {
                        margin: 10px 0;
                        width: 200px
                    }
                    .email-body {
                        padding: 20px;
                        text-align: center;
                        color: #333333;
                    }
                    .email-body h1 {
                        font-size: 24px;
                        color: #015a63;
                        margin-bottom: 10px;
                    }
                    .email-body p {
                        font-size: 16px;
                        margin: 10px 0;
                    }
                    .email-code {
                        font-size: 28px;
                        font-weight: bold;
                        color: #015a63;
                        margin: 20px 0;
                    }
                    .email-footer {
                        text-align: center;
                        padding: 15px;
                        background-color: #f5f5f5;
                        font-size: 14px;
                        color: #777777;
                    }
                    .email-footer a {
                        text-decoration: none;
                        color: #015a63;
                        font-weight: bold;
                    }
                </style>
            </head>
            <body>
                <div class="email-container">
                    <div class="email-header">
                        This is a System Generated Email
                    </div>
                    <div class="email-body">
                        <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo">
                        <h2>Hello ' . $username . '</h2>
                        <hr style="border: none; border-top: 1px solid #ddd; width: 50%; margin: 10px auto;">
                        <p>Thanks for joining us.<br>Please use the below code to verify your email address.</p>
                        <div class="email-code">' . $otpcode . '</div>
                    </div>
                    <div class="email-footer">
                        &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All Rights Reserved.
                    </div>
                </div>
            </body>
            </html>';

            $send = sendmail($email, $username, $subject, $htmlMessage);

            if ($send) {
                echo json_encode(['success' => true, 'message' => 'Account created successfully! Please check your email for verification code.']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Account created but failed to send verification email.']);
            }


        }
            
        
        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'Unable to prepare statement.']);
    }
}





// Get the submitted OTP
if (isset($_GET['process-otp'])) {
    $submittedCode = $_POST['code'] ?? '';

    // Sanitize input
    $submittedCode = htmlspecialchars(trim($submittedCode));

    // Validate input
    if (strlen($submittedCode) === 6 && ctype_digit($submittedCode)) {
        $useremail = $_SESSION['email'] ?? null; // Get the logged-in user's ID

        if ($useremail) {
            // Query the database to check the OTP
            $stmt = $conn->prepare("SELECT otp FROM users WHERE email = ?");
            $stmt->bind_param("s", $useremail);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();

                if ($submittedCode == $row['otp']) {
                    // Update the user's status to 'verified'
                    $updateStmt = $conn->prepare("UPDATE users SET email_verification = 'verified' WHERE email = ?");
                    $updateStmt->bind_param("s", $useremail);

                    if ($updateStmt->execute()) {
                        echo json_encode([
                            'success' => true,
                            'message' => 'OTP verified successfully! Your account has been verified.',
                            'redirect_url' => 'user-data', // Redirect URL
                        ]);
                    } else {
                        echo json_encode(['success' => false, 'message' => 'Failed to update user status.']);
                    }

                    $updateStmt->close();
                } else {
                    // Incorrect OTP
                    echo json_encode(['success' => false, 'message' => 'Invalid verification code.']);
                }
            } else {
                // User not found
                echo json_encode(['success' => false, 'message' => 'User not found.']);
            }
            $stmt->close();
        } else {
            // User not logged in
            echo json_encode(['success' => false, 'message' => 'Please log in to verify your code.']);
        }
    } else {
        // Invalid input
        echo json_encode(['success' => false, 'message' => 'The verification code must be 6 digits.']);
    }
}


if(isset($_GET['copytrader'])){
    $user_id = $_SESSION['user_id'] ?? null;
    $trader_id = intval($_POST['trader_id']);

    // Fetch trader info
    $stmt = $conn->prepare("SELECT * FROM traders WHERE id = ?");
    $stmt->bind_param("i", $trader_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Trader not found.']);
        exit;
    }

    $trader = $result->fetch_assoc();
    $capital = $trader['investment_capital'];
    $trader_name = $trader['name'];
    $trader_gain_percent = $trader['gain_percentage'];
    $duration = $trader['avg_trade_time'];

    // Fetch user balance
    $stmtBal = $conn->prepare("SELECT username,email,total_balance FROM users WHERE id = ?");
    $stmtBal->bind_param("i", $user_id);
    $stmtBal->execute();
    $resBal = $stmtBal->get_result();

    if ($resBal->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'User not found']);
        exit;
    }

    $user = $resBal->fetch_assoc();
    $total_balance = $user['total_balance'];
    $username = $user['username'];
    $email = $user['email'];

    if ($total_balance < $capital) {
        echo json_encode(['status' => 'error', 'message' => 'Insufficient balance to copy this trader.']);
        exit;
    }

    // Prevent duplicate copy
    $checkStmt = $conn->prepare("SELECT id FROM copy_trades WHERE user_id = ? AND trader_id = ? AND status = 'Active'");
    $checkStmt->bind_param("ii", $user_id, $trader_id);
    $checkStmt->execute();
    $checkRes = $checkStmt->get_result();

    if ($checkRes->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => 'You are already copying this trader.']);
        exit;
    }

    // Deduct capital
    $stmtUpdate = $conn->prepare("UPDATE users SET total_balance = total_balance - ? WHERE id = ?");
    $stmtUpdate->bind_param("di", $capital, $user_id);
    $stmtUpdate->execute();

    // Calculate profit
    $initial_profit = $capital * 0.10; //10% commission
    $percent_profit = $capital * ($trader_gain_percent / 100);
    $total_profit = $initial_profit + $percent_profit;

    $start_date = "";
    $end_date = "";
    $now = date("Y-m-d H:i:s");

    $status = 'Pending';
    $increase = $trader_gain_percent;

    // Insert into copy_trades
    $stmtInsert = $conn->prepare("INSERT INTO copy_trades 
        (user_id, trader_id, invest_amt, trader_name, increase, duration, total_profit, start_date, end_date, status, date)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmtInsert->bind_param(
        "iidssssssss",
        $user_id,
        $trader_id,
        $capital,
        $trader_name,
        $increase,
        $duration,
        $total_profit,
        $start_date,
        $end_date,
        $status,
        $now
    );

    if ($stmtInsert->execute()) {
        $subject = 'Copy Trading Confirmation';

        $htmlMessage = '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Copy Trading Notification</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f9f9f9;
                    margin: 0;
                    padding: 0;
                }
                .email-container {
                    max-width: 600px;
                    margin: 20px auto;
                    background-color: #ffffff;
                    border: 1px solid #ddd;
                    border-radius: 8px;
                    overflow: hidden;
                }
                .email-header {
                    background-color: #015a63;
                    color: #ffffff;
                    padding: 20px;
                    text-align: center;
                    font-size: 18px;
                    font-weight: bold;
                }
                .email-logo {
                    margin: 10px 0;
                    width: 200px;
                }
                .email-body {
                    padding: 20px;
                    color: #333333;
                }
                .email-body h2 {
                    color: #015a63;
                }
                .email-body p {
                    font-size: 16px;
                    margin: 10px 0;
                }
                .email-summary {
                    background-color: #f1f1f1;
                    padding: 15px;
                    margin: 20px 0;
                    border-radius: 5px;
                    text-align: left;
                }
                .email-summary strong {
                    color: #015a63;
                }
                .email-footer {
                    text-align: center;
                    padding: 15px;
                    background-color: #f5f5f5;
                    font-size: 14px;
                    color: #777777;
                }
                .email-footer a {
                    text-decoration: none;
                    color: #015a63;
                    font-weight: bold;
                }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    Copy Trading Activated
                </div>
                <div class="email-body">
                    <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo">
                    <h2>Hello ' . $username . ',</h2>
                    <p>You have successfully started copying trades from the following trader:</p>
                    <div class="email-summary">
                        <p><strong>Trader Name:</strong> ' . $trader_name . '</p>
                        <p><strong>Investment Amount:</strong> $' . number_format($capital, 2) . ' USD</p>
                        <p><strong>Expected Profit:</strong> $' . number_format($total_profit, 2) . ' USD</p>
                        <p><strong>Trade Duration:</strong> ' . $duration . ' day(s)</p>
                        <p><strong>Status:</strong> Pending</p>
                    </div>
                    <p>We’ll notify you of important updates throughout this trading period.</p>
                </div>
                <div class="email-footer">
                    &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All Rights Reserved.
                </div>
            </div>
        </body>
        </html>';

        $send = sendmail($email, $username, $subject, $htmlMessage);

        echo json_encode(['status' => 'success', 'message' => 'You have successfully started copying this trader.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => "Failed to copy trader: " . $stmtInsert->error]);
    }
}


if(isset($_GET['invest'])){
    $planId = htmlspecialchars(trim($_POST['plan_id']));
	$amount = htmlspecialchars(trim($_POST['amount']));
     $user_id = $_SESSION['user_id'];
	if (empty($planId)) {
        echo json_encode(['status' => 'error', 'message' => 'Select a plan']);
        exit;
	}

	if (empty($amount) || $amount <= 0 ) {
        echo json_encode(['status' => 'error', 'message' => 'Input your investment amount']);
        exit;
	}

    $qq = mysqli_query($conn, "SELECT * FROM package1 WHERE id = '$planId' ");
    if (mysqli_num_rows($qq) > 0) {
        $pln = mysqli_fetch_assoc($qq);
        $plan_name = $pln['pname']; 
        $plan_increase = $pln['increase']; 
        $plan_duration = $pln['duration']; 
        $min_amt = $pln['min_amt']; 
        $max_amt = $pln['max_amt']; 
    }

    // Fetch user balance
    $stmtBal = $conn->prepare("SELECT username,email,total_balance FROM users WHERE id = ?");
    $stmtBal->bind_param("i", $user_id);
    $stmtBal->execute();
    $resBal = $stmtBal->get_result();

    if ($resBal->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'User not found']);
        exit;
    }

    $user = $resBal->fetch_assoc();
    $total_balance = $user['total_balance'];
    $username = $user['username'];
    $email = $user['email'];


	if ($amount < $min_amt) {
        echo json_encode(['status' => 'error', 'message' => "Invest amount should not be lower than $".$min_amt]);
        exit;
	}
    if ($amount > $max_amt) {
        echo json_encode(['status' => 'error', 'message' => "Invest amount should not be higher than $".$max_amt]);
        exit;
	}

    
	if ($amount > $total_balance) {
		$err = "Insufficient fund to purchase this plan";
	}

    $start_date = date('d-m-Y H:i:s');
    $end_date  = date('d-m-Y H:i:s', strtotime(' + '.$plan_duration.' hours'));
    $total_profit = ($plan_increase/100) * $amount;

    $sql = mysqli_query($conn, "INSERT INTO investments (`userId`, `planId`, `invest_amt`, `plan_name`, `increase`, `duration`, `total_profit`, `start_date`, `end_date`, `status`) VALUES ('$user_id', '$planId', '$amount', '$plan_name', '$plan_increase', '$plan_duration', '$total_profit', '$start_date', '$end_date', 'Active' ) ");

    if ($sql) {
        $subject = 'Investment Confirmation';

        $htmlMessage = '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Investment Confirmation</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f9f9f9;
                    margin: 0;
                    padding: 0;
                }
                .email-container {
                    max-width: 600px;
                    margin: 20px auto;
                    background-color: #ffffff;
                    border: 1px solid #ddd;
                    border-radius: 8px;
                    overflow: hidden;
                }
                .email-header {
                    background-color: #015a63;
                    color: #ffffff;
                    padding: 20px;
                    text-align: center;
                    font-size: 18px;
                    font-weight: bold;
                }
                .email-logo {
                    margin: 10px 0;
                    width: 200px;
                }
                .email-body {
                    padding: 20px;
                    color: #333333;
                }
                .email-body h2 {
                    color: #015a63;
                }
                .email-body p {
                    font-size: 16px;
                    margin: 10px 0;
                }
                .email-summary {
                    background-color: #f1f1f1;
                    padding: 15px;
                    margin: 20px 0;
                    border-radius: 5px;
                    text-align: left;
                }
                .email-summary strong {
                    color: #015a63;
                }
                .email-footer {
                    text-align: center;
                    padding: 15px;
                    background-color: #f5f5f5;
                    font-size: 14px;
                    color: #777777;
                }
                .email-footer a {
                    text-decoration: none;
                    color: #015a63;
                    font-weight: bold;
                }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    Investment Activated
                </div>
                <div class="email-body">
                    <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo">
                    <h2>Hello ' . $username . ',</h2>
                    <p>Your investment has been successfully activated. Please find the details below:</p>
                    <div class="email-summary">
                        <p><strong>Plan Name:</strong> ' . $plan_name . '</p>
                        <p><strong>Investment Amount:</strong> $' . number_format($amount, 2) . ' USD</p>
                        <p><strong>Expected Profit:</strong> $' . number_format($total_profit, 2) . ' USD</p>
                        <p><strong>Growth Rate:</strong> ' . $plan_increase . '%</p>
                        <p><strong>Duration:</strong> ' . $plan_duration . ' hour(s)</p>
                        <p><strong>Start Date:</strong> ' . $start_date . '</p>
                        <p><strong>End Date:</strong> ' . $end_date . '</p>
                        <p><strong>Status:</strong> Active</p>
                    </div>
                    <p>We’ll keep you updated as your investment progresses. Thank you for choosing ' . $sitename . '.</p>
                </div>
                <div class="email-footer">
                    &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All Rights Reserved.
                </div>
            </div>
        </body>
        </html>';

        $send = sendmail($email, $username, $subject, $htmlMessage);

        mysqli_query($conn, "UPDATE users SET total_balance = total_balance - $amount WHERE id = '$user_id' ");
        echo json_encode(['status' => 'success', 'message' => "Investment started successfully"]);
    }

}

if (isset($_GET['user-data-submit'])) {
    
    $email_ = $_SESSION['email'];

    // Sanitize and get form inputs
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
    $lastname = mysqli_real_escape_string($conn, $_POST['lastname']);
    $dob = mysqli_real_escape_string($conn, $_POST['dob']);
    $country = mysqli_real_escape_string($conn, $_POST['country']);
    $street = mysqli_real_escape_string($conn, $_POST['street']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $zipcode = mysqli_real_escape_string($conn, $_POST['zipcode']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    
    // Additional fields
    $employment = mysqli_real_escape_string($conn, $_POST['employment']);
    $source = mysqli_real_escape_string($conn, $_POST['source']);
    $industry = mysqli_real_escape_string($conn, $_POST['industry']);
    $education = mysqli_real_escape_string($conn, $_POST['education']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $worth = mysqli_real_escape_string($conn, $_POST['worth']);
    $lot = mysqli_real_escape_string($conn, $_POST['lot']);
    $freq = mysqli_real_escape_string($conn, $_POST['freq']);
    $nature = mysqli_real_escape_string($conn, $_POST['nature']);
    $experience = mysqli_real_escape_string($conn, $_POST['experience']);
    $currency = mysqli_real_escape_string($conn, $_POST['currency']);
    
    // Prepare SQL update statement
    $sql = "UPDATE users SET 
            title = ?,
            firstname = ?,
            lastname = ?,
            dob = ?,
            country = ?,
            street = ?,
            address = ?,
            zip = ?,
            mobile = ?,
            employment = ?,
            source = ?,
            industry = ?,
            education = ?,
            amount = ?,
            worth = ?,
            lot = ?,
            freq = ?,
            nature = ?,
            experience = ?,
            currency = ?,
            updated_at = NOW()
            WHERE email = ?"; // Assuming you have the user ID from session or similar

    // Prepare and bind parameters
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssssssssssssssssssss", 
        $title, $firstname, $lastname, $dob, $country, 
        $street, $address, $zipcode, $phone, $employment,
        $source, $industry, $education, $amount, $worth,
        $lot, $freq, $nature, $experience, $currency,
        $_SESSION['email'] // Assuming user ID is stored in session
    );

    // Execute the statement
    if ($stmt->execute()) {
         $query = $conn->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
        $query->bind_param("s", $_SESSION['email']); 
        $query->execute();
        $result = $query->get_result();
    
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            $_SESSION['user_id'] = $user['id'];
        }
        $response = [
            'status' => 'success',
            'message' => 'User information updated successfully'
        ];
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Error updating user information: ' . $conn->error
        ];
    }

   
}


if(isset($_GET['update-deposit'])){
    $trx_id = $_SESSION['trx_id'] ?? null;
    if (!$trx_id || !isset($_FILES['proof'])) {
        echo json_encode(['status' => 'error', 'message' => 'No Deposit has been intiated']);
        exit;
    }

    $proofFile = $_FILES['proof'];

    $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
    if (!in_array($proofFile['type'], $allowedTypes)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type.']);
        exit;
    }

    if ($proofFile['size'] > 2 * 1024 * 1024) {
        echo json_encode(['status' => 'error', 'message' => 'File size exceeds 2MB.']);
        exit;
    }

    $uploadDir = 'uploads/proof/';
    $proofName = time().uniqid('proof_') . '_' . basename($proofFile['name']);
    $targetPath = $uploadDir . $proofName;

    if (!move_uploaded_file($proofFile['tmp_name'], $targetPath)) {
        echo json_encode(['status' => 'error', 'message' => 'File upload failed.']);
        exit;
    }

    $sql = "UPDATE transactions 
        SET status = 'Pending', proof = ?, updated_at = NOW()
        WHERE trx_id = ?";

    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        echo json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . $conn->error]);
        exit;
    }

    $stmt->bind_param("ss", $proofName, $trx_id);

    if ($stmt->execute()) {
        //Get transaction and user details
        $sql = "SELECT t.user_id, t.amount, t.currency, t.rate, t.trx_id, u.username, u.email 
            FROM transactions t 
            JOIN users u ON t.user_id = u.id 
            WHERE t.trx_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $trx_id);
        $stmt->execute();

        $result = $stmt->get_result();
        $data = $result->fetch_assoc();
        $amount = $data['amount'];
        $currency = $data['currency'];
        $rate = $data['rate'];
        $username = $data['username'];
        $user_id = $data['user_id'];
        $email = $data['email'];
        $subject = "Deposit request submitted - $sitename";

        //Delete other intiated deposit
        $sql = "DELETE FROM transactions WHERE user_id = ? AND status = 'Initiated'";
        $stmt = $conn->prepare($sql);

        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $htmlMessage = '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Deposit Notification</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 0;
                    padding: 0;
                    background-color: #f9f9f9;
                    color: #333;
                }
                .email-container {
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: #ffffff;
                    border: 1px solid #e0e0e0;
                    border-radius: 5px;
                    overflow: hidden;
                }
                .email-header {
                    background-color: #05445E;
                    color: white;
                    text-align: center;
                    padding: 20px;
                    font-size: 16px;
                    font-weight: bold;
                }
                .email-logo {
                    display: block;
                    margin: 0 auto 10px;
                    width: 200px;
                }
                .email-body {
                    padding: 20px;
                    text-align: center;
                }
                .email-body h2 {
                    margin: 10px 0;
                    font-size: 24px;
                }
                .email-body p {
                    margin: 15px 0;
                    font-size: 16px;
                    line-height: 1.5;
                }
                .details-table {
                    width: 100%;
                    margin-top: 20px;
                    border-collapse: collapse;
                }
                .details-table td {
                    padding: 10px;
                    border: 1px solid #e0e0e0;
                    text-align: left;
                }
                .email-footer {
                    text-align: center;
                    padding: 15px;
                    font-size: 14px;
                    color: #888;
                    border-top: 1px solid #e0e0e0;
                }
                .email-footer a {
                    color: #05445E;
                    text-decoration: none;
                }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    Deposit Proof Received
                </div>
                <div class="email-body">
                    <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo">
                    <h2>Hello ' . $username . '</h2>
                    <p>We have received your deposit request. Your transaction is currently under review.</p>

                    <table class="details-table">
                        <tr><td><strong>Amount</strong></td><td>' . $amount . ' USD</td></tr>
                        <tr><td><strong>Currency</strong></td><td>' . $currency . '</td></tr>
                        <tr><td><strong>Crypto Rate</strong></td><td>' . $rate . '</td></tr>
                        <tr><td><strong>Transaction ID</strong></td><td>' . $trx_id . '</td></tr>
                        <tr><td><strong>Status</strong></td><td>Pending Approval</td></tr>
                        <tr><td><strong>Submitted At</strong></td><td>' . date("Y-m-d H:i:s") . '</td></tr>
                    </table>

                    <p>You will receive another email once the transaction is confirmed.</p>
                    <p>If you did not authorize this deposit, please contact support immediately.</p>
                </div>
                <div class="email-footer">
                    &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All Rights Reserved.
                </div>
            </div>
        </body>
        </html>
        ';

        $send = sendmail($email, $username, $subject, $htmlMessage);

        echo json_encode(['status' => 'success', 'message' => 'Payment proof uploaded and transaction updated.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Execute failed: ' . $stmt->error]);
    }


}


if(isset($_GET['deposit'])){
    $amount = isset($_POST['amount']) ? $_POST['amount'] : '';
    $gatewayName = isset($_POST['gateway_name']) ? $_POST['gateway_name'] : '';
    $currency = isset($_POST['currency']) ? $_POST['currency'] : '';
    $userId = isset($_POST['user_id']) ? $_POST['user_id'] : '';
    $rate = isset($_POST['rate']) ? $_POST['rate'] : '';
    
    // Validate data
    if (empty($amount) || empty($gatewayName) || empty($currency) || empty($userId) || empty($rate)) {
        echo json_encode(['success' => false, 'message' => 'Invalid input']);
        exit;
    }
    
    // Insert into database
    
    $type = 'Deposit';

    $status = "Initiated";
    
    $sql = "INSERT INTO transactions (trx_id, amount, gateway, currency, user_id, rate, type, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sdsssdss', $trx_id, $amount, $gatewayName, $currency, $userId, $rate, $type, $status);
    
    if ($stmt->execute()) {
        $_SESSION['trx_id'] = $trx_id;
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $stmt->error]);
    }

}






if (isset($_GET['withdrawal'])) {
    
    function jsonResponse($status, $message) {
        echo json_encode(['status' => $status, 'message' => $message]);
        exit;
    }

    // Ensure the user is logged in
    if (!isset($_SESSION['user_id'])) {
        jsonResponse('error', 'User not logged in.');
    } 

    // Retrieve and sanitize input values
    $walletType = isset($_POST['wallet']) ? intval($_POST['wallet']) : null;
    $gateway = isset($_POST['with_gateway']) ? trim($_POST['with_gateway']) : null;
    $amount = isset($_POST['with_amount']) ? floatval($_POST['with_amount']) : 0;
    $currency = 'USD'; // Assuming USD, adjust as needed
    
    // Validate wallet type
    if (!in_array($walletType, [1, 2])) {
        jsonResponse('error', 'Invalid wallet type selected.');
    }


    
    // Validate amount
    if ($amount < 50) { // Minimum withdrawal amount of 50 USD
        jsonResponse('error', 'The minimum withdrawal amount is 50 USD.');
    }

    // Fetch user balance from the database
    $userId = $_SESSION['user_id'];
    $userQuery = "SELECT total_balance, profit_balance,email,username FROM users WHERE id = ?";
    $stmt = $conn->prepare($userQuery);
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        jsonResponse('error', 'User not found.');
    }
    
    $user = $result->fetch_assoc();
    $stmt->close();
    $email = $user['email'];
    $username = $user['username'];
    
    // Check if the user has sufficient balance
    $balance = $walletType === 1 ? $user['total_balance'] : $user['profit_balance'];
    if ($amount > $balance) {
        jsonResponse('error', 'Insufficient balance for this withdrawal.');
    }

    // Deduct the amount from the user's balance and process the withdrawal
    $conn->autocommit(FALSE); // Start transaction
    
    try {
        // Deduct balance
        $newBalance = $balance - $amount;
        $column = $walletType === 1 ? 'total_balance' : 'profit_balance';
        
        // Update user's balance
        $updateQuery = "UPDATE users SET $column = ? WHERE id = ?";
        $stmt = $conn->prepare($updateQuery);
        if (!$stmt) {
            throw new Exception("Failed to prepare update query: " . $conn->error);
        }
        $stmt->bind_param('di', $newBalance, $userId);
        if (!$stmt->execute()) {
            throw new Exception("Failed to execute update query: " . $stmt->error);
        }
        $stmt->close();
        
        // Insert withdrawal record
        $insertQuery = "INSERT INTO transactions (trx_id, user_id, amount, gateway, status, currency, created_at, type) VALUES (?, ?, ?, ?, 'pending', ?, NOW(), 'Withdrawal')";
        $stmt = $conn->prepare($insertQuery);
        if (!$stmt) {
            throw new Exception("Failed to prepare insert query: " . $conn->error);
        }
        $stmt->bind_param('sidss', $trx_id, $userId, $amount, $gateway, $currency);
        if (!$stmt->execute()) {
            throw new Exception("Failed to execute insert query: " . $stmt->error);
        }
        $stmt->close();
        
        // Commit the transaction
        $conn->commit();
        $subject = "Withdrawal Request Received";
        $htmlMessage = '
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Withdrawal Request</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f9f9f9;
                    margin: 0;
                    padding: 0;
                    color: #333;
                }
                .email-container {
                    max-width: 600px;
                    margin: 0 auto;
                    background-color: #ffffff;
                    border: 1px solid #e0e0e0;
                    border-radius: 5px;
                }
                .email-header {
                    background-color: #05445E;
                    color: white;
                    text-align: center;
                    padding: 20px;
                    font-size: 16px;
                    font-weight: bold;
                }
                .email-body {
                    padding: 20px;
                    text-align: center;
                }
                .email-body h2 {
                    margin: 10px 0;
                    font-size: 24px;
                }
                .email-body p {
                    margin: 15px 0;
                    font-size: 16px;
                }
                .details-table {
                    width: 100%;
                    margin-top: 20px;
                    border-collapse: collapse;
                }
                .details-table td {
                    padding: 10px;
                    border: 1px solid #e0e0e0;
                    text-align: left;
                }
                .email-footer {
                    text-align: center;
                    padding: 15px;
                    font-size: 14px;
                    color: #888;
                    border-top: 1px solid #e0e0e0;
                }
                .email-footer a {
                    color: #05445E;
                    text-decoration: none;
                }
            </style>
        </head>
        <body>
            <div class="email-container">
                <div class="email-header">
                    Withdrawal Request Received
                </div>
                <div class="email-body">
                    <img src="' . $siteurl . '/logo.jpg" alt="' . $sitename . ' Logo" class="email-logo" style="width: 200px;">
                    <h2>Hello ' . $username . ',</h2>
                    <p>We have received your withdrawal request. Your transaction is currently being processed and is pending approval.</p>

                    <table class="details-table">
                        <tr><td><strong>Amount</strong></td><td>' . $amount . ' USD</td></tr>
                        <tr><td><strong>Currency</strong></td><td>' . $currency . '</td></tr>
                        <tr><td><strong>Gateway</strong></td><td>' . htmlspecialchars($gateway) . '</td></tr>
                        <tr><td><strong>Transaction ID</strong></td><td>' . $trx_id . '</td></tr>
                        <tr><td><strong>Status</strong></td><td>Pending Approval</td></tr>
                        <tr><td><strong>Requested At</strong></td><td>' . date("Y-m-d H:i:s") . '</td></tr>
                    </table>

                    <p>You will receive another notification once the withdrawal is processed.</p>
                    <p>If you did not initiate this request, please contact our support team immediately.</p>
                </div>
                <div class="email-footer">
                    &copy; 2025 <a href="' . $siteurl . '">' . $sitename . '</a>. All rights reserved.
                </div>
            </div>
        </body>
        </html>';


        $send = sendmail($email, $username, $subject, $htmlMessage);
        jsonResponse('success', 'Withdrawal processed successfully! Your request is pending approval.');
        
    } catch (Exception $e) {
        // Rollback transaction if an error occurs
        $conn->rollback();
        jsonResponse('error', 'An error occurred while processing your withdrawal: ' . $e->getMessage());
        
    } finally {
        // End transaction and close connection
        $conn->autocommit(TRUE);
        $conn->close();
    }
}










if (isset($_GET['submit-kyc'])) {

// File Upload Validation
function validate_file($file, $file_type) {
    $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
    $max_size = 5 * 1024 * 1024; // 5MB

    if (!in_array($file['type'], $allowed_types)) {
        return "Invalid file type. Only JPG, JPEG, and PNG are allowed.";
    }

    if ($file['size'] > $max_size) {
        return "File size exceeds the 5MB limit.";
    }

    // Generate unique file name to avoid overwriting
    $target_dir = 'uploads/';  // Directory where the files will be stored
    $file_name = uniqid($file_type . '_') . basename($file['name']);
    $target_file = $target_dir . $file_name;

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        return $file_name; // Return the new file name if successful
    } else {
        return "Error uploading file.";
    }
}


    $document_type = isset($_POST['document_type']) ? $_POST['document_type'] : 'ID';
    $id_number = isset($_POST['id_number']) ? trim($_POST['id_number']) : '';
    $exp_date = isset($_POST['exp_date']) ? $_POST['exp_date'] : '';

    // Validate inputs
    if (empty($id_number) || empty($exp_date)) {
        echo json_encode(['success' => false, 'message' => 'ID Number and Expiry Date are required.']);
        exit;
    }

    // Validate and process front image
    if (isset($_FILES['front_image']) && $_FILES['front_image']['error'] === UPLOAD_ERR_OK) {
        $front_image = validate_file($_FILES['front_image'], 'front');
        if (strpos($front_image, 'Error') !== false) {
            echo json_encode(['success' => false, 'message' => $front_image]);
            exit;
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Front image is required.']);
        exit;
    }

    // Validate and process back image (optional)
    $back_image = null;
    if (isset($_FILES['back_image']) && $_FILES['back_image']['error'] === UPLOAD_ERR_OK) {
        $back_image = validate_file($_FILES['back_image'], 'back');
        if (strpos($back_image, 'Error') !== false) {
            echo json_encode(['success' => false, 'message' => $back_image]);
            exit;
        }
    }


    $userId = $_SESSION['user_id'];
    
    // Prepare the SQL statement to prevent SQL injection
    $stmt = $conn->prepare("INSERT INTO kyc_documents (user_id, document_type, id_number, exp_date, front_image, back_image) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param('isssss', $userId, $document_type, $id_number, $exp_date, $front_image, $back_image);

    // Execute the statement and check for success
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'KYC submitted successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error inserting data into database.']);
    }

    // Close statement and connection
    $stmt->close();
    $conn->close();
}
?>
