<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/page_access_control.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get user details
$sql = "SELECT u.*, ur.role_name FROM users u 
        INNER JOIN user_roles ur ON u.role_id = ur.role_id 
        WHERE u.user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

$pac = new PageAccessControl($conn, $user_id);
$assigned_pages = $pac->getAssignedPages();

// Get role ID for this user
$role_id = $user['role_id'];

// Get assigned pages from database directly
$sql_assigned = "SELECT page_name FROM role_page_permissions WHERE role_id = ? ORDER BY page_name";
$stmt_assigned = $conn->prepare($sql_assigned);
$stmt_assigned->bind_param("i", $role_id);
$stmt_assigned->execute();
$db_assigned = $stmt_assigned->get_result();

$pages_from_db = [];
while ($row = $db_assigned->fetch_assoc()) {
    $pages_from_db[] = $row['page_name'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Access Control Debug</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .debug-container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        .section { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .user-info { background: #e3f2fd; }
        .assigned-pages { background: #e8f5e8; }
        .test-results { background: #fff3e0; }
        h2 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
        h3 { color: #666; }
        .page-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px; }
        .page-item { background: #f8f9fa; padding: 8px; border-radius: 4px; font-family: monospace; font-size: 12px; }
        .test-item { display: flex; justify-content: space-between; padding: 5px; border-bottom: 1px solid #eee; }
        .allowed { color: green; font-weight: bold; }
        .denied { color: red; font-weight: bold; }
        .count { font-weight: bold; color: #007bff; }
    </style>
</head>
<body>
    <div class="debug-container">
        <h1>🔍 Access Control Debug Information</h1>
        
        <div class="section user-info">
            <h2>👤 Current User Information</h2>
            <p><strong>User ID:</strong> <?php echo $user_id; ?></p>
            <p><strong>Name:</strong> <?php echo htmlspecialchars($user['full_name']); ?></p>
            <p><strong>Role:</strong> <?php echo htmlspecialchars($user['role_name']); ?></p>
            <p><strong>Role ID:</strong> <?php echo $user['role_id']; ?></p>
            <p><strong>Username:</strong> <?php echo htmlspecialchars($user['username']); ?></p>
        </div>
        
        <div class="section assigned-pages">
            <h2>📋 Assigned Pages Analysis</h2>
            
            <h3>From PageAccessControl Class (<span class="count"><?php echo count($assigned_pages); ?> pages</span>):</h3>
            <?php if (in_array('*', $assigned_pages)): ?>
                <p class="allowed">✅ SUPER ADMIN - Full Access to All Pages</p>
            <?php else: ?>
                <div class="page-list">
                    <?php foreach ($assigned_pages as $page): ?>
                        <div class="page-item"><?php echo htmlspecialchars($page); ?></div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <h3>Direct from Database (<span class="count"><?php echo count($pages_from_db); ?> pages</span>):</h3>
            <div class="page-list">
                <?php foreach ($pages_from_db as $page): ?>
                    <div class="page-item"><?php echo htmlspecialchars($page); ?></div>
                <?php endforeach; ?>
            </div>
            
            <?php if ($assigned_pages !== $pages_from_db): ?>
                <div style="background: #ffebee; padding: 10px; border-radius: 4px; margin-top: 10px;">
                    <strong>⚠️ MISMATCH DETECTED!</strong> The PageAccessControl class and direct database query return different results.
                </div>
            <?php endif; ?>
        </div>
        
        <div class="section test-results">
            <h2>🧪 Page Access Tests</h2>
            <p>Testing access to common pages for this role:</p>
            
            <?php 
            $test_pages = [
                'index.php' => 'Dashboard',
                'list_patients.php' => 'View All Patients',
                'register_patient.php' => 'Register Patient',
                'list_visits.php' => 'All Visits',
                'register_visit.php' => 'Register Visit',
                'list_consultations.php' => 'All Consultations',
                'list_lab_orders.php' => 'Lab Orders',
                'pending_lab_orders.php' => 'Pending Lab Orders',
                'enter_lab_results.php' => 'Enter Lab Results',
                'list_invoices.php' => 'All Invoices',
                'create_invoice.php' => 'Create Invoice',
                'pending_invoices.php' => 'Pending Invoices',
                'overdue_invoices.php' => 'Overdue Invoices',
                'list_payments.php' => 'All Payments',
                'record_payment.php' => 'Record Payment',
                'record_payments.php' => 'Record Payments',
                'mpesa_payments.php' => 'MPesa Payments',
                'payment_reports.php' => 'Payment Reports',
                'list_users.php' => 'View All Users',
                'add_user.php' => 'Add User',
                'access_control.php' => 'Access Control',
                'profile.php' => 'My Profile',
                'logout.php' => 'Logout'
            ];
            
            foreach ($test_pages as $page => $title): 
                $hasAccess = $pac->hasPageAccess($page);
            ?>
                <div class="test-item">
                    <span><?php echo htmlspecialchars($title); ?> (<?php echo $page; ?>)</span>
                    <span class="<?php echo $hasAccess ? 'allowed' : 'denied'; ?>">
                        <?php echo $hasAccess ? '✅ ALLOWED' : '❌ DENIED'; ?>
                    </span>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="section">
            <h2>🛠️ Troubleshooting Steps</h2>
            <ol>
                <li><strong>Check Database Connection:</strong> Verify role_page_permissions table exists and has data</li>
                <li><strong>Verify Role Assignment:</strong> Ensure user has correct role_id in users table</li>
                <li><strong>Check Page Assignment:</strong> Use Page & Role Assignment tool to verify assignments</li>
                <li><strong>Clear Browser Cache:</strong> Refresh the page and clear browser cache</li>
                <li><strong>Check Session:</strong> Ensure session is properly maintained</li>
            </ol>
        </div>
        
        <div class="section">
            <h2>📊 Database Queries for Verification</h2>
            <h3>Check User Role:</h3>
            <code style="background: #f5f5f5; padding: 10px; display: block; margin: 10px 0;">
                SELECT u.user_id, u.full_name, u.role_id, ur.role_name 
                FROM users u 
                JOIN user_roles ur ON u.role_id = ur.role_id 
                WHERE u.user_id = <?php echo $user_id; ?>;
            </code>
            
            <h3>Check Assigned Pages:</h3>
            <code style="background: #f5f5f5; padding: 10px; display: block; margin: 10px 0;">
                SELECT page_name 
                FROM role_page_permissions 
                WHERE role_id = <?php echo $user['role_id']; ?> 
                ORDER BY page_name;
            </code>
            
            <h3>Check All Role Assignments:</h3>
            <code style="background: #f5f5f5; padding: 10px; display: block; margin: 10px 0;">
                SELECT ur.role_name, COUNT(rpp.page_name) as page_count
                FROM user_roles ur 
                LEFT JOIN role_page_permissions rpp ON ur.role_id = rpp.role_id
                GROUP BY ur.role_id, ur.role_name
                ORDER BY ur.role_name;
            </code>
        </div>
        
        <div style="text-align: center; margin: 20px 0;">
            <a href="index.php" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">← Back to Dashboard</a>
            <a href="access_control.php" style="background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-left: 10px;">→ Page Assignment Tool</a>
        </div>
    </div>
</body>
</html>