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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = trim($_POST['username']);
    $password = $_POST['password'];

    // Validasi input kosong
    if (empty($email) || empty($password)) {
        $_SESSION['error'] = "Email dan Kata Sandi harus diisi!";
        header("Location: ../login");
        exit();
    }

    // Cek apakah email terdaftar dan ambil status
    $stmt = $conn->prepare("SELECT id_user, nama_lengkap, password, role, status FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id_user, $nama_lengkap, $hashed_password, $role, $status);
        $stmt->fetch();

        // Cek apakah status user "active"
        if ($status !== "active") {
            $_SESSION['error'] = "Akun Anda dinonaktifkan. Silakan hubungi admin.";
            header("Location: ../login");
            exit();
        }

        // Verifikasi password
        if (password_verify($password, $hashed_password)) {
            $_SESSION['user_id'] = $id_user;
            $_SESSION['nama_lengkap'] = $nama_lengkap;
            $_SESSION['role'] = $role;

            // Jika "Ingatkan Saya" dicentang, simpan cookie selama 30 hari
            if (isset($_POST['remember'])) {
                setcookie("user_email", $email, time() + (30 * 24 * 60 * 60), "/");
            }

            $_SESSION['success'] = "Masuk berhasil! Selamat datang, $nama_lengkap.";

            // Arahkan berdasarkan role
            if ($role === 'admin') {
                header("Location: ../admin/");
            } else {
                header("Location: ../users/");
            }
            exit();
        } else {
            $_SESSION['error'] = "Email / Kata Sandi salah!";
        }
    } else {
        $_SESSION['error'] = "Email / Kata Sandi salah!";
    }

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

    header("Location: ../login");
    exit();
}
