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

require_once '../config/db.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once '../../vendor/autoload.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username       = mysqli_real_escape_string($conn, $_POST['username']);
    $phone          = mysqli_real_escape_string($conn, $_POST['phone']);
    $email          = mysqli_real_escape_string($conn, $_POST['email']);
    $plain_password = $_POST['password'];
    $password       = $plain_password;
    $referral       = mysqli_real_escape_string($conn, $_POST['referral_id'] ?? '');

    $account_id = generateUniqueAccountId($conn);
    $wallet = 'WEB_' . $account_id . '_' . time();

    // Email duplicate check
   

    // Insert user
    $sql = "INSERT INTO users 
        (account_id, name, email, mobile, wallet, password, referral_id, balance, created_at) 
        VALUES 
        ('$account_id', '$username', '$email', '$phone', '$wallet', '$password', '$referral', 0.00, NOW())";

    if (mysqli_query($conn, $sql)) {

        // 10 Free Coins
        $checkIncome = mysqli_query($conn, "SELECT id FROM incomes WHERE wallet = '$wallet'");
        if (mysqli_num_rows($checkIncome) == 0) {
            $sqlIncome = "INSERT INTO incomes (wallet, leocxx_coin) VALUES ('$wallet', 10.00)";
            mysqli_query($conn, $sqlIncome);
        }

        // Email Send
        sendWelcomeEmail($email, $username, $account_id, $plain_password);

        echo "Success:" . $account_id;

    } else {
        echo "DB Error: " . mysqli_error($conn);
    }
}

// ==========================================
// EMAIL FUNCTION
// ==========================================
function sendWelcomeEmail($toEmail, $name, $accountId, $password) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'sadhnasaini085@gmail.com';
        $mail->Password   = 'uysm wnwf dxyp wisd';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('sadhnasaini085@gmail.com', 'EarnPerDay');
        $mail->addAddress($toEmail, $name);

        $mail->isHTML(true);
        $mail->Subject = '🎉 Welcome to EARNPERDAY— Your Account Details';
        $mail->Body    = getEmailTemplate($name, $accountId, $password);
        $mail->AltBody = "Welcome $name! Your Account ID: $accountId | Password: $password";

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email Error: " . $mail->ErrorInfo);
        return false;
    }
}

// ==========================================
// EMAIL HTML TEMPLATE
// ==========================================
function getEmailTemplate($name, $accountId, $password) {
    return '
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <style>
        body { margin: 0; padding: 0; background: #030712; font-family: Arial, sans-serif; }
        .wrapper { max-width: 560px; margin: 30px auto; background: #0f172a; border-radius: 16px; overflow: hidden; border: 1px solid rgba(34,211,238,0.2); }
        .header { background: linear-gradient(135deg, #0f172a, #1e293b); padding: 36px 30px; text-align: center; border-bottom: 1px solid rgba(34,211,238,0.15); }
        .logo { font-size: 26px; font-weight: 900; letter-spacing: 4px; color: #22d3ee; }
        .header p { color: #64748b; font-size: 13px; margin-top: 6px; }
        .body { padding: 36px 30px; }
        .greeting { color: #ffffff; font-size: 20px; font-weight: 700; margin-bottom: 12px; }
        .desc { color: #94a3b8; font-size: 14px; line-height: 1.7; margin-bottom: 28px; }
        .info-box { background: rgba(34,211,238,0.05); border: 1px solid rgba(34,211,238,0.2); border-radius: 12px; padding: 20px 24px; margin-bottom: 24px; }
        .info-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .info-row:last-child { border-bottom: none; }
        .info-label { color: #64748b; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; }
        .info-value { color: #22d3ee; font-size: 16px; font-weight: 700; font-family: monospace; letter-spacing: 2px; }
        .warn { background: rgba(251,191,36,0.08); border: 1px solid rgba(251,191,36,0.2); border-radius: 10px; padding: 14px 18px; color: #fbbf24; font-size: 13px; margin-bottom: 28px; }
        .btn { display: block; width: fit-content; margin: 0 auto; background: #22d3ee; color: #000; padding: 14px 36px; border-radius: 10px; text-decoration: none; font-weight: 800; font-size: 14px; letter-spacing: 1px; }
        .footer { background: #020617; padding: 20px 30px; text-align: center; color: #334155; font-size: 12px; border-top: 1px solid rgba(255,255,255,0.05); }
    </style>
    </head>
    <body>
    <div class="wrapper">
        <div class="header">
            <div class="logo">EARNPERDAY</div>
            <p>Next Generation Web3 Network</p>
        </div>
        <div class="body">
            <p class="greeting">Welcome, ' . htmlspecialchars($name) . '! 🎉</p>
            <p class="desc">Your account has been successfully created. Below are your login credentials. Please save them in a safe place.</p>
            
            <div class="info-box">
                <div class="info-row">
                    <span class="info-label">Account ID</span>
                    <span class="info-value">' . $accountId . '</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Password</span>
                    <span class="info-value">' . htmlspecialchars($password) . '</span>
                </div>
            </div>

            <div class="warn">
                ⚠️ <strong>Important:</strong> Never share your Account ID and Password with anyone. EARNPERDAY team will never ask for your credentials.
            </div>

            <a href="https://earnperday.live/frontend/login.html" class="btn">LOGIN TO DASHBOARD →</a>
        </div>
        <div class="footer">
            © 2025 Smart Flow fX. All rights reserved.<br>
            If you did not register, please ignore this email.
        </div>
    </div>
    </body>
    </html>
    ';
}

// ==========================================
// HELPER FUNCTIONS
// ==========================================
function generateAccountId() {
    return strval(rand(100000, 999999));
}

function generateUniqueAccountId($conn) {
    do {
        $id = generateAccountId();
        $check = mysqli_query($conn, "SELECT id FROM users WHERE account_id='$id'");
    } while (mysqli_num_rows($check) > 0);
    return $id;
}
?>