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

$fname = '';
$lname = '';

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $stmt = $conn->prepare("SELECT fname, lname FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($fname, $lname);
    $stmt->fetch();
    $stmt->close();
}

// Fetch all categories from the database
$categories = [];
$result = $conn->query("SELECT name, slug, image FROM categories");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="css/style.css" rel="stylesheet">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">
<title>DSGN</title>
</head>
<body>
    <header>
        <img src="img/logo.png" alt="Logo" class="logo">
        <?php if (isset($_SESSION['user_id'])): ?>
            <button type="button" class="btn" id="navbtn" onclick="window.location.href='profile.php'">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-person-fill" viewBox="0 0 16 16">
                    <path d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/>
                </svg>
            </button>
        <?php else: ?>
            <button type="button" class="btn" id="loginbtn" onclick="window.location.href='login.html'">Login</button>
        <?php endif; ?>
    </header>
    <div class="d-grid gap-2 col-6 mx-auto" style="padding: 10px;">
        <?php if (isset($_SESSION['user_id'])): ?>
            <h1>Welcome to DSGN, <?php echo htmlspecialchars($fname . ' ' . $lname); ?>!</h1>
        <?php else: ?>
            <h1>Welcome to DSGN!</h1>
        <?php endif; ?>
    </div>
    <div class="category_grid">
        <?php foreach ($categories as $cat): ?>
            <div class="category_container">
                <img src="img/<?php echo htmlspecialchars($cat['image']); ?>" 
                    alt="<?php echo htmlspecialchars($cat['name']); ?>" 
                    class="category_image" 
                    onclick="window.location.href='category.php?slug=<?php echo htmlspecialchars($cat['slug']); ?>'">
                <button class="category_name" 
                    onclick="window.location.href='category.php?slug=<?php echo htmlspecialchars($cat['slug']); ?>'">
                    <?php echo htmlspecialchars($cat['name']); ?>
                </button>
            </div>
        <?php endforeach; ?>
    </div>
<script src="js/script.js"></script>
</body>
</html>