
<?php
// Include your database connection file (e.g., _db.php)
@session_start();

require_once("../_db.php");

// Function to send email notification
function sendEmailNotification($email, $full_name,$userid, $subject) {
    // Set the recipient's email
    $to = $email;

    // Message content with HTML formatting
    $message = "<html>
    <head>
        <style>
            .container {
                font-family: Arial, sans-serif;
                background-color: #f4f4f4;
                padding: 20px;
                border-radius: 5px;
            }
            .mail-link {
                color: #007bff; 
                text-decoration: none;
            }
            
            .mail-link:hover {
                text-decoration: underline;
            }
            .green-button {
                display: inline-block;
                background-color: #4CAF50; /* Green background */
                color: white;
                padding: 10px 20px; /* Add padding */
                text-align: center;
                text-decoration: none;
                font-size: 16px;
                border-radius: 5px;
                border: none;
                cursor: pointer;
            }
            
            .green-button:hover {
                background-color: #45a049;
            }
        </style>
    </head>
    <body>
        <div class='container'>
        <center>
            <img src='https://choicydigitals.org/img/icon-deal.png' alt='logo'/>
        </center>
            <h3>Dear, $full_name </h3>
            <p>We are thrilled to have you join Choicy Digitals, your premier destination for Real Estate investment opportunities and financial growth! Thank you for choosing Choicy Digitals as your platform to explore, invest, and secure your financial future. We're excited to welcome you to our community of savvy investors and wealth builders..
            </p>
            <span>What's waiting for you on Choicy Digitals:</span>
            <p>1. Explore Real Estate Investment Opportunities: Dive into a diverse range of investment options tailored to suit your financial goals and preferences. From stocks and bonds to real estate and alternative assets, discover opportunities that align with your investment strategy.</p>
            
            <p>2. Personalized Portfolio Management: Take control of your financial portfolio with our intuitive tools and resources. Choicy Digitals provides comprehensive portfolio management solutions to help you optimize your investments and track your progress.
            </p>
            <p>3. Expert Insights and Analysis: Gain valuable insights and expert analysis to make informed investment decisions. Stay updated with the latest market trends, news, and strategies to maximize your returns and minimize risks.</p>
            <p>4. Community Engagement: Engage with fellow investors, share experiences, and exchange ideas within the Choicy Digitals community. Connect with like-minded individuals, participate in discussions, and expand your knowledge base.
            </p>
            <p>Getting Started:</p>
            <p>Complete Your Profile: Ensure you get the most out of your Choicy Digitals experience by setting up your profile with relevant information and preferences.</p>
            <p>2. Explore Investment Opportunities: Browse through our curated selection of investment opportunities and choose the ones that best suit your financial objectives.</p>
            <p>3. Diversify Your Portfolio: Build a diversified investment portfolio tailored to your risk tolerance and investment goals. Explore a variety of asset classes to spread risk and enhance potential returns.</p>
            <p>
            Should you have any questions or need assistance, our support team is here to help. Don't hesitate to reach out to support@solixproperties.org for any inquiries.</p>
            <p>Once again, thank you for choosing Choicy Digitals. We look forward to supporting you on your journey towards financial success and prosperity.</p>
            <p class='text-center'> Verify Your Account</p>
            <p>To verify your account, please click on the following link:</p>
            <a href='solixproperties.org/verify.php?userid=$userid' class='green-button'>Verify</a>
            <p>Welcome to the solixproperties family!</p>
            <p>Warm regards,</p>
            <p>Get Started</p>
            <p>Choicy Digitals Bot</p>
            <p>Noreply</p>
        </div>
    </body>
    </html>";

    // Set additional headers if needed
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";

    // Additional headers for sender information
    // $headers .= 'From: Choicy Digitals<noreply@solixproperties.org>' . "\r\n";
    $headers .= 'Reply-To: support@choicydigitals.org' . "\r\n";
    $headers .= 'X-Mailer: PHP/' . phpversion();

    // Send the email
    return mail($to, $subject, $message, $headers);
}

// Validate user input
function validateInput($full_name, $email, $phone_number, $password, $cpassword) {
    $errors = [];

    if (empty($full_name) || empty($email) || empty($phone_number) || empty($password) || empty($cpassword)) {
        $errors[] = 'Enter all fields';
    } elseif (strlen($password) < 7) {
        $errors[] = 'Password should be at least 7 characters long';
    } elseif ($password !== $cpassword) {
        $errors[] = 'Password and Confirm Password do not match';
    }

    return $errors;
}

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = $_POST['full_name'];
    $phone_number = $_POST['phone_number'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $cpassword = $_POST['cpassword'];

    // Validate user input
    $errors = validateInput($full_name, $email, $phone_number, $password, $cpassword);

    if (!empty($errors)) {
        header('Location: ../signin.php?status=error&message=' . implode(' ', $errors));
        exit();
    }

    // Check if the email already exists
    $checkEmailQuery = "SELECT * FROM user_login WHERE email = ?";
    $checkEmailStmt = $conn->prepare($checkEmailQuery);

    if ($checkEmailStmt) {
        $checkEmailStmt->bind_param("s", $email);
        $checkEmailStmt->execute();
        $checkEmailResult = $checkEmailStmt->get_result();
        $checkEmailStmt->close();

        if ($checkEmailResult->num_rows > 0) {
            $errors[] = 'User Email already exists.';
        }

        if (!empty($errors)) {
            header('Location: ../signin.php?status=error&message=' . implode(' ', $errors));
            exit();
        }

        // Auto-generate user_id
        $userid = generateUserId();

        // Hash the password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Perform database query to insert user data (use prepared statements for security)
        $insertQuery = "INSERT INTO user_login (userid, full_name, email, phone_number, password) VALUES (?, ?, ?, ?, ?)";
        $insertStmt = $conn->prepare($insertQuery);

        if ($insertStmt) {
            $insertStmt->bind_param("sssss", $userid, $full_name, $email, $phone_number, $hashed_password);
            $insertStmt->execute();

            if ($insertStmt->error) {
                header('Location: ../signin.php?status=error&message=Error in database query: ' . $insertStmt->error);
                exit();
            }

            // Send email notification
            $subject = "Welcome to Choicy Digitals";
            sendEmailNotification($email, $full_name,$userid, $subject);

            header('Location: ../signin.php?status=success&message=Registration successful. Verify Your Email');
            exit();
        } else {
            header('Location: ../signin.php?status=error&message=Error in database query: ' . $conn->error);
            exit();
        }
    } else {
        header('Location: ../signin.php?status=error&message=Error in database query: ' . $conn->error);
        exit();
    }
} else {
    header('Location: ../signin.php?status=error&message=Invalid request');
    exit();
}

// Function to generate a random user_id and hash it using MD5
function generateUserId() {
    // Customize the logic to generate a unique user_id based on your requirements
    $randomUserId = 'OPM' . mt_rand(100000, 999999);

    // Hash the user ID using MD5
    $hashedUserId = md5($randomUserId);

    return $hashedUserId;
}
?>
