<?php
require_once "../setting/database.php";

$username = $nomor = $password = "";
$username_err = $nomor_err = $password_err = "";

// Memproses data saat form dikirim
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Validasi username
    if(empty(trim($_POST["username"]))){
        $username_err = "Silakan masukkan username.";
    } else {
        $sql = "SELECT id FROM users WHERE username = ?";
        if($stmt = mysqli_prepare($link, $sql)){
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            $param_username = trim($_POST["username"]);
            if(mysqli_stmt_execute($stmt)){
                mysqli_stmt_store_result($stmt);
                if(mysqli_stmt_num_rows($stmt) == 1){
                    $username_err = "Username ini sudah digunakan.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } else{
                echo "Oops! Terjadi kesalahan. Silakan coba lagi nanti.";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // Validasi nomor telepon
    if(empty(trim($_POST["nomor"]))){
        $nomor_err = "Silakan masukkan nomor telepon Anda.";
    } else{
        $nomor = trim($_POST["nomor"]);
    }

    // Validasi password
    if(empty(trim($_POST["password"]))){
        $password_err = "Silakan masukkan password.";
    } elseif(strlen(trim($_POST["password"])) < 6){
        $password_err = "Password minimal harus 6 karakter.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Cek error sebelum memasukkan data ke database
    if(empty($username_err) && empty($nomor_err) && empty($password_err)){
        $sql = "INSERT INTO users (username, nomor, password, apikey, masa_aktif, limit_user) VALUES (?, ?, ?, ?, ?, ?)";
        if($stmt = mysqli_prepare($link, $sql)){
            mysqli_stmt_bind_param($stmt, "sssssi", $param_username, $param_nomor, $param_password, $param_apikey, $param_masa_aktif, $param_limit);

            $param_username = $username;
            $param_nomor = $nomor;
            $param_password = password_hash($password, PASSWORD_DEFAULT);
            $param_apikey = "API-" . bin2hex(random_bytes(6)); // Generate API key unik dengan prefix
            $param_masa_aktif = date('Y-m-d', strtotime('+2 days')); // Masa aktif 2 hari
            $param_limit = 10; // Limit awal

            if(mysqli_stmt_execute($stmt)){
                // Alihkan ke halaman login setelah berhasil
                header("location: login");
            } else{
                echo "Terjadi kesalahan. Silakan coba lagi nanti.";
            }
            mysqli_stmt_close($stmt);
        }
    }
    mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Akun</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <style>
        /* CSS untuk memusatkan form */
        body, html {
            height: 100%;
        }
        .container-register {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem 0;
            min-height: 100%;
        }
        .card {
            width: 100%;
            max-width: 450px; /* Sedikit lebih lebar untuk form registrasi */
        }
    </style>
</head>
<body class="bg-light">

    <div class="container-register">
        <div class="card shadow-sm">
            <div class="card-body p-4 p-md-5">
                <h2 class="card-title text-center mb-2">Buat Akun Baru</h2>
                <p class="text-center text-muted mb-4">Isi form di bawah untuk mendaftar.</p>

                <form action="daftar" method="post" novalidate>
                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" name="username" id="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo htmlspecialchars($username); ?>">
                        <div class="invalid-feedback">
                            <?php echo $username_err; ?>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="nomor" class="form-label">Nomor Telepon</label>
                        <input type="text" name="nomor" id="nomor" class="form-control <?php echo (!empty($nomor_err)) ? 'is-invalid' : ''; ?>" value="<?php echo htmlspecialchars($nomor); ?>" placeholder="Contoh: 08123456789">
                        <div class="invalid-feedback">
                            <?php echo $nomor_err; ?>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" name="password" id="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                        <div class="invalid-feedback">
                            <?php echo $password_err; ?>
                        </div>
                    </div>
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-primary">Daftar</button>
                    </div>
                    <hr class="my-4">
                    <p class="text-center">Sudah punya akun? <a href="login">Login di sini</a>.</p>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</body>
</html>
