<?php
ob_start();
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Sertakan file koneksi database dan fungsi pengiriman email
include 'koneksi.php';
include 'send_admin_email.php'; // Pastikan path file ini benar

$error = "";
$success = "";

if (isset($_POST['submit'])) {
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validasi input
    if (empty($email) || empty($username) || empty($password)) {
        $error = "Semua field wajib diisi.";
    } elseif (strlen($password) < 8) {
        $error = "Password harus minimal 8 karakter.";
    } else {
        // Cek apakah email sudah terdaftar di database
        $stmt = mysqli_prepare($conn, "SELECT id FROM users WHERE email = ?");
        mysqli_stmt_bind_param($stmt, "s", $email);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($result && mysqli_num_rows($result) > 0) {
            $error = "Email sudah terdaftar.";
        } else {
            // Hash password dan simpan ke database dengan status 'pending' (0)
            $hashed = password_hash($password, PASSWORD_DEFAULT);
            $stmt = mysqli_prepare($conn, "INSERT INTO users (email, username, password, is_verified) VALUES (?, ?, ?, 0)");
            mysqli_stmt_bind_param($stmt, "sss", $email, $username, $hashed);

            if (mysqli_stmt_execute($stmt)) {
                // Kirim email notifikasi ke admin
                if (sendAdminNotificationEmail($email, $username)) {
                    $success = "Akun berhasil didaftarkan. Akun Anda akan diaktifkan setelah verifikasi dari admin. Silakan tunggu.";
                } else {
                    $error = "Akun berhasil didaftarkan, tetapi gagal mengirim email notifikasi ke admin. Mohon hubungi admin.";
                }
                // Hapus redirect agar tetap di halaman register dan menampilkan pesan
                // header("Location: dashboard_total");
                // exit();
            } else {
                $error = "Gagal menyimpan data. Coba lagi. Error: " . mysqli_error($conn);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Daftar Akun - Kas Rembas</title>
    <link rel="icon" href="img/logo.png" type="png" />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
    <link id="loginstyle" href="assets/css/stylelogin.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" />
    <style>
        .input-wrapper {
            position: relative;
        }

        .input-icon {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #ccc;
        }

        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #ccc;
        }

        input[type="password"] {
            padding-right: 40px;
        }
    </style>
</head>

<body>
    <div class="login-container">
        <div class="login-form-section">
            <div class="login-header">
                <h1>Daftar</h1>
                <p>Buat akun baru untuk mengakses sistem</p>
            </div>
            <?php if ($error): ?>
                <div style="color:red; margin-bottom:10px; padding: 10px; border: 1px solid red; border-radius: 5px; background-color: #ffeaea;"><?= $error ?></div>
            <?php endif; ?>
            <?php if ($success): ?>
                <div style="color:green; margin-bottom:10px; padding: 10px; border: 1px solid green; border-radius: 5px; background-color: #eafaea;"><?= $success ?></div>
            <?php endif; ?>
            <form action="register.php" method="POST">
                <div class="input-group">
                    <label for="username">Nama Pengguna</label>
                    <div class="input-wrapper">
                        <i class="fas fa-user input-icon"></i>
                        <input type="text" id="username" name="username" placeholder="Nama lengkap" required value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" />
                    </div>
                </div>
                <br>
                <div class="input-group">
                    <label for="email">Email</label>
                    <div class="input-wrapper">
                        <i class="fas fa-envelope input-icon"></i>
                        <input type="email" id="email" name="email" placeholder="contoh@domain.com" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" />
                    </div>
                </div>
                <br>
                <div class="input-group">
                    <label for="password">Password</label>
                    <div class="input-wrapper">
                        <i class="fas fa-lock input-icon"></i>
                        <input type="password" id="password" name="password" placeholder="Minimal 8 karakter" required />
                        <i class="fas fa-eye-slash toggle-password" id="togglePassword"></i>
                    </div>
                </div>
                <br>
                <button type="submit" name="submit" class="login-button">Daftar</button>
            </form>
            <div class="social-login">
                <p>atau daftar/login dengan</p>
                <div class="social-buttons">
                    <a href="#" class="social-button google" id="google-login-button"><i class="fab fa-google"></i> Google</a>
                </div>
            </div>
            <div class="signup-link">
                Sudah punya akun? <a href="login.php">Masuk sekarang</a>
            </div>
        </div>
        <div class="login-illustration-section">
            <div class="overlay-text">Sistem Kas Rembas</div>
            <img src="img/register.png" alt="Ilustrasi Login" />
        </div>
    </div>
    <script>
        const togglePassword = document.getElementById('togglePassword');
        const passwordInput = document.getElementById('password');
        togglePassword.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            this.classList.toggle('fa-eye');
            this.classList.toggle('fa-eye-slash');
        });
    </script>
    <script src="https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.1/firebase-auth-compat.js"></script>
    <script>
        // Konfigurasi Firebase Anda
        const firebaseConfig = {
            apiKey: "AIzaSyAOJBbEtkUOxrvdvXuJy5ia8JzLmRDx_Oo",
            authDomain: "kasrembas.firebaseapp.com",
            projectId: "kasrembas",
            storageBucket: "kasrembas.appspot.com",
            messagingSenderId: "SENDER_ID",
            appId: "APP_ID"
        };
        firebase.initializeApp(firebaseConfig);

        // Logika untuk login Google
        const provider = new firebase.auth.GoogleAuthProvider();
        const googleLoginButton = document.getElementById('google-login-button');

        googleLoginButton.addEventListener('click', function(e) {
            e.preventDefault(); // Mencegah navigasi default link
            firebase.auth().signInWithPopup(provider)
                .then(result => {
                    const user = result.user;
                    fetch('login_google.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                email: user.email,
                                name: user.displayName,
                                uid: user.uid
                            })
                        })
                        .then(res => res.json())
                        .then(data => {
                            if (data.status === 'success') {
                                window.location.href = 'dashboard_total';
                            } else {
                                alert('Gagal login: ' + data.message);
                            }
                        })
                        .catch(error => {
                            alert('Terjadi kesalahan saat berkomunikasi dengan server: ' + error);
                        });
                })
                .catch(error => {
                    console.error('Google Sign-In Error:', error);
                    if (error.code !== 'auth/popup-closed-by-user') {
                        alert('Gagal login dengan Google: ' + error.message);
                    }
                });
        });
    </script>
</body>

</html>