<?php
session_start();
include 'includes/config.php';

$error = '';

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

    if (empty($no_ic) || empty($password)) {
        $error = "Sila isi No Kad Pengenalan dan Kata Laluan.";
    } else {
        // Cari admin ikut no_ic
        $sql = "SELECT * FROM admin WHERE no_ic = ? LIMIT 1";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "s", $no_ic);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        if ($result && mysqli_num_rows($result) == 1) {
            $row = mysqli_fetch_assoc($result);

            // Semak password hash
            if (password_verify($password, $row['password'])) {
                // Set session admin
                $_SESSION['id_admin'] = $row['id'];
                $_SESSION['nama'] = $row['nama'];
                $_SESSION['no_ic'] = $row['no_ic'];
                $_SESSION['jawatan'] = $row['jawatan'];
                $_SESSION['jenis_admin'] = $row['jenis_admin'];

                // Redirect ke dashboard admin
                header('Location: dashboard_admin.php');
                exit;
            } else {
                $error = "Kata laluan salah.";
            }
        } else {
            $error = "No Kad Pengenalan tidak ditemui.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Login Admin - e-SPEKTRA</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="background:#f4f6f9;">

<div class="container d-flex justify-content-center align-items-center" style="height:100vh;">
    <div class="card p-4 shadow" style="width: 360px;">
        <h3 class="mb-3 text-center">Login Admin</h3>

        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="post" action="">
            <div class="mb-3">
                <label for="no_ic" class="form-label">No Kad Pengenalan</label>
                <input type="text" id="no_ic" name="no_ic" class="form-control" required autofocus />
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Kata Laluan</label>
                <input type="password" id="password" name="password" class="form-control" required />
            </div>
            <button type="submit" class="btn btn-primary w-100">Log Masuk</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
