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

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');

$action = $_POST['action'] ?? '';

// ==========================================
// TAHAP 1: REQUEST OTP
// ==========================================
if ($action === 'request_otp') {
    $email = trim(strtolower($_POST['email']));

    // PENTING: Sesuaikan nama kolom 'email' dengan yang ada di database Bapak (misal: email_guru)
    $stmt = $conn->prepare("SELECT id FROM users WHERE email_guru = ?"); 
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Email tidak ditemukan dalam sistem.']);
        exit;
    }
    
    $user = $result->fetch_assoc();
    $user_id = $user['id'];

    // Generate OTP & Expiry (15 Menit)
    date_default_timezone_set('Asia/Jakarta');
    $otp_code = sprintf("%06d", mt_rand(1, 999999));
    $otp_expiry = date('Y-m-d H:i:s', strtotime('+15 minutes'));

    // Simpan OTP ke DB
    $update_stmt = $conn->prepare("UPDATE users SET otp_code = ?, otp_expiry = ? WHERE id = ?");
    $update_stmt->bind_param("ssi", $otp_code, $otp_expiry, $user_id);
    $update_stmt->execute();

    // Kirim Email
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        
        // Gunakan kredensial yang sama dengan file broadcast Bapak
        $mail->Username   = 'sikawarsito.s.kom@gmail.com'; 
        $mail->Password   = 'lmzgercvsvhkogiw'; 
        
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        
        $mail->SMTPOptions = array(
            'ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)
        );

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

        $mail->isHTML(true);
        $mail->Subject = 'Kode OTP Reset Password - 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;'>Reset Password</h2>
                <p>Halo,</p>
                <p>Seseorang baru saja meminta reset password untuk akun Anda di XIEQA AI.</p>
                <p>Masukkan kode OTP berikut untuk melanjutkan proses reset:</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;'>Kode ini hangus dalam 15 menit. Jika Anda tidak merasa meminta reset password, abaikan email ini.</p>
            </div>
        ";

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

// ==========================================
// TAHAP 2: VERIFIKASI OTP & UPDATE PASSWORD
// ==========================================
if ($action === 'verify_otp') {
    $email = trim(strtolower($_POST['email']));
    $otp_input = trim($_POST['otp_code']);
    $new_password = $_POST['new_password'];

    date_default_timezone_set('Asia/Jakarta');
    $current_time = date('Y-m-d H:i:s');

    // Cek kecocokan email, OTP, dan waktu kedaluwarsa (Sesuaikan kolom 'email_guru' jika perlu)
    $stmt = $conn->prepare("SELECT id FROM users WHERE email_guru = ? AND otp_code = ? AND otp_expiry > ?");
    $stmt->bind_param("sss", $email, $otp_input, $current_time);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        // Enkripsi password baru dengan BCRYPT (Sesuai standar password_verify di login_page.php Bapak)
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        // Update password dan kosongkan kolom OTP
        $update_stmt = $conn->prepare("UPDATE users SET password = ?, otp_code = NULL, otp_expiry = NULL WHERE email_guru = ?");
        $update_stmt->bind_param("ss", $hashed_password, $email);
        
        if ($update_stmt->execute()) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui database.']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Kode OTP salah atau sudah kedaluwarsa.']);
    }
    exit;
}
?>