<?php
// STEP 1: START THE SESSION
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// STEP 2: INCLUDE THE DATABASE CONNECTION
require_once __DIR__ . '/../includes/db.php';

// STEP 3: INCLUDE HELPER FUNCTIONS
require_once __DIR__ . '/../includes/helpers.php';

// STEP 4: SECURITY CHECK - REDIRECT GUESTS
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// STEP 5: FETCH LOGGED-IN USER DATA
$user_id = $_SESSION['user_id'];
$user_name = 'Customer'; // Default value
// (Code to fetch user's full name remains here)
if ($stmt = $conn->prepare("SELECT full_name FROM users WHERE id = ?")) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $user_result = $stmt->get_result()->fetch_assoc();
    if ($user_result) {
        $user_name = $user_result['full_name'];
    }
    $stmt->close();
}


// --- NEW CODE BLOCK TO FIX THE ERROR ---
// STEP 6: FETCH UNREAD MESSAGE COUNT FOR THE HEADER BADGE
$unread_messages_count = 0;
if ($stmt = $conn->prepare("SELECT COUNT(id) as total FROM messages WHERE user_id = ? AND is_read = 0")) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $unread_messages_count = $result['total'] ?? 0;
    $stmt->close();
}
