<?php
session_start();
include 'koneksi.php'; // Pastikan Anda memiliki koneksi ke database di sini

// Menyimpan hasil OTP yang baru
$hasilOtp = rand(100000, 999999);

// Cek jika form disubmit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $otp = $_POST['otp'];
    $rekening = $_POST['rekening']; // Ganti ini dengan nilai rekening yang sesuai
    $_SESSION['otp'] = $otp;

    // Validasi OTP
    if ($otp == $_SESSION['otp']) { // Pastikan ini membandingkan dengan $hasilOtp yang baru
        echo "<div class='alert success'>OTP valid! $otp</div>";

        // Simpan OTP ke database       
        //$query = "INSERT INTO otp_pjm (number, rekening, no_otp) VALUES ('6285648336734', '$rekening', '$hasilOtp')";
        $query = "INSERT INTO otp_pjm (number, rekening, no_otp)
            SELECT '6285648336734', '{$rekening}', '{$otp}'
            WHERE NOT EXISTS (
                SELECT 1 FROM otp_pjm
                WHERE rekening = '$rekening' 
           
            )
        ";
        if (mysqli_query($koneksi, $query)) {
            echo "<div class='alert success'>OTP telah disimpan ke database.</div>";
            header("location:otp_legal2.php");
        } else {
            echo "<div class='alert error'>Gagal menyimpan OTP ke database: " . mysqli_error($koneksi) . "</div>";
        }
    } else {
        echo "<div class='alert error'>OTP tidak valid, coba lagi.</div>";
    }
}
$tgl= date('Y-m-d');
// Ambil semua OTP dari tabel untuk ditampilkan
$result = mysqli_query($koneksi, "SELECT rekening,no_otp FROM otp_pjm WHERE tgl='$tgl' ");
$otpResults = [];
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $otpResults[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form OTP</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            height: 100vh;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
        }
        h2 {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin: 10px 0 5px;
            font-weight: bold;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }
        input[type="number"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }
        input[type="submit"] {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        input[type="submit"]:hover {
            background-color: #45a049;
        }
        .alert {
            padding: 10px;
            margin-top: 15px;
            border-radius: 4px;
        }
        .alert.success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .alert.error {
            background-color: #f2dede;
            color: #a94442;
        }
        table {
            margin-top: 20px;
            width: 80%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: center;
        }
        th {
            background-color: #f4f4f4;
        }
    </style>
</head>
<script>
function formatNumber(input) {
    // Menghapus semua karakter selain angka
    let value = input.value.replace(/[^0-9]/g, '');
    
    // Menambahkan pemisah ribuan
    value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    
    input.value = value;
}

function validateInput() {
    var rekening = document.getElementById('rekening').value;
    var plafond = document.getElementById('plafond').value.replace(/,/g, ''); // Menghapus pemisah ribuan untuk validasi
    var numericPlafond = parseInt(plafond); // Menggunakan parseInt untuk mendapatkan nilai numerik
    
    // Validasi panjang karakter rekening harus 13
    if (rekening.length < 13) {
        alert('Jumlah karakter rekening harus tepat 13 huruf');
        return false; // Mencegah form untuk dikirim
    }

    // Validasi panjang karakter plafon harus 13 digit
    /*if (plafond.length !== 13) {
        alert('Jumlah karakter plafon harus tepat 13 digit');
        return false; // Mencegah form untuk dikirim
    }*/
    
    // Validasi minimal dan maksimal plafon
    if (numericPlafond < 2500000 || numericPlafond > 5000000) {
        alert('Nilai plafon harus antara 5.000.000 dan 10.000.000');
        return false; // Mencegah form untuk dikirim
    }
    
    return true; // Izinkan form untuk dikirim
}
</script>




<body>
    <div class="container">
        <h2>Form OTP</h2>
        <form method="POST" action="" onsubmit="return validateInput()">
            <label for="rekening">Rekening:</label>
            <input type="text" id="rekening" name="rekening" required maxlength="13">
            <label for="Plafond">Plafond:</label>
             <input type="text" id="plafond" name="plafond" maxlength="10" required oninput="formatNumber(this)">

            <label for="otp">OTP:</label>
            <input type="text" id="otp" name="otp" value="<?php echo $hasilOtp; ?>">
            <input type="submit" value="Verifikasi">
        </form>
    </div>

    <!-- Tampilkan hasil OTP dalam tabel -->
    <table>
        <thead>
            <tr>
                <th>No</th>
                <th>Rekening</th>
                <th>OTP</th>
            </tr>
        </thead>
        <tbody>
        <?php if (!empty($otpResults)) : ?>
    <?php foreach ($otpResults as $index => $row) : ?>
        <tr>
            <td><?php echo $index + 1; ?></td>
            <td><?php echo htmlspecialchars($row['rekening']); ?></td>
            <td id="otp-<?php echo $index; ?>"><?php echo htmlspecialchars($row['no_otp']); ?></td>
            <td>
                <button onclick="copyText('otp-<?php echo $index; ?>')">Copy</button>
            </td>
        </tr>
    <?php endforeach; ?>
<?php else : ?>
    <tr>
        <td colspan="4">Data tidak ditemukan</td>
    </tr>
<?php endif; ?>
        </tbody>
    </table>
</body>
<script>
function copyText(elementId) {
    // Get the text field by dynamic ID
    var copyText = document.getElementById(elementId);

    // Create a temporary textarea element to select the text
    var textarea = document.createElement("textarea");
    textarea.value = copyText.textContent;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);

    // Alert the copied text
    alert("OTP Tercopy: " + copyText.textContent);
}
</script>


</html>
