<?php
require_once "config.php";
session_start();

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

$permissionTable = "Zabbar_Admin_Permission";
$adminTable = "admin";

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function login_check(mysqli $conn, string $table, string $username, string $password): ?array {
    $sql = "SELECT * FROM `$table` WHERE username = ? AND password = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

if (!empty($_SESSION['auth_logged_in'])) {
    header("Location: index.php");
    exit;
}

$error = '';

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

    if ($username === '' || $password === '') {
        $error = "Username and password are required.";
    } else {
        $permissionRow = login_check($conn, $permissionTable, $username, $password);

        if ($permissionRow) {
            session_regenerate_id(true);
            $_SESSION['auth_logged_in'] = true;
            $_SESSION['auth_role'] = 'permission';
            $_SESSION['auth_username'] = $username;
            $_SESSION['auth_password'] = $password;
            $_SESSION['auth_source_table'] = $permissionTable;
            $_SESSION['auth_last_activity'] = time();

            header("Location: index.php");
            exit;
        }

        $adminRow = login_check($conn, $adminTable, $username, $password);

        if ($adminRow) {
            session_regenerate_id(true);
            $_SESSION['auth_logged_in'] = true;
            $_SESSION['auth_role'] = 'admin';
            $_SESSION['auth_username'] = $username;
            $_SESSION['auth_password'] = $password;
            $_SESSION['auth_source_table'] = $adminTable;
            $_SESSION['auth_last_activity'] = time();

            header("Location: index.php");
            exit;
        }

        $error = "Invalid username or password.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
    <style>
        :root{
            --bg:#f4f7fb;
            --card:#ffffff;
            --text:#102033;
            --muted:#5f6f82;
            --line:#dbe5f0;
            --accent:#2563eb;
            --accent2:#7c3aed;
            --shadow:0 20px 60px rgba(16,32,51,.10);
            --radius:24px;
        }
        *{box-sizing:border-box}
        body{
            margin:0;
            min-height:100vh;
            font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
            background:
                radial-gradient(circle at top left, rgba(37,99,235,.10), transparent 28%),
                radial-gradient(circle at top right, rgba(124,58,237,.08), transparent 24%),
                var(--bg);
            color:var(--text);
            display:flex;
            align-items:center;
            justify-content:center;
            padding:18px;
        }
        .card{
            width:min(460px, 100%);
            background:rgba(255,255,255,.94);
            border:1px solid var(--line);
            border-radius:var(--radius);
            box-shadow:var(--shadow);
            overflow:hidden;
            backdrop-filter: blur(12px);
        }
        .head{
            padding:24px 24px 16px;
            border-bottom:1px solid var(--line);
        }
        .brand{
            display:flex;
            align-items:center;
            gap:14px;
            margin-bottom:14px;
        }
        .logo{
            width:52px;
            height:52px;
            border-radius:18px;
            display:grid;
            place-items:center;
            color:#fff;
            font-weight:800;
            background:linear-gradient(135deg, var(--accent), var(--accent2));
            box-shadow:0 12px 28px rgba(37,99,235,.20);
            flex:0 0 auto;
        }
        h1{
            margin:0;
            font-size:22px;
            line-height:1.2;
        }
        p{
            margin:6px 0 0;
            color:var(--muted);
            font-size:13px;
        }
        .body{
            padding:24px;
        }
        .error{
            margin-bottom:16px;
            padding:12px 14px;
            border-radius:16px;
            background:#fef2f2;
            border:1px solid #fecaca;
            color:#991b1b;
            font-size:14px;
        }
        .field{
            display:flex;
            flex-direction:column;
            gap:8px;
            margin-bottom:14px;
        }
        label{
            font-size:13px;
            font-weight:700;
            color:#334155;
        }
        input{
            width:100%;
            border:1px solid var(--line);
            background:#fff;
            color:var(--text);
            border-radius:16px;
            padding:14px 15px;
            font-size:15px;
            outline:none;
            transition:.2s ease;
        }
        input:focus{
            border-color:rgba(37,99,235,.65);
            box-shadow:0 0 0 4px rgba(37,99,235,.10);
        }
        .btn{
            width:100%;
            border:none;
            border-radius:16px;
            padding:14px 16px;
            font-size:15px;
            font-weight:800;
            color:#fff;
            cursor:pointer;
            background:linear-gradient(135deg, var(--accent), var(--accent2));
            box-shadow:0 14px 28px rgba(37,99,235,.16);
            transition:.2s ease;
        }
        .btn:hover{transform:translateY(-1px)}
        .note{
            margin-top:14px;
            color:var(--muted);
            font-size:12px;
            line-height:1.6;
        }
    </style>
</head>
<body>
    <div class="card">
        <div class="head">
            <div class="brand">
                <div class="logo">Z</div>
                <div>
                    <h1>Admin Login</h1>
                    <p>Sign in to continue</p>
                </div>
            </div>
        </div>
        <div class="body">
            <?php if ($error !== ''): ?>
                <div class="error"><?= e($error) ?></div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <div class="field">
                    <label>Username</label>
                    <input type="text" name="username" required>
                </div>

                <div class="field">
                    <label>Password</label>
                    <input type="password" name="password" required>
                </div>

                <button type="submit" class="btn">Login</button>
            </form>

            <div class="note">
                Login first checks <strong>Login to access more</strong>. If no match is found, it checks <strong>Admin</strong>.
            </div>
        </div>
    </div>
</body>
</html>