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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    if ($password !== $confirm_password) {
        $_SESSION['error'] = "Password dan konfirmasi tidak cocok!";
        header('Location: daftar.php');
        exit;
    }

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

    if ($result) {
        $_SESSION['error'] = "Email sudah digunakan!";
        header('Location: daftar.php');
        exit;
    }

    // Buat OTP 6 digit dan waktu kadaluarsa (5 menit)
    $otp_code = rand(100000, 999999);
    $otp_expired = date("Y-m-d H:i:s", strtotime("+5 minutes"));
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    $insert_query = "INSERT INTO tb_akun (email, password, otp_code, otp_expired, status) 
                     VALUES ('$email', '$hashed_password', '$otp_code', '$otp_expired', 0)";
    
    if (mysqli_query($conn, $insert_query)) {
        // Kirim OTP ke email
        $email_template = "
            <h2>Verifikasi Akun Anda</h2>
            <p>Masukkan kode OTP berikut ke halaman verifikasi:</p>
            <h3>$otp_code</h3>
            <p>Kode ini berlaku selama 5 menit.</p>
        ";

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


        $_SESSION['email'] = $email;
        $_SESSION['status'] = "warning, Kode OTP telah dikirim ke email Anda.";
        header('Location: otp.php');
        exit;
    } else {
        $_SESSION['error'] = "Gagal mendaftarkan akun. " . mysqli_error($conn);
        header('Location: daftar.php');
        exit;
    }
}
?>
