<?php
session_start();
require 'koneksi.php';

// Ambil data dari form
$user = $_POST['username'] ?? '';
$pass = $_POST['password'] ?? '';

// Validasi awal
if (empty($user) || empty($pass)) {
    echo "<script>alert('Username dan Password wajib diisi'); window.location='index.php';</script>";
    exit();
}

// Cek data masyarakat berdasarkan username
$stmt = $conn->prepare("SELECT * FROM masyarakat WHERE username = ?");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();

// Cek apakah username ditemukan
if ($result->num_rows > 0) {
    $data = $result->fetch_assoc();

    // Verifikasi password
    if ($pass === $data['password']) {
    $_SESSION['nama'] = $data['nama'];
    $_SESSION['nik'] = $data['nik'];
    header('Location: masyarakat.php');
    exit();
} else {
    echo "<script>alert('Password salah'); window.location='index.php';</script>";
}

} else {
    echo "<script>alert('Username tidak ditemukan'); window.location='index.php';</script>";
}

$stmt->close();
$conn->close();
?>
