<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

// Database Connection
$host = "localhost";
$user = "root";      
$pass = "";          
$dbname = "savageboys";

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Database connection failed");
}

// Function to generate random password (alphabets + numbers)
function generateRandomPassword($length = 10) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $characters[random_int(0, strlen($characters) - 1)];
    }
    return $password;
}

// Check if accessed with referral code
$referral_from = isset($_GET['ref']) ? trim($_GET['ref']) : null;

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Collect input
    $first_name         = trim($_POST['first_name'] ?? '');
    $last_name          = trim($_POST['last_name'] ?? '');
    $phone_number       = trim($_POST['phone_number'] ?? '');
    $email              = trim($_POST['email'] ?? '');
    $account_number     = trim($_POST['account_number'] ?? '');
    $account_name       = trim($_POST['account_name'] ?? '');
    $bank_name          = trim($_POST['bank_name'] ?? '');
    $country            = trim($_POST['country'] ?? '');
    $dob                = trim($_POST['dob'] ?? '');
    $gender             = trim($_POST['gender'] ?? '');
    $state_of_residence = trim($_POST['state_of_residence'] ?? '');
    $experience         = trim($_POST['experience'] ?? '');

    // Validation
    if (
        empty($first_name) || empty($last_name) || empty($phone_number) || empty($email) ||
        empty($account_number) || empty($account_name) || empty($bank_name) ||
        empty($country) || empty($dob) || empty($gender) || empty($state_of_residence)
    ) {
        echo "<script>alert('Please fill in all required fields.'); window.history.back();</script>";
        exit;
    }

    // Generate referral code and password
    $referral_code = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
    $plain_password = generateRandomPassword(10);
    $hashed_password = password_hash($plain_password, PASSWORD_BCRYPT);

    // Save user data to database
    $stmt = $conn->prepare("INSERT INTO monosky 
        (first_name, last_name, phone_number, email, password, account_number, account_name, bank_name,
         country, dob, gender, state_of_residence, experience, referral_code, referred_by, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");

    if ($stmt) {
        $stmt->bind_param(
            "sssssssssssssss",
            $first_name,
            $last_name,
            $phone_number,
            $email,
            $hashed_password,
            $account_number,
            $account_name,
            $bank_name,
            $country,
            $dob,
            $gender,
            $state_of_residence,
            $experience,
            $referral_code,
            $referral_from
        );

        if ($stmt->execute()) {

            // Send Email
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'server371.web-hosting.com';
                $mail->SMTPAuth = true;
                $mail->Username = 'support@honeywey.org';
                $mail->Password = 'DSupport123!';
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = 465;

                $mail->setFrom('support@honeywey.org', 'ABN Realtors');
                $mail->addAddress($email, $first_name . ' ' . $last_name);
                $mail->isHTML(true);
                $mail->Subject = 'Welcome to Honeywey Realtors';
                $mail->Body = "
                    Dear {$first_name},<br><br>
                    Welcome to <strong>ABN Realtors</strong>! Kindly find below your login details:<br><br>
                    <strong>CID (USER ID):</strong> {$referral_code}<br>
                    <strong>Email:</strong> {$email}<br>
                    <strong>Password:</strong> {$plain_password}<br><br>
                    <strong>Your referral link:</strong> 
                    <a href='https://honeywey.org/{$referral_code}' target='_blank'>https://honeywey.org/{$referral_code}</a><br><br>
                    Kindly join our WhatsApp group below:<br>
                    <a href='https://chat.whatsapp.com/DoEI3IlYXllIzpsCklAKn4' target='_blank'>
                    https://chat.whatsapp.com/DoEI3IlYXllIzpsCklAKn4</a><br><br>
                    Thank you!<br><br>
                    <strong>ABN Realtors Team</strong>
                ";

                $mail->send();

                header('Location: thankyou.php?name=' . urlencode($first_name));
                exit;

            } catch (Exception $e) {
                echo "<script>alert('Registration successful, but email could not be sent.'); window.location='thankyou.php?name=" . urlencode($first_name) . "';</script>";
                exit;
            }
        } else {
            echo "<script>alert('Error saving data. Please try again.'); window.history.back();</script>";
        }
        $stmt->close();
    } else {
        echo "<script>alert('Database error occurred.'); window.history.back();</script>";
    }
}

$conn->close();
?>
