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

if (!isset($_SESSION['email'])) {
    header('Location: index.php');
    exit;
}

$email = $_SESSION['email'];
$input_otp = $_POST['otp'];

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

if ($result) {
    $stored_otp = $result['otp_code'];
    $expired = strtotime($result['otp_expired']);
    $now = time();

    if ($input_otp == $stored_otp) {
        if ($now <= $expired) {
            // OTP valid dan belum kadaluarsa
            $update = "UPDATE tb_akun SET status = 1, otp_code = NULL, otp_expired = NULL WHERE email = '$email'";
            if (mysqli_query($conn, $update)) {
                $_SESSION['status'] = "success, Akun berhasil diverifikasi. Silakan login.";
                session_destroy(); // keluar dulu agar bisa login ulang
                header('Location: index.php');
                exit;
            } else {
                $_SESSION['status'] = "danger, Gagal mengupdate status akun.";
                header('Location: otp.php');
                exit;
            }
        } else {
            $_SESSION['status'] = "danger, OTP telah kadaluarsa. Minta kode baru.";
            header('Location: otp.php');
            exit;
        }
    } else {
        $_SESSION['status'] = "danger, Kode OTP salah!";
        header('Location: otp.php');
        exit;
    }
} else {
    $_SESSION['status'] = "danger, Email tidak ditemukan.";
    header('Location: index.php');
    exit;
}
?>
