<?php
/**
 * Email/createacc.php - BUG FIXED + SMTP FROM DB VERSION
 * Changes:
 * 1. SMTP settings loaded from admin_settings table
 * 2. Proper escaping for email query
 */
include dirname(__DIR__) . '/konak.php';

// Load SMTP settings from admin panel
function loadSmtpSettings($koneksi) {
    $settings = [];
    $q = mysqli_query($koneksi, "SELECT setting_key, setting_value FROM admin_settings");
    if ($q) while ($row = mysqli_fetch_assoc($q)) $settings[$row['setting_key']] = $row['setting_value'];
    return $settings;
}

if (isset($_POST['email'])) {
    $usermail = trim($_POST['email']);
    $usermail = strip_tags(htmlspecialchars($usermail, ENT_QUOTES, 'UTF-8'));

    if (filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
        $esEmail = mysqli_real_escape_string($koneksi, $usermail);
        $cekuser = mysqli_query($koneksi, "SELECT username FROM user_id WHERE email='$esEmail'");

        if ($cekuser && mysqli_num_rows($cekuser) > 0) {
            $userrow = mysqli_fetch_assoc($cekuser);

            $smtp = loadSmtpSettings($koneksi);
            $mailerPath = __DIR__ . '/PHPMailer/';
            require_once $mailerPath . 'PHPMailer.php';
            require_once $mailerPath . 'SMTP.php';
            require_once $mailerPath . 'Exception.php';

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

            try {
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                $mail->Host       = !empty($smtp['smtp_host'])     ? $smtp['smtp_host']     : 'smtp.gmail.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = !empty($smtp['smtp_username'])  ? $smtp['smtp_username']  : '';
                $mail->Password   = !empty($smtp['smtp_password'])  ? $smtp['smtp_password']  : '';
                $enc = !empty($smtp['smtp_encryption']) ? $smtp['smtp_encryption'] : 'tls';
                $mail->SMTPSecure = $enc === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
                $mail->Port       = !empty($smtp['smtp_port']) ? (int)$smtp['smtp_port'] : 587;

                $fromEmail = !empty($smtp['smtp_from_email']) ? $smtp['smtp_from_email'] : $mail->Username;
                $fromName  = !empty($smtp['smtp_from_name'])  ? $smtp['smtp_from_name']  : 'System';
                $siteName  = !empty($smtp['site_name'])       ? $smtp['site_name']       : 'System';

                $mail->setFrom($fromEmail, $fromName);
                $mail->addAddress($usermail);
                $mail->isHTML(true);
                $mail->Subject = 'Welcome to ' . $siteName . ' - Account Created';
                $mail->Body = '
                <html><head><style>
                  body { font-family: Arial, sans-serif; background: #f9f9f9; }
                  .container { background: #fff; padding: 30px; border-radius: 10px; max-width: 500px; margin: 20px auto; border: 1px solid #e5e7eb; }
                  h2 { color: #333; } p { color: #666; }
                  .btn { display: inline-block; background: #6366f1; color: #fff !important; text-decoration: none; padding: 12px 24px; border-radius: 6px; }
                </style></head><body>
                <div class="container">
                  <h2>Welcome to ' . htmlspecialchars($siteName) . '!</h2>
                  <p>Hello <strong>' . htmlspecialchars($userrow['username']) . '</strong>,</p>
                  <p>Your account has been successfully created. You can now log in and start using our services.</p>
                  <p><a href="#" class="btn">Go to Dashboard</a></p>
                </div>
                </body></html>';

                $mail->send();
                echo "Email telah dikirim ke $usermail";
            } catch (Exception $e) {
                echo "Pesan tidak dapat dikirim. Mailer Error: {$mail->ErrorInfo}";
            }
        } else {
            echo "Email tidak ditemukan";
        }
    } else {
        echo "Email tidak valid";
    }
} else {
    echo "filed";
}
