<?php
require_once 'connection.php';
require_once 'sendmail_verify.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (empty($_POST['email'])) {
        $_SESSION['status'] = "danger, Email harus diisi.";
        header('Location: verify_ulang.php');
        exit;
    }

    $email = mysqli_real_escape_string($conn, $_POST['email']);

    $query = "SELECT * FROM tb_akun WHERE email = '$email' LIMIT 1";
    $sql = mysqli_query($conn, $query);

    if ($sql && mysqli_num_rows($sql) > 0) {
        $result = mysqli_fetch_assoc($sql);

        if ($result['status'] == 1) {
            $_SESSION['status'] = "info, Akun sudah diverifikasi. Silakan login.";
            header('Location: index.php');
            exit;
        }

        // Buat OTP baru
        $otp_code = rand(100000, 999999);
        $otp_expired = date("Y-m-d H:i:s", strtotime("+5 minutes"));

        $update = "UPDATE tb_akun SET otp_code = '$otp_code', otp_expired = '$otp_expired' WHERE email = '$email'";
        if (mysqli_query($conn, $update)) {

            $email_template = "
                <h2>Permintaan OTP Baru</h2>
                <p>Kode OTP baru Anda adalah:</p>
                <h1 style='color:#2e6c80;'>$otp_code</h1>
                <p>Kode ini berlaku selama 5 menit.</p>
                <p>Jika Anda tidak meminta OTP ini, silakan abaikan email ini.</p>
            ";

            $email_sent = sendmail_verify($email, $otp_code, $email_template);

            if ($email_sent === true) {
                $_SESSION['email'] = $email;
                $_SESSION['status'] = "success, Kode OTP baru telah dikirim ke email.";
                header('Location: otp.php');
                exit;
            } else {
                $_SESSION['status'] = "danger, Gagal mengirim email: $email_sent";
                header('Location: verify_ulang.php');
                exit;
            }

        } else {
            $_SESSION['status'] = "danger, Gagal memperbarui OTP.";
            header('Location: verify_ulang.php');
            exit;
        }

    } else {
        $_SESSION['status'] = "danger, Email tidak ditemukan.";
        header('Location: verify_ulang.php');
        exit;
    }
}
?>
