FUNCTIONS PAGE

 avatar
unknown
php
2 years ago
25 kB
3
Indexable
<?php

    
    // Import necessary PHPMailer classes
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    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';
    require __DIR__ . '/../PHPMailer/src/SMTP.php';


    
    /**
     * Formats a datetime string into a human-readable date and time format.
     *
     * @param string $dateTime The datetime string to be formatted.
     *
     * @return string Returns the formatted date and time string.
    */
    function formatDateTime($dateTime) {
        // Format the date part of the datetime string (M j, Y format)
        $date = date('M j, Y', strtotime($dateTime));

        // Format the time part of the datetime string (g:i A format)
        $time = date('g:i A', strtotime($dateTime));

        // Combine the formatted date and time strings with a separator
        return $date . ' - ' . $time;
    }





    /**
     * Handle funding errors.
     *
     * @param string $errorMessage The error message to log.
     */
    function handleFundingError($errorMessage) {

        error_log($errorMessage . ': ' . mysqli_error($GLOBALS['dbconn']), 3, '../error_log.php');
        echo 'funding failed';
    }






    /**
     * Selects a user's information based on their email address.
     *
     * @param string $email The email address of the user to retrieve information for.
     *
     * @return mixed|null Returns an associative array containing the user's information if found,
     *                   or null if the user is not found.
    */
    function selectUserByEmail($email) {
        // Query to select user information based on the provided email
        $query = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM `clients_tbl` WHERE u_email = '".$email."'");
        
        // Check if the query was successful and returned a single row
        if ($query && mysqli_num_rows($query) === 1) {
            // Fetch the row and store it as an associative array
            $userRow = mysqli_fetch_array($query, MYSQLI_ASSOC);
            
            // Return the user's information
            return $userRow;
        }

        // Return null if the user is not found
        return null;
    }



    

    /**
     * Selects the referral ID for a user based on their email address.
     *
     * @param string $email The email address of the user to retrieve the referral ID for.
     *
     * @return mixed Returns the user's referral ID if found, or false if not found or an error occurs.
    */
    function selectUserReferralIDByEmail($email) {
        // Query to select the referral ID based on the provided email
        $query = mysqli_query($GLOBALS['dbconn'], "SELECT u_referral_id FROM `clients_tbl` WHERE u_email = '".$email."'");
        
        // Check if the query was successful and returned a single row
        if ($query && mysqli_num_rows($query) === 1) {
            // Fetch the row and extract the referral ID
            $row = mysqli_fetch_assoc($query);
            
            // Return the user's referral ID
            return $row['u_referral_id'];
        }

        // Return false if the referral ID is not found or an error occurs
        return false;
    }




    
    
    /**
     * Checks the email verification status for a user and returns HTML code based on the status.
     *
     * @param string $email The email address of the user to check for verification status.
     *
     * @return string Returns HTML code representing the verification status message.
    */
    function checkEmailVerificationStatus($email) {
        // Initialize the email verification status result
        $emailVRStatusResult = '';
        
        // Query to select user information based on the provided email
        $query = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM `clients_tbl` WHERE u_email = '".$email."'");
        
        // Check if the query returned a single user
        if (mysqli_num_rows($query) === 1) {
            // Fetch user details
            $userRow = mysqli_fetch_array($query);
            
            // Extract email verification status
            $emailVRStatus = $userRow['u_email_verify_token'];
            
            // Check if the email is not verified
            if ($emailVRStatus !== 'Verified') {
                // Generate HTML code for the email verification status message
                $emailVRStatusResult = '<div class="col-xl-12 col-lg-12 -col-12">
                    <div class="alert alert-info" role="alert">
                        Your email address has not been verified yet. <a href="" class="alert-link"> Click Here</a> to verify your email address.
                    </div>
                </div>';
            } 
        }
        
        // Return the generated HTML code for the email verification status
        return $emailVRStatusResult;
    }

    
    
    


    /**
     * Retrieves and formats the user's notifications, returning HTML code.
     *
     * @param string $email The email of the user for whom to retrieve notifications.
     *
     * @return string Returns HTML code representing the user's notifications.
    */
    function userNotifications($email) {
        // Initialize the notification result
        $notificationResult = '';
        
        // Query to select unread notifications for the given user, limiting to the latest 5
        $selectNotification = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM `notifications_tbl` WHERE `n_client` = '".$email."' AND `n_status` = '0' ORDER BY `n_id` DESC LIMIT 5");
        
        // Check if there are notifications
        if (mysqli_num_rows($selectNotification) > 0) {
            // Loop through each notification and format the HTML
            while ($notificationRow = mysqli_fetch_array($selectNotification)) {
                // Extract notification time and format it
                $notification_time = $notificationRow['n_date'];
                $dateTime = formatDateTime($notification_time);
                
                // Append HTML for each notification to the result
                $notificationResult .= '<li class="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div class="d-flex">
                        <div class="flex-shrink-0 me-3">
                            <div class="avatar">
                                <span class="avatar-initial rounded-circle bg-label-warning"><i class="ti ti-bell"></i></span>
                            </div>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mb-1">'.$notificationRow['n_message'].'</h6>
                            <small class="text-muted">'.$dateTime.'</small>
                        </div>
                        <div class="flex-shrink-0 dropdown-notifications-actions">
                            <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="ti ti-x"></span></a>
                        </div>
                    </div>
                </li>';
            }
        } else {
            // If there are no notifications, display a message
            $notificationResult = '<li class="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                <div class="d-flex flex-column align-items-center justify-content-center">
                    <div class="flex-shrink-0 me-3">
                        <div class="avatar">
                            <span class="avatar-initial rounded-circle bg-label-warning"><i class="ti ti-bell"></i></span>
                        </div>
                    </div>
                    <div class="flex-grow-1 mt-2">
                        <h6 class="mb-1">No Notifications yet!</h6>
                    </div>
                </div>
            </li>';
        }
        
        // Return the generated HTML
        return $notificationResult;
    }


    
    
    

    /**
     * Counts the number of unread notifications for a user and generates the corresponding HTML.
     *
     * @param string $email The email of the user for whom to count notifications.
     *
     * @return string Returns HTML code representing the notification count badge.
    */
    function countUserNotification($email) {
        // Initialize the notification count result
        $notificationCountResult = '';
        
        // Query to select unread notifications for the given user
        $selectNotifications = mysqli_query($GLOBALS['dbconn'], "SELECT * FROM `notifications_tbl` WHERE n_client = '".$email."' AND n_status = '0'");
        
        // Count the number of unread notifications
        $notificationCount = mysqli_num_rows($selectNotifications);
        
        // Generate HTML based on the notification count
        if ($notificationCount > 0) {
            // If there are unread notifications, display the count in a badge
            $notificationCountResult = '<a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                <i class="ti ti-bell ti-md"></i>
                <span class="badge bg-danger rounded-pill badge-notifications">'.$notificationCount.'</span>
            </a>';
        } elseif ($notificationCount === 0) {
            // If there are no unread notifications, display the bell icon without a badge
            $notificationCountResult = '<a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                <i class="ti ti-bell ti-md"></i>
            </a>';
        }
        
        // Return the generated HTML
        return $notificationCountResult;
    }



    

    /**
     * Generates a unique support ticket ID.
     *
     * @return string Returns the generated support ticket ID.
    */
    function generateSupportTicketID() {
        // Generate a random 6-digit number, left-padded with zeros if necessary
        $randomNumber = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

        // Combine the prefix 'ST' with the random number to create the support ticket ID
        $supportTicketID = 'ST' . $randomNumber;

        // Return the generated support ticket ID
        return $supportTicketID;
    }



    

    /**
     * Retrieves the deposit count for a user based on their email.
     *
     * @param string $email The email for which to retrieve the deposit count.
     *
     * @return int|bool Returns the deposit count if found, or false on failure.
    */
    function getUserDepositCountByEmail($email) {
        // Replace 'clients_tbl' with your actual table name
        $depositCountQuery = 'SELECT u_deposit_count FROM `clients_tbl` WHERE u_email = ?';

        // Prepare and execute the query
        $stmt = mysqli_prepare($GLOBALS['dbconn'], $depositCountQuery);
        
        // Check if the query was successfully prepared
        if ($stmt) {
            // Bind the email parameter to the query
            mysqli_stmt_bind_param($stmt, 's', $email);
            
            // Execute the query
            mysqli_stmt_execute($stmt);
            
            // Bind the result
            mysqli_stmt_bind_result($stmt, $depositCount);
            
            // Fetch the result
            mysqli_stmt_fetch($stmt);
            
            // Close the statement
            mysqli_stmt_close($stmt);

            return $depositCount;
        } else {
            // Handle the case where the query preparation fails
            error_log('Error Fetching Deposit Count: ' . mysqli_error($GLOBALS['dbconn']), 3, '../error_log.php');
            return false;
        }
    }



    

    /**
     * Selects the referrer's ID based on the provided email.
     *
     * @param string $email The email for which to retrieve the referrer's ID.
     *
     * @return int|bool Returns the referrer's ID if found, or false on failure or if no referrer is found.
    */
    function selectReferrerByEmail($email) {
        // Prepare the statement
        $selectReferrerQuery = mysqli_prepare($GLOBALS['dbconn'], "SELECT u_referrer FROM clients_tbl WHERE u_email = ?");

        // Check if the statement was prepared successfully
        if (!$selectReferrerQuery) {
            // Handle the database query error
            $errorMessage = 'Error Fetching Referrer ID: ' . mysqli_error($GLOBALS['dbconn']);
            $errorMessage .= ' Query: SELECT u_referrer FROM clients_tbl WHERE u_email = ' . $email;
            error_log($errorMessage, 3, '../error_log.php');
            return false;
        }

        // Bind the email parameter to the query
        mysqli_stmt_bind_param($selectReferrerQuery, 's', $email);

        // Execute the query
        if (!mysqli_stmt_execute($selectReferrerQuery)) {
            // Handle the database query execution error
            $errorMessage = 'Error Fetching Referrer ID: ' . mysqli_stmt_error($selectReferrerQuery);
            $errorMessage .= ' Query: SELECT u_referrer FROM clients_tbl WHERE u_email = ' . $email;
            error_log($errorMessage, 3, '../error_log.php');
            return false;
        }

        // Bind the result
        mysqli_stmt_bind_result($selectReferrerQuery, $referrerId);

        // Fetch the result
        if (mysqli_stmt_fetch($selectReferrerQuery)) {
            // Check if the referrer ID is not empty
            if (!empty($referrerId)) {
                mysqli_stmt_close($selectReferrerQuery); // Close the statement
                return $referrerId;
            }
        }

        // No referrer found or empty referrer ID
        mysqli_stmt_close($selectReferrerQuery); // Close the statement
        return false;
    }



    

    /**
     * Records referral earnings in the referral_earnings_tbl table.
     *
     * @param int    $referrerId     The ID of the referrer.
     * @param int    $referralId     The ID of the referred user.
     * @param float  $depositAmount  The amount of the deposit made by the referred user.
     *
     * @return bool Returns true on successful recording, false on failure or invalid inputs.
    */
    function recordReferralEarnings($referrerId, $referralId, $depositAmount) {
        // Check if the referrer ID and deposit amount are valid
        if (!empty($referrerId) && is_numeric($depositAmount) && $depositAmount > 0) {

            // Calculate 20% of the deposit as referral earnings
            $referrerEarning = $depositAmount * 0.20;

            // Insert a record into the referral_earnings_tbl
            $insertQuery = "INSERT INTO referral_earnings_tbl (u_referrer_id, u_referred_id, earning_amount, earning_date) VALUES ('$referrerId', '$referralId', '$referrerEarning', NOW())";

            // Execute the query (you should have an active database connection)
            if (mysqli_query($GLOBALS['dbconn'], $insertQuery)) {
                // Referral earnings recorded successfully
                return true;
            } else {
                // Error occurred while inserting the record
                $errorMessage = 'Error Recording Referral Earning: ' . mysqli_error($GLOBALS['dbconn']);
                $errorMessage .= ' Query: ' . $insertQuery;
                error_log($errorMessage, 3, '../error_log.php');
                return false;
            }
        } else {
            // Invalid referrer ID or deposit amount
            $errorMessage = 'Error Recording Referral Earning: Invalid referrer ID or deposit amount';
            $errorMessage .= ' Referrer ID: ' . $referrerId . ', Deposit Amount: ' . $depositAmount;
            error_log($errorMessage, 3, '../error_log.php');
            return false;
        }
    }



    

    /**
     * Retrieves login logs for a client by their email.
     *
     * @param string $email The client's email.
     *
     * @return array Returns an array of login logs or an error message.
    */
    function getLoginLogsByEmail($email) {

        // Sanitize the email parameter to prevent SQL injection
        $email = sanitizeInput($email);

        // Prepare the SQL statement
        $stmt = mysqli_prepare($GLOBALS['dbconn'], "SELECT * FROM `clients_login_log_tbl` WHERE `email` = ?");
        
        // Check if the statement was successfully prepared
        if ($stmt) {
            // Bind the parameter to the statement
            mysqli_stmt_bind_param($stmt, 's', $email);
            
            // Execute the SQL statement
            if (mysqli_stmt_execute($stmt)) {
                // Get the result set
                $result = mysqli_stmt_get_result($stmt);
                
                // Fetch all rows into an associative array
                $loginLogs = [];
                while ($row = mysqli_fetch_assoc($result)) {
                    $loginLogs[] = $row;
                }
                
                // Close the statement
                mysqli_stmt_close($stmt);
                
                return $loginLogs;
            } else {
                // Handle SQL execution error (e.g., log, return an error message)
                error_log('SQL Error: ' . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
                return ['error' => 'SQL Error: ' . mysqli_error($GLOBALS['dbconn'])];
            }
        } else {
            // Handle SQL statement preparation error (e.g., log, return an error message)
            error_log('Error preparing statement: ' . mysqli_error($GLOBALS['dbconn']), 3, 'error_log.php');
            return ['error' => 'Error preparing statement: ' . mysqli_error($GLOBALS['dbconn'])];
        }
    }



    

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

        return $sanitizedInput;
    }




    
    /**
     * Generates a random 6-digit code for two-factor authentication (2FA) enablement.
     *
     * @return int Returns a randomly generated 6-digit code.
    */
    function generate6Digit2FAEnableCode() {
        // Define the minimum and maximum values for a 6-digit code.
        $min = 100000;
        $max = 999999;

        // Generate a random number within the specified range (6-digit code).
        $code = random_int($min, $max);

        return $code;
    }




    
    /**
     * Sends an email using PHPMailer.
     *
     * @param string      $toEmail       The recipient's email address.
     * @param string      $subject       The email subject.
     * @param string      $message       The email body content.
     * @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 on successful email sending, false on failure.
    */
    function sendEmail($toEmail, $subject, $message, $fromEmail, $fromName, $replyToEmail = null) {
        // Create a new PHPMailer instance
        $mail = new PHPMailer(true);

        try {
            // 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
            $mail->send();

            return true; // Email sent successfully
        } catch (Exception $e) {
            // Handle exceptions (e.g., log errors, return false)
            return false;
        }
    }





    
    /**
     * Checks the deposit notification status for a given client email.
     *
     * @param string $email The client's email.
     *
     * @return string|null Returns '0' or '1' if successful, null on error or if the value is not '0' or '1'.
    */
    function checkDepositNotificationStatus($email) {
        // Use prepared statements to prevent SQL injection
        $email = sanitizeInput($email);

        // SQL query to select the `u_deposit_notification` field
        $selectQuery = "SELECT u_deposit_notification FROM clients_tbl WHERE u_email = ?";

        // Initialize a prepared statement
        $stmt = mysqli_stmt_init($GLOBALS['dbconn']);

        // Check if the prepared statement was successfully initialized
        if (mysqli_stmt_prepare($stmt, $selectQuery)) {

            // Bind the parameter to the statement
            mysqli_stmt_bind_param($stmt, 's', $email);

            // Execute the statement
            mysqli_stmt_execute($stmt);

            // Bind the result
            mysqli_stmt_bind_result($stmt, $depositNotification);

            // Fetch the result
            mysqli_stmt_fetch($stmt);

            // Close the prepared statement
            mysqli_stmt_close($stmt);

            // Check if the value is either '0' or '1'
            if ($depositNotification === '0' || $depositNotification === '1') {
                // Return '0' or '1'
                return $depositNotification;
            }
        }

        // Return null if there's an error or if the value is not '0' or '1'
        return null;
    }




    
    /**
     * Inserts a funding record into the investments_tbl table.
     *
     * @param string $ref      The transaction ID or reference.
     * @param string $email    The client's email.
     * @param float  $amount   The amount of the deposit.
     * @param string $methodfull The funding method used.
     * @param string $fundTime The date and time of the funding transaction.
     *
     * @return bool Returns true on successful insertion, false on failure.
    */
    function insertFundingRecord($ref, $email, $amount, $methodfull, $fundTime) {
        // Construct the SQL query to insert a funding record
        $query = "INSERT INTO `investments_tbl` (`inv_type`, `tranx_id`, `inv_client`, `inv_amount`, `inv_method`, `inv_status`, `inv_date`) VALUES ('Deposit', '$ref', '$email', '$amount', '$methodfull', '0', '$fundTime')";
        
        // Execute the query
        $result = mysqli_query($GLOBALS['dbconn'], $query);

        // Check if the query was successful
        if ($result) {
            // Return true on successful insertion
            return true;
        } else {
            // Log the error, display an error message, or take appropriate action
            error_log('Error inserting funding record: ' . mysqli_error($GLOBALS['dbconn']), 3, '../error_log.php');
            
            // Return false on failure
            return false;
        }
    }





    /**
     * Inserts a notification record into the notifications table.
     *
     * @param string $email The client's email for whom the notification is intended.
     * @param string $message The message content of the notification.
     * @param string $fundTime The date and time of the notification.
     *
     * @return bool Returns true if the notification record is inserted successfully, otherwise false.
    */
    function insertNotificationRecord($email, $message, $fundTime) {
        // SQL query to insert a notification record
        $query = "INSERT INTO `notifications_tbl` (`n_client`, `n_message`, `n_status`, `n_date`) VALUES ('$email', '$message', '0', '$fundTime')";

        // Execute the query
        $result = mysqli_query($GLOBALS['dbconn'], $query);

        // Check if the query was successful
        if ($result) {
            return true; // Notification record inserted successfully
        } else {
            // Log the error, display an error message, or take appropriate action
            error_log('Error inserting notification record: ' . mysqli_error($GLOBALS['dbconn']), 3, '../error_log.php');
            return false; // Notification record insertion failed
        }
    }
Editor is loading...
Leave a Comment