FUNCTIONs

 avatar
unknown
php
a year ago
46 kB
4
Indexable
<?php

    // Import necessary PHPMailer classes
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    include 'db.inc.php';

    // Require PHPMailer classes using __DIR__
    require __DIR__ . '/PHPMailer/src/Exception.php';
    require __DIR__ . '/PHPMailer/src/PHPMailer.php';



    /**
     * Formats a given date time in the format 'M j, Y - g:i A'.
     *
     * @param string $dateTime The input date time string.
     * @return string Formatted date time string.
    */
    function formatDateTime($dateTime) {

        // Extract and format the date part
        $date = date('M j, Y', strtotime($dateTime));

        // Extract and format the time part
        $time = date('g:i A', strtotime($dateTime));

        // Combine the formatted date and time
        return $date . ' - ' . $time;
    }



    /**
     * Redirects to home.php with an error message.
     *
     * @param string $errorMessage Error message to display.
     *
     * @return void
     */
    function redirectWithError($pageName, $errorMessage) {

        header('Location: '.$pageName.'?type=error&message=' . urlencode($errorMessage));
        exit();
    }

    /**
     * Redirects to home.php with a success message.
     *
     * @param string $successMessage Success message to display.
     *
     * @return void
     */
    function redirectWithSuccess($pageName, $successMessage) {

        header('Location: '.$pageName.'?type=success&message=' . urlencode($successMessage));
        exit();
    }
    
    
    /**
     * Generate a random email verification token.
     *
     * @return string|bool - Returns the generated token if successful, or false if an error occurs.
    */
    function generateEmailVerificationToken() {
        // You can adjust the length of the token as needed
        $tokenLength = 32;

        try {
            // Generate a random binary string and convert it to hexadecimal
            $token = bin2hex(random_bytes($tokenLength));
            return $token;
        } catch (Exception $e) {
            // Handle the exception, log the error, or return an error response.
            return false;
        }
    }
    
    

    /**
     * Generate a random referral ID with a specified length.
     *
     * @param int $length - Optional. The length of the referral ID. Default is 10 characters.
     *
     * @return string - Returns the generated referral ID.
    */
    function generateReferralID($length = 10) {
        // Characters that can be used in the ID
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

        // Calculate the number of characters in the character set
        $numChars = strlen($characters);

        // Generate a random binary string
        $randomBytes = random_bytes($length);

        $referralID = '';

        // Loop through each character
        for ($i = 0; $i < $length; $i++) {
            // Convert the binary value to an index in the character set
            $index = ord($randomBytes[$i]) % $numChars;

            // Append the corresponding character to the ID
            $referralID .= $characters[$index];
        }

        return $referralID;
    }



    /**
     * Send an email using PHPMailer.
     *
     * @param string $toEmail - The recipient's email address.
     * @param string $subject - The subject of the email.
     * @param string $message - The content of the email.
     * @param string $fromEmail - The sender's email address.
     * @param string $fromName - The sender's name.
     * @param string|null $replyToEmail - Optional. The email address to set as the reply-to address.
     *
     * @return bool - Returns true if the email is sent successfully, false otherwise.
    */
    function sendEmail($toEmail, $subject, $message, $fromEmail, $fromName, $replyToEmail = null) {
        try {
            // Create a new PHPMailer instance
            $mail = new PHPMailer(true);
    
            // Recipients
            $mail->setFrom($fromEmail, $fromName);
            $mail->addAddress($toEmail);
            if ($replyToEmail) {
                $mail->addReplyTo($replyToEmail);
            }
            $mail->addCC($fromEmail);
            $mail->addBCC($fromEmail);
    
            // Content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $message;
    
            // Send the email
            if ($mail->send()) {
                return true; // Email sent successfully
            } else {
                // Log the error
                error_log("Email could not be sent. Error: " . $mail->ErrorInfo, 3, 'error_log.php');
                return false;
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Email exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }



    /**
     * Validate and sanitize a name to ensure it contains only allowed characters.
     *
     * @param string $name - The name to be validated and sanitized.
     *
     * @return string|bool - Returns the sanitized name if valid, or false if the name contains invalid characters.
    */
    function validateAndSanitizeName($name) {
        // Define a regular expression pattern to allow names from all languages
        $pattern = '/^[\p{L}\s\'-]+$/u';

        // Check if the name matches the pattern
        if (preg_match($pattern, $name)) {
            // Sanitize the name using mysqli_real_escape_string
            $sanitizedName = mysqli_real_escape_string($GLOBALS['dbconn'], $name);
            return $sanitizedName;
        } else {
            // Name contains invalid characters
            return false;
        }
    }



    /**
     * Retrieve user data based on the provided email address.
     *
     * @param string $email - The email address to search for in the database.
     *
     * @return mixed|null - Returns an associative array of user data if found, or null if not found.
    */
    function selectUserByEmail($email) {
        try {
            // Variable to store the user data
            $userRow = null;
    
            // Use prepared statements to prevent SQL injection
            $stmt = mysqli_prepare($GLOBALS['dbconn'], "SELECT * FROM `clients_tbl` WHERE u_email = ?");
            mysqli_stmt_bind_param($stmt, "s", $email);
            mysqli_stmt_execute($stmt);
    
            // Get the result
            $result = mysqli_stmt_get_result($stmt);
    
            // Check if a single matching record is found
            if ($result && mysqli_num_rows($result) === 1) {
                // Fetch the user data into an associative array
                $userRow = mysqli_fetch_array($result);
            }
    
            // Clean up resources by closing the statement
            mysqli_stmt_close($stmt);
    
            return $userRow;
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Select User By Email exception: " . $e->getMessage(), 3, 'error_log.php');
            return null;
        }
    }



    /**
     * Check if an email address already exists in the database.
     *
     * @param string $email - The email address to be checked.
     *
     * @return bool - Returns true if the email exists, false if it doesn't, or if an error occurs.
    */
    function checkEmailExists($email) {
        try {
            // Prepare the SQL statement to select a user by email
            $stmt = mysqli_prepare($GLOBALS['dbconn'], 'SELECT * FROM clients_tbl WHERE u_email = ');
    
            // Check if the statement is prepared successfully
            if ($stmt) {
                // Bind the email parameter
                mysqli_stmt_bind_param($stmt, 's', $email);
    
                // Execute the statement
                mysqli_stmt_execute($stmt);
    
                // Store the result
                mysqli_stmt_store_result($stmt);
    
                // Check the number of rows returned
                if (mysqli_stmt_num_rows($stmt) === 1) {
                    // Close the statement and return true if the email exists
                    mysqli_stmt_close($stmt);
                    return true;
                } else {
                    // Close the statement and return false if the email doesn't exist
                    mysqli_stmt_close($stmt);
                    return false;
                }
            } else {
                // Return false if an error occurs during statement preparation
                return false;
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Check Email Exists exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }


    
    /**
     * Validate an email address using the filter_var function.
     *
     * @param string $email - The email address to be validated.
     *
     * @return bool - Returns true if the email is valid, false otherwise.
    */
    function validateEmail($email) {
        // Return the result of the email validation using filter_var
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }



    /**
     * Sanitize user input to prevent SQL injection using mysqli_real_escape_string.
     *
     * @param string $input - The user input to be sanitized.
     *
     * @return string - The sanitized input.
    */
    function sanitizeInput($input) {
        // Sanitize the input using mysqli_real_escape_string
        $sanitizedInput = mysqli_real_escape_string($GLOBALS['dbconn'], $input);

        return $sanitizedInput;
    }



    /**
     * Check if the provided password and password confirmation match.
     *
     * @param string $password - User-entered password.
     * @param string $password_confirm - User-entered password confirmation.
     *
     * @return bool - Returns true if the passwords match, false otherwise.
    */
    function checkPasswordMismatch($password, $password_confirm) {
        // Compare the provided password and password confirmation
        return $password_confirm === $password;
    }



    /**
     * Retrieve user data based on the referral ID.
     *
     * @param string $ref - Referral ID to search for in the database.
     *
     * @return mixed - Returns an associative array of user data if found, or an empty string if not found.
    */
    function selectUserByReferralID($ref) {
        try {
            // Variable to store the user data
            $userRefRow = '';
    
            // Use prepared statements to prevent SQL injection
            $stmt = mysqli_prepare($GLOBALS['dbconn'], "SELECT * FROM `clients_tbl` WHERE u_referral_id = ?");
            mysqli_stmt_bind_param($stmt, "s", $ref);
            mysqli_stmt_execute($stmt);
    
            // Get the result
            $result = mysqli_stmt_get_result($stmt);
    
            // Check if a single matching record is found
            if ($result && mysqli_num_rows($result) === 1) {
                // Fetch the user data into an associative array
                $userRefRow = mysqli_fetch_array($result);
            }
    
            // Clean up resources by closing the statement
            mysqli_stmt_close($stmt);
    
            return $userRefRow;
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Select User By Referral ID exception: " . $e->getMessage(), 3, 'error_log.php');
            return '';
        }
    }



    /**
     * Update the referrer for a new user in the database.
     *
     * @param string $uReferralID - Referral ID of the new user.
     * @param string $uReferrerID - Referrer ID to be assigned to the new user.
     *
     * @return bool - Returns true if the update is successful, false otherwise.
    */
    function updateReferrerForNewUser($uReferralID, $uReferrerID) {
        try {
            // Flag to indicate the success of the update operation
            $success = false;
    
            // Use prepared statements to prevent SQL injection
            $stmt = mysqli_prepare($GLOBALS['dbconn'], "UPDATE `clients_tbl` SET u_referrer = ? WHERE u_referral_id = ?");
            mysqli_stmt_bind_param($stmt, "ss", $uReferrerID, $uReferralID);
    
            // Execute the statement and update the success flag
            $success = mysqli_stmt_execute($stmt);
    
            // Check for errors and log the MySQL error message if update fails
            if (!$success) {
                error_log("MySQL Error: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
            }
    
            // Clean up resources by closing the statement
            mysqli_stmt_close($stmt);
    
            return $success;
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Update Referrer exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }



    /**
     * Register a new user in the database.
     *
     * @param string $name - User's name.
     * @param string $email - User's email address.
     * @param string $tel - User's telephone number.
     * @param string $currency - User's preferred currency.
     * @param string $country - User's country.
     * @param string $password - User's password.
     * @param string $referralID - User's referral ID.
     * @param string $verify_code - Email verification code.
     * @param string $join_date - User's registration date.
     *
     * @return bool - Returns true if registration is successful, false otherwise.
    */
    function registerUser($name, $email, $tel, $currency, $country, $password, $referralID, $verify_code, $join_date) {
        try {
            // Prepare the SQL statement
            $stmt = mysqli_prepare($GLOBALS['dbconn'], 'INSERT INTO clients_tbl (u_name, u_email, u_password, u_currency, u_country, u_phone, u_referral_id, u_email_verify_token, u_join_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
    
            if ($stmt) {
                // Hash the password
                $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    
                // Bind parameters
                mysqli_stmt_bind_param($stmt, 'sssssssss', $name, $email, $passwordHash, $currency, $country, $tel, $referralID, $verify_code, $join_date);
    
                // Execute the statement
                if (mysqli_stmt_execute($stmt)) {
                    // Registration successful
                    return true;
                } else {
                    // Log the error
                    error_log("Registration Error: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                    // Registration failed
                    return false;
                }
    
                // Close the statement
                mysqli_stmt_close($stmt);
            } else {
                // Log the error
                error_log("Statement Preparation Error: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                // Statement preparation failed
                return false;
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Register User exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }


    
    /**
     * Generate a unique transaction ID with a specified length.
     *
     * @return string - The generated transaction ID.
    */
    function generateTransactionID() {
        try {
            // Define characters allowed in the alphanumeric string
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
            // Calculate the length of the alphanumeric string
            $length = 10;
    
            // Generate a random alphanumeric string
            $randomString = '';
            for ($i = 0; $i < $length; $i++) {
                // Append a random character from the allowed characters
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
            }
    
            // Combine the prefix 'TX' with the generated alphanumeric string
            $transactionID = 'TX' . $randomString;
    
            return $transactionID;
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Generate Transaction ID exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }




    /**
     * Inserts deposit information into the database.
     *
     * @param string $dep_transaction_id - The generated transaction ID for the deposit.
     * @param string $client - The email address of the client making the deposit.
     * @param float $amount - The amount of the deposit.
     * @param string $methodfull - The full name of the payment method used for the deposit.
     *
     * @return bool - Returns true if the insertion is successful, false otherwise.
    */
    function insertDepositPayment($dep_transaction_id, $client, $amount, $methodfull) {
        // Implement your database insertion logic here
    
        try {
            // SQL query to insert deposit information using prepared statements for security
            $query = "INSERT INTO `investments_tbl` (`inv_type`, `tranx_id`, `inv_client`, `inv_amount`, `inv_method`, `inv_status`, `inv_date`) VALUES ('Deposit', ?, ?, ?, ?, '0', NOW())";
    
            // Prepare the SQL statement
            $stmt = mysqli_prepare($GLOBALS['dbconn'], $query);
    
            if (!$stmt) {
                // Error handling for preparation failure
                error_log("Error preparing SQL statement: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                return false;
            }
    
            // Bind parameters to the prepared statement
            // 'ssds' indicates the types of the parameters (string, string, decimal, string)
            mysqli_stmt_bind_param($stmt, 'ssds', $dep_transaction_id, $client, $amount, $methodfull);
    
            // Execute the prepared statement
            $result = mysqli_stmt_execute($stmt);
    
            if (!$result) {
                // Error handling for execution failure
                error_log("Error executing SQL statement: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
            }
    
            // Close the prepared statement
            mysqli_stmt_close($stmt);
    
            // Return true if the insertion is successful, false otherwise
            return $result;
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Insert Deposit Payment exception: " . $e->getMessage(), 3, 'error_log.php');
            return false;
        }
    }



    /**
     * Get the full name of a payment method based on its code.
     *
     * @param string $payment - The code representing the payment method (e.g., 'btc', 'eth', 'erc', 'trc').
     *
     * @return string - The full name of the payment method.
    */
    function getPaymentMethodFullName($payment) {

        // Implement your logic to map payment method code to full name

        // Example mapping:
        if ($payment == 'btc') {

            return 'Bitcoin Deposit';
        } elseif ($payment == 'eth') {

            return 'Ethereum Deposit';
        } elseif ($payment == 'erc') {

            return 'USDT ERC20';
        } elseif ($payment == 'trc') {

            return 'USDT TRC20';
        }

        // If the provided payment code does not match any known methods, you may handle it here.
        // For simplicity, it returns an empty string. You may customize this based on your requirements.
        return '';
    }



    /**
     * Handles withdrawal request and returns a message.
     *
     * @param string $email User's email.
     * @param float $wth_amount Withdrawal amount.
     * @param string $wth_method Withdrawal method.
     * @param string $crypto_wth_address Crypto withdrawal address.
     * @param string $crypto_name Crypto name.
     * @param string $pp_address PayPal address.
     * @param string $skr_address Skrill address.
     * @param string $bank_name Bank name.
     * @param string $account_number Account number.
     * @param string $account_name Account name.
     * @param string $routing_number Routing number.
     *
     * @return void Redirects to home.php with appropriate message.
    */
    function requestWithdraw($email, $wth_amount, $wth_method, $crypto_wth_address, $crypto_name, $pp_address, $skr_address, $bank_name, $account_number, $account_name, $routing_number) {
    
        // Initialize withdrawal message
        $withdraw_message = '';
    
        try {
            $selectUserStmt = mysqli_prepare($GLOBALS['dbconn'], "SELECT * FROM clients_tbl WHERE u_email = ?");
            mysqli_stmt_bind_param($selectUserStmt, 's', $email);
            mysqli_stmt_execute($selectUserStmt);
            $selectUserResult = mysqli_stmt_get_result($selectUserStmt);
    
            if ($selectUserResult && mysqli_num_rows($selectUserResult) == 1) {
    
                $userRow = mysqli_fetch_array($selectUserResult);
                $balance = $userRow['u_balance'];
            }
    
            // Check if the withdrawal amount is greater than the user's balance
            if ($wth_amount > $balance) {
                $withdraw_message = redirectWithError('home.php', 'Insufficient Wallet Balance.');
            }
    
            // Check if the withdrawal amount is less than or equal to zero
            if ($wth_amount <= 0) {
                $withdraw_message = redirectWithError('home.php', 'Error! Invalid withdrawal amount.');
            }
    
            // Proceed with withdrawal if the amount is valid
            if ($wth_amount > 0 && $wth_amount <= $balance) {
    
                // Generate a transaction ID using the function
                $wthTransactionId = generateTransactionID();
    
                $to = 'thomkralow@gmail.com';
                $from = $GLOBALS['system_support_email'];
                $contactFrom = $GLOBALS['system_contact_email'];
                $fromName = $GLOBALS['system_name'];
                $subject = 'Client Withdrawal Request Notification';
                $message = 'A Client with email - ' . $email . ' just made a withdrawal request of $' . number_format($wth_amount, 2) . '';
    
                // Send email and handle result
                $emailResult = sendEmail($to, $subject, $message, $from, $fromName, $contactFrom);
    
                if ($emailResult) {
    
                    $insertWithdrawStmt = mysqli_prepare($GLOBALS['dbconn'], "INSERT INTO `investments_tbl` (`inv_type`, `tranx_id`, `inv_client`, `inv_amount`, `inv_method`, `crypto_name`, `crypto_wallet_address`, `pp_address`, `skr_address`, `bank_name`, `account_number`, `account_name`, `routing_number`, `inv_status`, `inv_date`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '0', NOW())");
                    mysqli_stmt_bind_param($insertWithdrawStmt, 'ssssssssssss', 'Withdraw', $wthTransactionId, $email, $wth_amount, $wth_method, $crypto_name, $crypto_wth_address, $pp_address, $skr_address, $bank_name, $account_number, $account_name, $routing_number);
                    $insertWithdrawResult = mysqli_stmt_execute($insertWithdrawStmt);
    
                    if ($insertWithdrawResult) {
    
                        $withdraw_message = redirectWithSuccess('home.php', 'Withdrawal Request Submitted Successfully. You will be notified through your email address when your request is confirmed. Your withdrawal amount will be sent to the withdrawal method you specified.');
                    } else {
    
                        $withdraw_message = redirectWithError('home.php', 'Something went wrong... Try Again or contact support for assistance.');
    
                        // Log the error
                        error_log("Withdrawal - Failed to insert withdrawal record: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                    }
                } else {
                    
                    $withdraw_message = redirectWithError('home.php', 'Something went wrong... Try Again or contact support for assistance.');
    
                    // Log the error
                    error_log("Withdrawal - Failed to send withdrawal notification email.", 3, 'error_log.php');
                }
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Withdrawal exception: " . $e->getMessage(), 3, 'error_log.php');
            $withdraw_message = redirectWithError('home.php', 'Something went wrong... Try Again or contact support for assistance.');
        }
    
        return $withdraw_message;
    }



    /**
     * Updates user profile information.
     *
     * @param string $email User's email address.
     * @param string $usr_name User's name.
     * @param string $usr_email User's email.
     * @param string $usr_country User's country.
     * @param string $usr_phone User's phone number.
     * @param string $usr_currency User's currency.
     * @return string Redirect message or header location based on the result.
    */
    function updateAccountProfile($email, $usr_name, $usr_email, $usr_country, $usr_phone, $usr_currency) {
    
        // Initialize the message variable
        $update_profile_message = '';
    
        try {
            // Check if the email exists
            $chck_email = checkEmailExists($email);
    
            if (!$chck_email) {
                // Redirect with email not found message
                $update_profile_message = redirectWithError('profile.php', 'Something went wrong... Try Again or contact support for assistance.');
            } else {
                // Update user profile in the database
                $update_profile_kwary = mysqli_prepare($GLOBALS['dbconn'], "UPDATE clients_tbl SET u_name = ?, u_email = ?, u_currency = ?, u_country = ?, u_phone = ? WHERE u_email = ?");
                mysqli_stmt_bind_param($update_profile_kwary, 'ssssss', $usr_name, $usr_email, $usr_currency, $usr_country, $usr_phone, $email);
    
                $update_result = mysqli_stmt_execute($update_profile_kwary);
    
                if ($update_result) {
    
                    // Update other tables where the user email is a foreign key
                    $update_investment_table_email = mysqli_prepare($GLOBALS['dbconn'], "UPDATE investments_tbl SET inv_client = ? WHERE inv_client = ?");
    
                    mysqli_stmt_bind_param($update_investment_table_email, "ss", $usr_email, $email);
    
                    $update_investment_result = mysqli_stmt_execute($update_investment_table_email);
    
                    if ($update_investment_result) {
    
                        // Redirect with success message
                        $update_profile_message = redirectWithSuccess('profile.php', 'Profile updated successfully.');
                    } else {
    
                        // Redirect with failure message for updating related tables
                        $update_profile_message = redirectWithError('profile.php', 'Something went wrong... Try Again or contact support for assistance.');
    
                        // Log the error
                        error_log("Update profile - Failed to update investment table: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                    }
    
                    // Close the prepared statement for updating related tables
                    mysqli_stmt_close($update_investment_table_email);
                } else {
    
                    // Redirect with failure message for updating user profile
                    $update_profile_message = redirectWithError('profile.php', 'Something went wrong... Try Again or contact support for assistance.');
    
                    // Log the error
                    error_log("Update profile - Failed to update user profile: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                }
    
                // Close the prepared statements
                mysqli_stmt_close($update_profile_kwary);
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Update profile exception: " . $e->getMessage(), 3, 'error_log.php');
            $update_profile_message = redirectWithError('profile.php', 'Something went wrong... Try Again or contact support for assistance.');
        }
    
        return $update_profile_message;
    }
	

	/**
     * Changes the user's password.
     *
     * @param string $email User's email address.
     * @param string $old_passkey Old password entered by the user.
     * @param string $new_passkey New password to be set.
     * @param string $new_passkey_confirm Confirmation of the new password.
     * @return string Redirect message or header location based on the result.
    */
    function changeAccountPassword($email, $old_passkey, $new_passkey, $new_passkey_confirm) {
    
        // Initialize the message variable
        $cp_message = '';
    
        try {
            // Check if the email exists
            $chck_email = checkEmailExists($email);
    
            if ($chck_email) {
    
                // Hash the old password for comparison
                $hash = password_hash($old_passkey, PASSWORD_DEFAULT);
    
                // Check if the hashed old password matches the stored password for the given email
                $chck_old_passkey_query = mysqli_prepare($GLOBALS['dbconn'], "SELECT u_password FROM clients_tbl WHERE u_password = ? AND u_email = ?");
                mysqli_stmt_bind_param($chck_old_passkey_query, 'ss', $hash, $email);
                mysqli_stmt_execute($chck_old_passkey_query);
                mysqli_stmt_store_result($chck_old_passkey_query);
    
                if (mysqli_stmt_num_rows($chck_old_passkey_query) === 1) {
    
                    // Check if the new passwords match
                    $chck_pass = checkPasswordMismatch($new_passkey, $new_passkey_confirm);
    
                    if ($chck_pass === false) {
    
                        // Hash the new password
                        $hash_new_pwd = password_hash($new_passkey, PASSWORD_DEFAULT);
    
                        // Update the user's password in the database
                        $change_password_query = mysqli_prepare($GLOBALS['dbconn'], "UPDATE clients_tbl SET u_password = ? WHERE u_email = ?");
                        mysqli_stmt_bind_param($change_password_query, "ss", $hash_new_pwd, $email);
                        $change_result = mysqli_stmt_execute($change_password_query);
    
                        if ($change_result) {
                            // Redirect with success message
                            $cp_message = redirectWithSuccess('settings.php', 'Password changed successfully.');
                        } else {
                            // Redirect with failure message
                            $cp_message = redirectWithError('settings.php', 'Something went wrong... Try Again or contact support for assistance.');
    
                            // Log the error
                            error_log("Change password - Failed to update user password: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                        }
                    } else {
                        // Redirect with password mismatch message
                        $cp_message = redirectWithError('settings.php', 'Passwords do not match.');
                    }
                } elseif (mysqli_stmt_num_rows($chck_old_passkey_query) === 0) {
                    // Redirect with old password mismatch message
                    $cp_message = redirectWithError('settings.php', 'Old password is incorrect.');
                }
    
                // Close the prepared statements
                mysqli_stmt_close($chck_old_passkey_query);
                mysqli_stmt_close($change_password_query);
            } else {
                // Redirect with email not found message
                $cp_message = redirectWithError('settings.php', 'Something went wrong... Try Again or contact support for assistance.');
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Change password exception: " . $e->getMessage(), 3, 'error_log.php');
            $cp_message = redirectWithError('settings.php', 'Something went wrong... Try Again or contact support for assistance.');
        }
    
        return $cp_message;
    }



    /**
     * Handles the KYC document upload logic and updates the user profile.
     *
     * @param string $email User's email address.
     * @param string $doc_type Document type.
     * @param string $frontFileName Front document file name.
     * @param string $backFileName Back document file name.
     * @return string Redirect message or header location based on the result.
    */
    function handleKYCDocumentUpload($email, $doc_type, $frontFileName, $backFileName) {
    
        // Initialize the message variable
        $kyc_message = '';
    
        try {
            // Define target directories for front and back document uploads
            $frontTargetDir = '../uploads/kyc/front/';
            $backTargetDir = '../uploads/kyc/back/';
    
            // Retrieve and sanitize file names and paths for front and back documents
            $frontTargetFilePath = $frontTargetDir . $frontFileName;
            $frontFileType = pathinfo($frontTargetFilePath, PATHINFO_EXTENSION);
    
            $backTargetFilePath = $backTargetDir . $backFileName;
            $backFileType = pathinfo($backTargetFilePath, PATHINFO_EXTENSION);
    
            // Allowed file types for document upload
            $allowTypes = array('jpg', 'png', 'jpeg', 'pdf');
    
            // Check if file types are allowed
            if (in_array($frontFileType, $allowTypes) && in_array($backFileType, $allowTypes)) {
    
                // Move the uploaded files to the target directories
                if (move_uploaded_file($_FILES['doc_front']['tmp_name'], $frontTargetFilePath) && move_uploaded_file($_FILES['doc_back']['tmp_name'], $backTargetFilePath)) {
    
                    // Update user database record with document information using prepared statement
                    $updateStatement = mysqli_prepare($GLOBALS['dbconn'], "UPDATE `clients_tbl` SET u_id_doc_type = ?, u_id_doc_front = ?, u_id_doc_back = ?, u_id_doc_status = '1' WHERE u_email = ?");
    
                    mysqli_stmt_bind_param($updateStatement, "ssss", $doc_type, $frontFileName, $backFileName, $email);
    
                    $updateResult = mysqli_stmt_execute($updateStatement);
    
                    if ($updateResult) {
    
                        // Redirect with success message
                        $kyc_message = redirectWithSuccess('settings.php', 'KYC document uploaded successfully.');
                    } else {
    
                        // Redirect with failure message
                        $kyc_message = redirectWithError('settings.php', 'Failed to update KYC information.');
    
                        // Log the error
                        error_log("KYC Document Upload - Failed to update KYC information: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                    }
                } else {
    
                    // Redirect with error message
                    $kyc_message = redirectWithError('settings.php', 'Error in moving uploaded files.');
                }
            } else {
    
                // Redirect with file format error message
                $kyc_message = redirectWithError('settings.php', 'Invalid file format for KYC documents.');
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("KYC Document Upload exception: " . $e->getMessage(), 3, 'error_log.php');
            $kyc_message = redirectWithError('settings.php', 'Something went wrong... Try Again or contact support for assistance.');
        }
    
        return $kyc_message;
    }



    /**
     * Checks the KYC verification status for a user.
     *
     * @param string $email User's email address.
     * @return string Verification status: '0' for pending, '1' for rejected, '2' for approved, '3' for error.
    */
    function checkIDVerificationStatus($email) {
        // Initialize the verification message
        $IDVerifyMessage = '3';
    
        try {
            // Check if the email exists
            $checkEmail = checkEmailExists($email);
    
            if ($checkEmail) {
                // Use prepared statement to retrieve the verification status
                $select = mysqli_prepare($GLOBALS['dbconn'], "SELECT u_id_doc_status FROM clients_tbl WHERE u_email = ?");
                mysqli_stmt_bind_param($select, 's', $email);
    
                if (mysqli_stmt_execute($select)) {
                    // Fetch the result
                    mysqli_stmt_store_result($select);
    
                    if (mysqli_stmt_num_rows($select) > 0) {
                        mysqli_stmt_bind_result($select, $statusNo);
                        mysqli_stmt_fetch($select);
    
                        // Determine the verification status
                        switch ($statusNo) {
                            case '0':
                                $IDVerifyMessage = '0'; // Pending
                                break;
                            case '1':
                                $IDVerifyMessage = '1'; // Rejected
                                break;
                            case '2':
                                $IDVerifyMessage = '2'; // Approved
                                break;
                            default:
                                $IDVerifyMessage = '3'; // Declined
                                break;
                        }
                    }
                } else {
                    // Handle database query execution error
                    // You may log the error or take appropriate action based on your application's needs
                    // For example: error_log(mysqli_error($GLOBALS['dbconn']));
                    $IDVerifyMessage = '3'; // Error
    
                    // Log the error
                    error_log("Check ID Verification Status - Database query execution error: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                }
    
                // Close the prepared statement
                mysqli_stmt_close($select);
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Check ID Verification Status exception: " . $e->getMessage(), 3, 'error_log.php');
            $IDVerifyMessage = '3'; // Error
        }
    
        return $IDVerifyMessage;
    }



    /**
     * Retrieves transaction history for a user including both deposits and withdrawals.
     *
     * @param string $email User's email address.
     * @return string HTML representation of the user's transaction history.
    */
    function transactionHistory($email) {
    
        // Initialize the history message
        $historyMessage = '';
    
        try {
            $userRow = selectUserByEmail($email);
    
            // Check if the email exists
            $checkEmail = checkEmailExists($email);
    
            if ($checkEmail) {
    
                // Use prepared statement to select transactions
                $selectTransactions = mysqli_prepare($GLOBALS['dbconn'], "SELECT inv_type, inv_amount, inv_method, inv_date, inv_status FROM investments_tbl WHERE inv_client = ? ORDER BY inv_id DESC");
    
                mysqli_stmt_bind_param($selectTransactions, 's', $email);
    
                if (mysqli_stmt_execute($selectTransactions)) {
                    // Fetch the result
                    mysqli_stmt_store_result($selectTransactions);
    
                    if (mysqli_stmt_num_rows($selectTransactions) > 0) {
    
                        mysqli_stmt_bind_result($selectTransactions, $invType, $invAmount, $invMethod, $invDate, $invStatus);
    
                        while (mysqli_stmt_fetch($selectTransactions)) {
    
                            // Determine the transaction status
                            switch ($invStatus) {
                                case '0':
                                    $status = '<a href="#" class="btn btn-warning btn-md wd-100">Pending</a>';
                                    break;
                                case '1':
                                    $status = '<a href="#" class="btn btn-success btn-md wd-100">Confirmed</a>';
                                    break;
                                case '2':
                                    $status = '<a href="#" class="btn btn-danger btn-md wd-100">Declined</a>';
                                    break;
                                default:
                                    $status = ''; // Handle other statuses as needed
                                    break;
                            }
    
                            // Determine the transaction type
                            switch ($invType) {
                                case 'Deposit':
                                    $Typestatus = '<span class="icon me-3 rounded-circle d-flex align-items-center justify-content-center bg-success">
                                        <i class="las la-arrow-up"></i>
                                    </span>';
                                    break;
                                case 'Withdrawal':
                                    $Typestatus = '<span class="icon me-3 rounded-circle d-flex align-items-center justify-content-center bg-danger">
                                        <i class="las la-arrow-down"></i>
                                    </span>';
                                    break;
                            }
    
                            $TxDateTime = formatDateTime($invDate);
    
                            // Build HTML for each transaction
                            $historyMessage .= '<li class="d-sm-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center">
                                    '.$Typestatus.'
                                    <div>
                                        <p class="mb-2">'.$TxDateTime.'</p>
                                        <h5>'.$invMethod.'</h5>
                                    </div>
                                </div>
                                <div class="ms-5 mt-3 text-sm-end">
                                    <h4>'.number_format($invAmount, 2).' '.$userRow['u_currency'].'</h4>
                                    <small class="text-muted">'.$status.'</small>
                                </div>
                            </li>';
                        }
                    }
                } else {
                    // Handle database query execution error
                    // You may log the error or take appropriate action based on your application's needs
                    // For example: error_log(mysqli_error($GLOBALS['dbconn']));
                    $historyMessage = '<tr><td colspan="5">Error retrieving transaction history</td></tr>';
    
                    // Log the error
                    error_log("Transaction History - Database query execution error: " . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                }
    
                // Close the prepared statement
                mysqli_stmt_close($selectTransactions);
            }
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors)
            error_log("Transaction History exception: " . $e->getMessage(), 3, 'error_log.php');
            $historyMessage = '<tr><td colspan="5">Error retrieving transaction history</td></tr>';
        }
    
        return $historyMessage;
    }
Editor is loading...
Leave a Comment