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

// Check if the user is logged in and has the correct role (manager or admin)
if (!isset($_SESSION['user_id']) || ($_SESSION['role_id'] != 1 && $_SESSION['role_id'] != 2)) {
    header("Location: ../login.php");
    exit();
}

// Fetch user details (either admin or manager)
$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

// Fetch user info (manager or admin)
$user_sql = "SELECT first_name, last_name FROM users WHERE id = ?";
$user_stmt = $conn->prepare($user_sql);
if ($user_stmt === false) {
    die('MySQL prepare error: ' . $conn->error);
}
$user_stmt->bind_param("i", $user_id);
$user_stmt->execute();
$user_result = $user_stmt->get_result();
$user = $user_result->fetch_assoc();

// Fetch store details (only for managers)
$store_id = $_SESSION['store_id'] ?? null;
$store = null;
if ($store_id) {
    $store_sql = "SELECT store_name, store_address FROM stores WHERE id = ?";
    $store_stmt = $conn->prepare($store_sql);
    if ($store_stmt === false) {
        die('MySQL prepare error: ' . $conn->error);
    }
    $store_stmt->bind_param("i", $store_id);
    $store_stmt->execute();
    $store_result = $store_stmt->get_result();
    $store = $store_result->fetch_assoc();
}

// Check if manager and store are found
if (!$user || ($store_id && !$store)) {
    die('User or store data not found.');
}
?>
<link rel="stylesheet" href="../../includes/styles.css">

<header class="dashboard-header">
    <div><i class="fas fa-user-circle"></i> Welcome, 
        <?php 
            // Display the user's name
            echo isset($user) ? htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) : 'Manager'; 
        ?>
    </div>

    <?php if (isset($store) && $store): ?>
        <div><i class="fas fa-store"></i> <strong>Store:</strong> <?php echo htmlspecialchars($store['store_name']); ?></div>
        <div><i class="fas fa-map-marker-alt"></i> <strong>Location:</strong> <?php echo htmlspecialchars($store['store_address']); ?></div>
    <?php else: ?>
        <div><i class="fas fa-store"></i> <strong>Store:</strong> Not Assigned</div>
    <?php endif; ?>

    <div><i class="fas fa-calendar-alt"></i> <strong>Date:</strong> <?php echo date('d M Y, H:i'); ?></div>
    
    <div style="display: flex; gap: 10px; justify-content: flex-end;">
        <a href="../logout.php" style="color: white; text-decoration: none;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</header>
