<?php
if (!isset($_SESSION)) { session_start(); }
include 'koneksi.php'; // Pastikan file koneksi sudah benar

// Fungsi untuk membersihkan input
function clean_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Proses login
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Pastikan input form diisi
    if (!empty($_POST['nama_pengguna_anggota']) && !empty($_POST['kata_sandi_anggota'])) {
        // Ambil data dari form login dan bersihkan
        $username = clean_input($_POST['nama_pengguna_anggota']); 
        $password = clean_input($_POST['kata_sandi_anggota']);
        
        // Query untuk mencari pengguna berdasarkan username
        $query = "SELECT id_anggota, nama_pengguna_anggota, saldo_anggota, kata_sandi_anggota, status_anggota FROM anggota WHERE nama_pengguna_anggota = ?";
        
        // Gunakan prepared statement
        if ($stmt = $koneksi->prepare($query)) {
            $stmt->bind_param('s', $username);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 1) {
                // Ambil hasil query
                $row = $result->fetch_assoc();
                
                // Cek status anggota
                if ($row['status_anggota'] === 'terkunci') {
                    echo '<script>alert("Akun Anda terkunci."); window.location.href = "home";</script>';
                    exit();
                }
                
                // Verifikasi password
                if (password_verify($password, $row['kata_sandi_anggota'])) {
                    // Password benar, atur sesi
                    $_SESSION['loggedin'] = true;
                    $_SESSION['id_anggota'] = $row['id_anggota'];
                    $_SESSION['nama_pengguna_anggota'] = $row['nama_pengguna_anggota'];
                    $_SESSION['saldo_anggota'] = $row['saldo_anggota'];
                    
                    // Redirect ke halaman home setelah login berhasil
                    echo "<script>window.location.replace('" . htmlspecialchars($alamat_website) . "home');</script>";
                } else {
                    // Password salah
                    echo '<script>alert("Username atau password salah. Silakan coba lagi!"); window.location.href = "home";</script>';
                }
            } else {
                // Username tidak ditemukan
                echo '<script>alert("Username tidak ditemukan. Silakan daftar!"); window.location.href = "home";</script>';
            }
            $stmt->close();
        } else {
            echo 'Gagal menjalankan query: ' . $koneksi->error;
        }
    } else {
        echo '<script>alert("Mohon isi username dan password."); window.location.href = "home";</script>';
    }
}

// Tutup koneksi database
$koneksi->close();
?>
