<?php
session_start();
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);

include 'koneksi.php';

$error = "";

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

    if (empty($email) || empty($password)) {
        $error = "Email dan password wajib diisi.";
    } else {
        $stmt = mysqli_prepare($conn, "SELECT username, password, is_verified FROM users WHERE email = ?");
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "s", $email);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            if ($result && mysqli_num_rows($result) > 0) {
                $row = mysqli_fetch_assoc($result);
                $username = $row['username'];
                $hashed_password = $row['password'];
                $is_verified = $row['is_verified'];

                if ($is_verified != 1) {
                    $error = "Akun Anda belum diverifikasi oleh admin. Harap tunggu verifikasi.";
                } elseif (empty($hashed_password)) {
                    $error = "Akun ini hanya dapat login menggunakan Google.";
                } elseif (password_verify($password, $hashed_password)) {
                    $_SESSION['session_username'] = $email;
                    $_SESSION['session_name'] = $username;
                    session_regenerate_id(true);
                    header("Location: dashboard_total");
                    exit();
                } else {
                    $error = "Email atau password salah.";
                }
            } else {
                $error = "Email tidak ditemukan.";
            }
            mysqli_stmt_close($stmt);
        } else {
            $error = "Kesalahan pada server: " . 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>Login 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" />
</head>

<body>
    <div class="login-container">
        <div class="login-form-section">
            <div class="login-header">
                <h1>Masuk</h1>
                <p>Silakan login 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; ?>

            <form method="POST">
                <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@gmail.com" required />
                    </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 />
                    </div>
                </div>
                <br>
                <div class="form-options">
                    <div class="remember-me">
                        <input type="checkbox" id="remember" name="remember" />
                        <label for="remember">Ingat saya</label>
                    </div>
                    <a href="#" class="forgot-password">Lupa Password?</a>
                </div>
                <button type="submit" name="submit" class="login-button">Login</button>
            </form>

            <div class="social-login">
                <h4>Daftar/login dengan</h4>
                <br>
                <div class="social-buttons">
                    <a href="#" class="social-button google"><i class="fab fa-google"></i> Google</a>
                    <a href="#" class="social-button facebook"><i class="fab fa-facebook-f"></i> Facebook</a>
                </div>
            </div>

            <div class="signup-link">
                Belum punya akun? <a href="register.php">Daftar sekarang</a>
            </div>
        </div>

        <div class="login-illustration-section">
            <div class="overlay-text">Sistem Kas Rembas</div>
            <img src="img/bg.png" alt="Ilustrasi Login" />
        </div>
    </div>

    <!-- Firebase -->
    <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>
        const firebaseConfig = {
            apiKey: "AIzaSyAOJBbEtkUOxrvdvXuJy5ia8JzLmRDx_Oo",
            authDomain: "kasrembas.firebaseapp.com",
            projectId: "kasrembas",
            storageBucket: "kasrembas.appspot.com",
            messagingSenderId: "SENDER_ID",
            appId: "APP_ID"
        };

        firebase.initializeApp(firebaseConfig);
        const provider = new firebase.auth.GoogleAuthProvider();

        document.querySelector('.google').addEventListener('click', function(e) {
            e.preventDefault();
            // Tambahkan di bagian Firebase Google login
            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,
                                photo: user.photoURL // <- Tambahan foto profil
                            })
                        })
                        .then(res => res.json())
                        .then(data => {
                            if (data.status === 'success') {
                                window.location.href = 'dashboard_total';
                            } else {
                                alert(data.message);
                            }
                        });
                })
        });
    </script>
</body>

</html>