<?php
/**
 * send_otp.php - BUG FIXED + SMTP FROM DB VERSION
 * Changes:
 * 1. SMTP settings now loaded from admin_settings table (set via Admin Panel)
 * 2. Falls back to old hardcoded values if DB settings not available
 * 3. Better error handling
 */
include 'anti.php';
include 'konak.php';
date_default_timezone_set('Asia/Jakarta');

// Load SMTP settings from admin_settings table
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 = anti_injection($_POST['email']);

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

        if (mysqli_num_rows($cekuser) > 0) {
            $userrow  = mysqli_fetch_assoc($cekuser);
            $usercode = rand(100000, 999999);

            // Store OTP (optional: save to DB for verification)
            // mysqli_query($koneksi, "UPDATE user_id SET otp='$usercode' WHERE email='$esEmail'");

            // Load SMTP from admin panel settings
            $smtp = loadSmtpSettings($koneksi);

            $mailerPath = __DIR__ . '/Email/PHPMailer/';
            require_once $mailerPath . 'PHPMailer.php';
            require_once $mailerPath . 'SMTP.php';
            require_once $mailerPath . 'Exception.php';

            use PHPMailer\PHPMailer\PHPMailer;
            use PHPMailer\PHPMailer\SMTP;
            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 = 'Password Recovery - ' . $siteName;
                $mail->Body = '
                <html><head>
                <style>
                  body { font-family: Arial, sans-serif; background-color: #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; }
                  .otp { font-size: 32px; font-weight: bold; color: #6366f1; letter-spacing: 6px; text-align: center; padding: 16px; background: #eef2ff; border-radius: 8px; margin: 20px 0; }
                </style>
                </head><body>
                <div class="container">
                  <h2>Password Recovery</h2>
                  <p>Hello <strong>' . htmlspecialchars($userrow['username']) . '</strong>, your OTP code is:</p>
                  <div class="otp">' . $usercode . '</div>
                  <p style="color:#999;font-size:13px">This code is valid for 10 minutes. Do not share it with anyone.</p>
                </div>
                </body></html>';

                $mail->send();
                echo "done";
            } catch (Exception $e) {
                echo "fail: " . $mail->ErrorInfo;
            }
        } else {
            echo "notfound";
        }
    } else {
        echo "filed";
    }
} else {
    echo "filed";
}
