<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include 'koneksi.php';

$msg = "";

// =========================
// KIRIM OTP
// =========================
if(isset($_POST['kirim'])){

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

    $cek = mysqli_query($conn,
    "SELECT * FROM users WHERE no_hp='$hp'");

    if(mysqli_num_rows($cek) > 0){

        // generate OTP
        $otp = rand(100000,999999);

        mysqli_query($conn,
        "UPDATE users SET otp='$otp' WHERE no_hp='$hp'");

        // simpan hp ke session
        $_SESSION['hp_reset'] = $hp;

        // =========================
        // KIRIM WHATSAPP (FONNTE)
        // =========================
        $token = "RLbMMRQFGFvNZWQdzqhE"; // API KEY

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.fonnte.com/send",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => array(
                'target' => $hp,
                'message' => "OTP Reset Password SILAKU: $otp"
            ),
            CURLOPT_HTTPHEADER => array(
                "Authorization: $token"
            ),
        ));

        curl_exec($curl);
        curl_close($curl);

        $msg = "OTP berhasil dikirim ke WhatsApp";

    }else{
        $msg = "Nomor HP tidak ditemukan";
    }
}

// =========================
// VERIFIKASI OTP
// =========================
if(isset($_POST['verifikasi'])){

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

    $cek = mysqli_query($conn,
    "SELECT * FROM users WHERE otp='$otp_input'");

    if(mysqli_num_rows($cek) > 0){

        $_SESSION['otp_verified'] = true;

        header("Location: password_baru.php");
        exit;

    }else{
        $msg = "OTP SALAH";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reset OTP</title>
</head>
<body>

<h2>Reset Password via WhatsApp OTP</h2>

<!-- =========================
     FORM KIRIM OTP
========================= -->
<form method="POST">

    <input type="text"
    name="hp"
    placeholder="Masukkan No HP (08123456789)"
    required>

    <button name="kirim">
        Kirim OTP
    </button>

</form>

<br><br>

<!-- =========================
     FORM VERIFIKASI OTP
========================= -->
<form method="POST">

    <label>Masukkan Kode OTP</label><br>

    <input type="text"
    name="otp"
    placeholder="6 digit OTP"
    maxlength="6"
    required
    style="padding:10px;width:200px;">

    <br><br>

    <button name="verifikasi">
        Verifikasi OTP
    </button>

</form>

<p>
<?php echo $msg; ?>
</p>

</body>
</html>