<?php
// api/ajukan_broadcast.php
session_start();
include '../config/database.php';

// Memanggil library PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../libs/PHPMailer/src/Exception.php';
require '../libs/PHPMailer/src/PHPMailer.php';
require '../libs/PHPMailer/src/SMTP.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    echo json_encode(['status' => 'error', 'message' => 'Akses tidak sah.']);
    exit;
}

$user_id = $_SESSION['user_id'];
$email = trim(strtolower($_POST['email'] ?? ''));

// 1. Validasi Domain Email (Menggunakan strpos agar aman di semua versi PHP)
if (strpos($email, 'belajar.id') === false && strpos($email, 'guru.id') === false) {
    echo json_encode(['status' => 'error', 'message' => 'Hanya gunakan email domain belajar.id atau guru.id']);
    exit;
}

// 2. Generate OTP 6 Digit & Waktu Kedaluwarsa (15 Menit)
date_default_timezone_set('Asia/Jakarta'); // <-- Tambahkan baris ini
$otp_code = sprintf("%06d", mt_rand(1, 999999));
$otp_expiry = date('Y-m-d H:i:s', strtotime('+15 minutes'));

// 3. Simpan OTP ke Database (Status masih 'none', hanya catat email & OTP)
$stmt = $conn->prepare("UPDATE users SET email_guru = ?, otp_code = ?, otp_expiry = ? WHERE id = ?");
$stmt->bind_param("sssi", $email, $otp_code, $otp_expiry, $user_id);

if (!$stmt->execute()) {
    echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data sistem.']);
    exit;
}
$stmt->close();

// 4. Konfigurasi PHPMailer untuk Kirim Email
$mail = new PHPMailer(true);
try {
    // Pengaturan Server SMTP Gmail
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    
    // ==========================================
    // UBAH DUA BARIS DI BAWAH INI MILIK ANDA!
    $mail->Username   = 'sikawarsito.s.kom@gmail.com'; // Masukkan Gmail pengirim Anda
    $mail->Password   = 'lmzgercvsvhkogiw'; // Masukkan 16 digit App Password tanpa spasi google app
    // ==========================================
    
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    
    // --- TAMBAHKAN KODE INI UNTUK BYPASS SSL HOSTING ---
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    // ---------------------------------------------------

    // Penerima & Pengirim
    $mail->setFrom($mail->Username, 'Admin XIEQA AI');
    $mail->addAddress($email);

    // Konten Email
    $mail->isHTML(true);
    $mail->Subject = 'Kode Verifikasi Akses Broadcast - XIEQA AI';
    $mail->Body    = "
        <div style='font-family: Arial, sans-serif; max-width: 500px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
            <h2 style='color: #4285f4; text-align: center;'>XIEQA AI</h2>
            <p>Halo,</p>
            <p>Seseorang telah meminta akses untuk fitur <b>Broadcast Tugas</b> di XIEQA AI menggunakan email ini.</p>
            <p>Berikut adalah kode verifikasi OTP Anda (berlaku 15 menit):</p>
            <div style='text-align: center; margin: 20px 0;'>
                <span style='font-size: 24px; font-weight: bold; background: #f0f4f9; padding: 10px 20px; border-radius: 5px; letter-spacing: 5px;'>{$otp_code}</span>
            </div>
            <p style='font-size: 12px; color: #777;'>Jika Anda tidak merasa meminta kode ini, abaikan saja email ini.</p>
        </div>
    ";

    $mail->send();
    echo json_encode(['status' => 'success', 'message' => 'Kode OTP telah dikirim ke email Anda.']);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Gagal mengirim email: ' . $mail->ErrorInfo]);
}
?>