<?php
// File: check_auth.php
session_start();
header('Content-Type: application/json');

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Ensure it's a GET request for security and RESTfulness
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['authenticated' => false, 'message' => 'Only GET requests are allowed.']);
    exit;
}

// Check if user_id is set in the session
if (isset($_SESSION['user_id'])) { // Only need to check user_id for existence
    require_once __DIR__ . '/db.php'; // Include DB connection here

    try {
        // Fetch full user details from DB based on session user_id
        $stmt = $pdo->prepare('SELECT id, username, email, role, name, region, department, status FROM users WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $_SESSION['user_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            // Return comprehensive user data
            echo json_encode([
                'authenticated' => true,
                'user' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'email' => $user['email'],
                    'role' => $user['role'],
                    'name' => $user['name'], // Added 'name'
                    'region' => $user['region'], // Added 'region'
                    'status' => $user['status'], // Added 'status'
                    'department' => $user['department'] // Added 'department'
                    // Add any other fields you need from the users table
                ]
            ]);
        } else {
            // Session data exists, but user not found in DB (e.g., deleted user)
            // Invalidate session for security
            session_unset();
            session_destroy();
            echo json_encode(['authenticated' => false, 'message' => 'Session invalid. User not found.']);
        }
    } catch (PDOException $e) {
        error_log("DB error during session check in check_auth.php: " . $e->getMessage());
        http_response_code(500); // Internal Server Error for DB issues
        echo json_encode(['authenticated' => false, 'message' => 'Server error during authentication check.']);
    }
} else {
    // No user ID in session, not authenticated
    echo json_encode(['authenticated' => false, 'message' => 'Not authenticated.']);
}
exit;
?>