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

if (isset($_COOKIE['remember_username'])) {
    $_SESSION['login'] = 1;
    $_SESSION['Name'] = $_COOKIE['remember_username'];
    header("Location: dashboard/dashboard.php");
    exit();
}

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

    if (empty($username) || empty($password)) {
        echo "Username dan Password tidak boleh kosong."; 
        session_destroy();
    } else {
        $stmt = $conn->prepare("
            SELECT u.username, u.password, u.nama_lengkap, r.role_name
            FROM users u
            JOIN roles r ON u.role_id = r.role_id
            WHERE u.username = ?
        ");

        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();

            if (md5($password) === $user['password']) {
                $_SESSION['login'] = 1;
                $_SESSION['Name'] = $user['username'];
                $_SESSION['FullName'] = $user['nama_lengkap'];
                $_SESSION['Role'] = $user['role_name'];

                if (isset($_POST['remember'])) {
                    setcookie("remember_username", $user['username'], time() + (86400 * 30), "/");
                    setcookie("remember", "1", time() + (86400 * 30), "/");
                    setcookie("remember_fullname", $user['nama_lengkap'], time() + (86400 * 30), "/");
                    setcookie("remember_role", $user['role_name'], time() + (86400 * 30), "/");

                } else {
                    setcookie("remember_username", "", time() - 3600, "/");
                    setcookie("remember", "", time() - 3600, "/");
                    setcookie("remember_fullname", "", time() - 3600, "/");
                    setcookie("remember_role", "", time() - 3600, "/");

                }

                header("Location: dashboard/dashboard.php");
                exit();
            } else {
                header("Location: loginGagal.php");
                exit();
            }
        } else {
            header("Location: loginGagal.php");
                exit();
        }

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