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

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

    if (empty($email) || empty($password)) {
        echo "<script>alert('Email dan Password harus diisi!'); window.location.href='login.php';</script>";
        exit();
    }

    $query = "SELECT * FROM users WHERE email = '$email'";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);

        if ($password == $user['password']) {
            $_SESSION['id'] = $user['id_user'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['email'] = $user['email'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['status'] = "login";

            if ($user['role'] == 'admin') {
                echo "<script>alert('Login Berhasil! Selamat datang Admin.'); window.location.href='dashboard.php';</script>";
            } elseif ($user['role'] == 'apoteker') {
                echo "<script>alert('Login Berhasil! Selamat datang Apoteker " . $user['username'] . "'); window.location.href='dashboardapoteker.php';</script>";
            } elseif ($user['role'] == 'petugas') {
                echo "<script>alert('Login Berhasil! Selamat datang Petugas " . $user['username'] . "'); window.location.href='dashboardpetugas.php';</script>";
            } elseif ($user['role'] == 'kepala_puskesmas') {
                echo "<script>alert('Login Berhasil! Selamat datang Kepala Puskesmas " . $user['username'] . "'); window.location.href='dashboardkepala_puskesmas.php';</script>";
            } else {
                echo "<script>alert('Role tidak dikenali!'); window.location.href='login.php';</script>";
            }
        } else {
            echo "<script>alert('Password salah!'); window.location.href='login.php';</script>";
        }
    } else {
        echo "<script>alert('Email tidak terdaftar!'); window.location.href='login.php';</script>";
    }
} else {
    header("Location: login.php");
    exit();
}
?>