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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Get current user details and role verification
$current_user_id = $_SESSION['user_id'];
$sql_current_user = "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_current = $conn->prepare($sql_current_user);
$stmt_current->bind_param("i", $current_user_id);
$stmt_current->execute();
$current_user = $stmt_current->get_result()->fetch_assoc();

if (!$current_user || $current_user['role_name'] !== 'Super Admin') {
    header('Location: dashboard.php');
    exit();
}

// Get target user ID from URL
$target_user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($target_user_id <= 0) {
    header('Location: list_users.php');
    exit();
}

// Handle quick actions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'reset_password':
            if ($target_user_id !== $current_user_id) {
                $new_password = 'laundry123';
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                
                $sql_reset = "UPDATE users SET password = ?, last_password_change = CURRENT_TIMESTAMP WHERE user_id = ?";
                $stmt_reset = $conn->prepare($sql_reset);
                $stmt_reset->bind_param("si", $hashed_password, $target_user_id);
                
                if ($stmt_reset->execute()) {
                    $message = "Password reset successfully! New password: $new_password";
                    $message_type = "success";
                } else {
                    $message = "Error resetting password.";
                    $message_type = "error";
                }
            }
            break;
            
        case 'toggle_status':
            if ($target_user_id !== $current_user_id) {
                $new_status = $_POST['new_status'];
                $sql_toggle = "UPDATE users SET status = ? WHERE user_id = ?";
                $stmt_toggle = $conn->prepare($sql_toggle);
                $stmt_toggle->bind_param("si", $new_status, $target_user_id);
                
                if ($stmt_toggle->execute()) {
                    $message = "User status updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating user status.";
                    $message_type = "error";
                }
            }
            break;
    }
}

// Get detailed user information
$sql_user = "SELECT 
    u.*,
    ur.role_name,
    ur.description as role_description,
    ur.is_system,
    DATEDIFF(CURRENT_DATE, DATE(u.last_login)) as days_since_login,
    DATEDIFF(CURRENT_DATE, DATE(u.created_at)) as account_age_days,
    DATEDIFF(CURRENT_DATE, DATE(u.last_password_change)) as password_age_days
FROM users u
INNER JOIN user_roles ur ON u.role_id = ur.role_id
WHERE u.user_id = ?";

$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $target_user_id);
$stmt_user->execute();
$user = $stmt_user->get_result()->fetch_assoc();

if (!$user) {
    header('Location: list_users.php');
    exit();
}

// Get user's activity statistics
$sql_activity = "SELECT 
    (SELECT COUNT(*) FROM orders WHERE created_by = ?) as orders_created,
    (SELECT COUNT(*) FROM customers WHERE created_by = ?) as customers_created,
    (SELECT COUNT(*) FROM payments WHERE processed_by = ?) as payments_processed,
    (SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE created_by = ? AND status = 'DELIVERED') as revenue_generated,
    (SELECT COUNT(*) FROM activity_log WHERE user_id = ?) as total_log_entries,
    (SELECT COUNT(*) FROM activity_log WHERE user_id = ? AND DATE(logged_at) = CURDATE()) as today_activities";

$stmt_activity = $conn->prepare($sql_activity);
$stmt_activity->bind_param("iiiiii", $target_user_id, $target_user_id, $target_user_id, $target_user_id, $target_user_id, $target_user_id);
$stmt_activity->execute();
$activity_stats = $stmt_activity->get_result()->fetch_assoc();

// Get user's recent orders
$sql_recent_orders = "SELECT 
    o.order_id,
    o.order_number,
    o.order_date,
    o.status as order_status,
    o.total_amount,
    o.total_pieces,
    c.first_name,
    c.last_name,
    c.customer_code
FROM orders o
INNER JOIN customers c ON o.customer_id = c.customer_id
WHERE o.created_by = ?
ORDER BY o.order_date DESC
LIMIT 10";

$stmt_recent_orders = $conn->prepare($sql_recent_orders);
$stmt_recent_orders->bind_param("i", $target_user_id);
$stmt_recent_orders->execute();
$recent_orders = $stmt_recent_orders->get_result();

// Get user's recent activity log
$sql_recent_activity = "SELECT 
    al.*,
    CASE 
        WHEN al.module = 'orders' AND al.action = 'CREATE' THEN CONCAT('Created order #', al.record_id)
        WHEN al.module = 'customers' AND al.action = 'CREATE' THEN CONCAT('Registered new customer')
        WHEN al.module = 'payments' AND al.action = 'CREATE' THEN CONCAT('Processed payment')
        WHEN al.action = 'LOGIN' THEN 'Logged into system'
        WHEN al.action = 'LOGOUT' THEN 'Logged out of system'
        ELSE CONCAT(al.action, ' in ', al.module)
    END as activity_description
FROM activity_log al
WHERE al.user_id = ?
ORDER BY al.logged_at DESC
LIMIT 15";

$stmt_recent_activity = $conn->prepare($sql_recent_activity);
$stmt_recent_activity->bind_param("i", $target_user_id);
$stmt_recent_activity->execute();
$recent_activity = $stmt_recent_activity->get_result();

// Get user's assigned page permissions
$sql_permissions = "SELECT 
    rpp.page_name,
    rpp.created_at as permission_granted
FROM role_page_permissions rpp
WHERE rpp.role_id = ?
ORDER BY rpp.page_name";

$stmt_permissions = $conn->prepare($sql_permissions);
$stmt_permissions->bind_param("i", $user['role_id']);
$stmt_permissions->execute();
$user_permissions = $stmt_permissions->get_result();

// Page titles mapping
$page_titles = [
    'register_customer.php' => 'Register Customer',
    'customer_search.php' => 'Customer Search',
    'list_customers.php' => 'Customer List',
    'new_order.php' => 'New Order',
    'order_status.php' => 'Order Status',
    'ready_orders.php' => 'Ready Orders',
    'pending_orders.php' => 'Pending Orders',
    'inprogress_orders.php' => 'In Progress Orders',
    'all_orders.php' => 'All Orders',
    'update_order_status.php' => 'Update Order Status',
    'order_analytics.php' => 'Order Analytics',
    'process_payment.php' => 'Process Payment',
    'generate_receipt.php' => 'Generate Receipt',
    'daily_sales.php' => 'Daily Sales',
    'list_payments.php' => 'All Payments',
    'payment_methods.php' => 'Payment Methods',
    'outstanding_bills.php' => 'Outstanding Bills',
    'list_staff.php' => 'Staff List',
    'add_staff.php' => 'Add Staff',
    'staff_performance.php' => 'Staff Performance',
    'check_supplies.php' => 'Check Supplies',
    'request_supplies.php' => 'Request Supplies',
    'inventory_management.php' => 'Inventory Management',
    'stock_management.php' => 'Stock Management',
    'suppliers.php' => 'Suppliers',
    'purchase_orders.php' => 'Purchase Orders',
    'daily_reports.php' => 'Daily Reports',
    'monthly_revenue.php' => 'Monthly Revenue',
    'daily_revenue.php' => 'Daily Revenue',
    'profit_analysis.php' => 'Profit Analysis',
    'customer_analytics.php' => 'Customer Analytics',
    'service_pricing.php' => 'Service Pricing',
    'service_types.php' => 'Service Types',
    'list_users.php' => 'All Users',
    'add_user.php' => 'Add User',
    'user_roles.php' => 'User Roles',
    'system_settings.php' => 'System Settings',
    'backup_restore.php' => 'Backup & Restore',
    'activity_logs.php' => 'Activity Logs'
];

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View User - ' . $user['full_name'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Header Section */
        .user-header {
            background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 2rem;
        }
        
        .user-profile {
            display: flex;
            align-items: center;
            gap: 1.5rem;
        }
        
        .user-avatar-large {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 2rem;
            border: 3px solid rgba(255, 255, 255, 0.3);
        }
        
        .user-info {
            flex: 1;
        }
        
        .user-name {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .user-title {
            font-size: 1.125rem;
            opacity: 0.9;
            margin-bottom: 0.5rem;
        }
        
        .user-meta {
            display: flex;
            gap: 2rem;
            flex-wrap: wrap;
            opacity: 0.8;
            font-size: 0.875rem;
        }
        
        .header-actions {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            min-width: 200px;
        }
        
        .btn-header {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
            text-align: center;
            cursor: pointer;
        }
        
        .btn-header:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* Alert Messages */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #22c55e;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        /* Content Layout */
        .content-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        /* Info Cards */
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .card-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .card-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
        }
        
        .info-grid {
            display: grid;
            gap: 1rem;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-item:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-value {
            font-weight: 600;
            color: #1e293b;
            text-align: right;
        }
        
        /* Statistics Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .stat-orders .stat-value { color: #3b82f6; }
        .stat-customers .stat-value { color: #10b981; }
        .stat-payments .stat-value { color: #f59e0b; }
        .stat-revenue .stat-value { color: #059669; }
        
        /* Status Badges */
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #f3f4f6; color: #374151; }
        .status-suspended { background: #fee2e2; color: #991b1b; }
        
        .role-badge {
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            font-size: 0.875rem;
            font-weight: 600;
            background: #e0e7ff;
            color: #3730a3;
        }
        
        /* Tables */
        .data-table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #374151;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Activity Timeline */
        .activity-timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 0.75rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .activity-item {
            position: relative;
            padding: 1rem 0;
            margin-bottom: 1rem;
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: -0.5rem;
            top: 1.25rem;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #3b82f6;
            border: 2px solid white;
            box-shadow: 0 0 0 1px #e2e8f0;
        }
        
        .activity-content {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            border: 1px solid #e2e8f0;
        }
        
        .activity-description {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .activity-meta {
            font-size: 0.75rem;
            color: #64748b;
            display: flex;
            gap: 1rem;
        }
        
        /* Permissions List */
        .permissions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 0.5rem;
        }
        
        .permission-item {
            display: flex;
            justify-content: between;
            align-items: center;
            padding: 0.75rem;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.875rem;
        }
        
        .permission-name {
            font-weight: 600;
            color: #374151;
        }
        
        .permission-file {
            font-family: 'Courier New', monospace;
            color: #64748b;
            font-size: 0.75rem;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .content-grid {
                grid-template-columns: 1fr;
                gap: 1.5rem;
            }
            
            .user-profile {
                flex-direction: column;
                text-align: center;
            }
            
            .header-actions {
                width: 100%;
            }
            
            .user-meta {
                justify-content: center;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .permissions-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- User Profile Header -->
                    <div class="user-header">
                        <div class="header-content">
                            <div class="user-profile">
                                <div class="user-avatar-large">
                                    <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                                </div>
                                <div class="user-info">
                                    <div class="user-name"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                    <div class="user-title">
                                        <?php echo htmlspecialchars($user['role_name']); ?> • @<?php echo htmlspecialchars($user['username']); ?>
                                    </div>
                                    <div class="user-meta">
                                        <span>📧 <?php echo htmlspecialchars($user['email']); ?></span>
                                        <?php if ($user['phone']): ?>
                                        <span>📱 <?php echo htmlspecialchars($user['phone']); ?></span>
                                        <?php endif; ?>
                                        <span>🆔 User ID: <?php echo $user['user_id']; ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="header-actions">
                                <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" class="btn-header">
                                    <i class="ph-pencil"></i> Edit User
                                </a>
                                
                                <?php if ($target_user_id !== $current_user_id): ?>
                                <form method="POST" style="margin: 0;" 
                                      onsubmit="return confirm('Reset password for this user? New password will be: laundry123')">
                                    <input type="hidden" name="action" value="reset_password">
                                    <button type="submit" class="btn-header">
                                        <i class="ph-lock-key"></i> Reset Password
                                    </button>
                                </form>
                                
                                <form method="POST" style="margin: 0;" 
                                      onsubmit="return confirm('<?php echo $user['status'] === 'ACTIVE' ? 'Suspend' : 'Activate'; ?> this user?')">
                                    <input type="hidden" name="action" value="toggle_status">
                                    <input type="hidden" name="new_status" value="<?php echo $user['status'] === 'ACTIVE' ? 'SUSPENDED' : 'ACTIVE'; ?>">
                                    <button type="submit" class="btn-header">
                                        <i class="ph-<?php echo $user['status'] === 'ACTIVE' ? 'user-minus' : 'user-plus'; ?>"></i> 
                                        <?php echo $user['status'] === 'ACTIVE' ? 'Suspend' : 'Activate'; ?> User
                                    </button>
                                </form>
                                <?php endif; ?>
                                
                                <a href="list_users.php" class="btn-header">
                                    <i class="ph-arrow-left"></i> Back to Users
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if (!empty($message)): ?>
                    <div class="alert alert-<?php echo $message_type; ?>">
                        <?php echo $message; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Activity Statistics -->
                    <div class="stats-grid">
                        <div class="stat-card stat-orders">
                            <div class="stat-value"><?php echo number_format($activity_stats['orders_created']); ?></div>
                            <div class="stat-label">Orders Created</div>
                        </div>
                        
                        <div class="stat-card stat-customers">
                            <div class="stat-value"><?php echo number_format($activity_stats['customers_created']); ?></div>
                            <div class="stat-label">Customers Added</div>
                        </div>
                        
                        <div class="stat-card stat-payments">
                            <div class="stat-value"><?php echo number_format($activity_stats['payments_processed']); ?></div>
                            <div class="stat-label">Payments Processed</div>
                        </div>
                        
                        <div class="stat-card stat-revenue">
                            <div class="stat-value">KES <?php echo number_format($activity_stats['revenue_generated']); ?></div>
                            <div class="stat-label">Revenue Generated</div>
                        </div>
                    </div>

                    <!-- User Details -->
                    <div class="content-grid">
                        <!-- Personal Information -->
                        <div class="info-card">
                            <h3 class="card-title">
                                <div class="card-icon" style="background: #dbeafe; color: #1d4ed8;">👤</div>
                                Personal Information
                            </h3>
                            
                            <div class="info-grid">
                                <div class="info-item">
                                    <span class="info-label">Last Login</span>
                                    <span class="info-value">
                                        <?php if ($user['last_login']): ?>
                                            <?php echo date('M j, Y \a\t g:i A', strtotime($user['last_login'])); ?>
                                            <div style="font-size: 0.75rem; color: #64748b;">
                                                <?php echo $user['days_since_login']; ?> days ago
                                            </div>
                                        <?php else: ?>
                                            <span style="color: #64748b;">Never logged in</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Password Changed</span>
                                    <span class="info-value">
                                        <?php echo date('M j, Y', strtotime($user['last_password_change'])); ?>
                                        <div style="font-size: 0.75rem; color: #64748b;">
                                            <?php echo $user['password_age_days']; ?> days ago
                                        </div>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Failed Attempts</span>
                                    <span class="info-value">
                                        <span style="color: <?php echo $user['failed_attempts'] > 0 ? '#dc2626' : '#059669'; ?>;">
                                            <?php echo $user['failed_attempts']; ?>
                                        </span>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Email Verified</span>
                                    <span class="info-value">
                                        <?php if ($user['verified']): ?>
                                            <span style="color: #059669;">✅ Verified</span>
                                        <?php else: ?>
                                            <span style="color: #dc2626;">❌ Not Verified</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">System Activity</span>
                                    <span class="info-value">
                                        <?php echo number_format($activity_stats['total_log_entries']); ?> total actions
                                        <div style="font-size: 0.75rem; color: #64748b;">
                                            <?php echo number_format($activity_stats['today_activities']); ?> today
                                        </div>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Role Information & Permissions -->
                    <div class="content-grid">
                        <div class="info-card">
                            <h3 class="card-title">
                                <div class="card-icon" style="background: #e0e7ff; color: #4f46e5;">🛡️</div>
                                Role & Permissions
                            </h3>
                            
                            <div style="margin-bottom: 1.5rem;">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                                    <div>
                                        <div style="font-weight: 700; font-size: 1.125rem; color: #1e293b; margin-bottom: 0.25rem;">
                                            <?php echo htmlspecialchars($user['role_name']); ?>
                                        </div>
                                        <div style="color: #64748b; font-size: 0.875rem;">
                                            <?php echo htmlspecialchars($user['role_description'] ?: 'No description available'); ?>
                                        </div>
                                    </div>
                                    <span class="role-badge">
                                        <?php echo $user['is_system'] ? 'System Role' : 'Custom Role'; ?>
                                    </span>
                                </div>
                            </div>
                            
                            <h4 style="font-size: 1rem; font-weight: 600; color: #374151; margin-bottom: 1rem;">
                                Page Access Permissions:
                            </h4>
                            
                            <?php if ($user['role_name'] === 'Super Admin'): ?>
                                <div style="background: #f0fdf4; border: 1px solid #22c55e; border-radius: 8px; padding: 1rem; text-align: center;">
                                    <div style="font-weight: 600; color: #166534; margin-bottom: 0.5rem;">
                                        🌟 Full System Access
                                    </div>
                                    <div style="color: #166534; font-size: 0.875rem;">
                                        Super Admin has access to all pages and features automatically
                                    </div>
                                </div>
                            <?php else: ?>
                                <?php if ($user_permissions->num_rows > 0): ?>
                                <div class="permissions-grid">
                                    <?php while($permission = $user_permissions->fetch_assoc()): ?>
                                    <div class="permission-item">
                                        <div>
                                            <div class="permission-name">
                                                <?php echo htmlspecialchars($page_titles[$permission['page_name']] ?? 'Unknown Page'); ?>
                                            </div>
                                            <div class="permission-file">
                                                <?php echo htmlspecialchars($permission['page_name']); ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                                <?php else: ?>
                                <div style="text-align: center; padding: 2rem; color: #64748b;">
                                    <div style="font-size: 2rem; margin-bottom: 1rem;">🚫</div>
                                    <div style="font-weight: 600; margin-bottom: 0.5rem;">No Specific Permissions</div>
                                    <div style="font-size: 0.875rem;">User only has access to basic system pages</div>
                                </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Recent Activity -->
                        <div class="info-card">
                            <h3 class="card-title">
                                <div class="card-icon" style="background: #dcfce7; color: #059669;">📋</div>
                                Recent Activity
                            </h3>
                            
                            <?php if ($recent_activity->num_rows > 0): ?>
                            <div class="activity-timeline">
                                <?php while($activity = $recent_activity->fetch_assoc()): ?>
                                <div class="activity-item">
                                    <div class="activity-content">
                                        <div class="activity-description">
                                            <?php echo htmlspecialchars($activity['activity_description']); ?>
                                        </div>
                                        <div class="activity-meta">
                                            <span>📅 <?php echo date('M j, Y \a\t g:i A', strtotime($activity['logged_at'])); ?></span>
                                            <span>🌐 <?php echo htmlspecialchars($activity['ip_address'] ?: 'Unknown IP'); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile; ?>
                            </div>
                            <?php else: ?>
                            <div style="text-align: center; padding: 2rem; color: #64748b;">
                                <div style="font-size: 2rem; margin-bottom: 1rem;">📝</div>
                                <div style="font-weight: 600; margin-bottom: 0.5rem;">No Recent Activity</div>
                                <div style="font-size: 0.875rem;">User hasn't performed any tracked actions yet</div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Recent Orders Created -->
                    <?php if ($recent_orders->num_rows > 0): ?>
                    <div class="data-table-container">
                        <div class="table-header">
                            <h3 class="table-title">Recent Orders Created by User</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Order Details</th>
                                    <th>Customer</th>
                                    <th>Order Date</th>
                                    <th>Status</th>
                                    <th>Items</th>
                                    <th>Amount</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($order = $recent_orders->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div>
                                            <a href="view_order.php?id=<?php echo $order['order_id']; ?>" 
                                               style="color: #3b82f6; text-decoration: none; font-weight: 600;">
                                                <?php echo htmlspecialchars($order['order_number']); ?>
                                            </a>
                                            <div style="font-size: 0.75rem; color: #64748b;">
                                                ID: <?php echo $order['order_id']; ?>
                                            </div>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            <?php echo htmlspecialchars($order['first_name'] . ' ' . $order['last_name']); ?>
                                        </div>
                                        <div style="font-size: 0.75rem; color: #64748b;">
                                            <?php echo htmlspecialchars($order['customer_code']); ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <div style="font-weight: 600;"><?php echo date('M j, Y', strtotime($order['order_date'])); ?></div>
                                        <div style="font-size: 0.75rem; color: #64748b;">
                                            <?php echo date('g:i A', strtotime($order['order_date'])); ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="status-badge status-<?php echo strtolower($order['order_status']); ?>">
                                            <?php echo str_replace('_', ' ', $order['order_status']); ?>
                                        </span>
                                    </td>
                                    
                                    <td>
                                        <span style="font-weight: 600;"><?php echo $order['total_pieces']; ?></span>
                                        <div style="font-size: 0.75rem; color: #64748b;">pieces</div>
                                    </td>
                                    
                                    <td>
                                        <div style="font-weight: 600; color: #059669;">
                                            KES <?php echo number_format($order['total_amount'], 2); ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <a href="view_order.php?id=<?php echo $order['order_id']; ?>" 
                                           style="color: #3b82f6; text-decoration: none; font-size: 0.75rem; padding: 0.25rem 0.5rem; border: 1px solid #3b82f6; border-radius: 4px;">
                                            <i class="ph-eye"></i> View
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <!-- System Information -->
                    <div class="info-card">
                        <h3 class="card-title">
                            <div class="card-icon" style="background: #f3e8ff; color: #7c3aed;">⚙️</div>
                            System Information & Security
                        </h3>
                        
                        <div class="content-grid" style="grid-template-columns: 1fr 1fr; gap: 2rem;">
                            <div>
                                <h4 style="font-size: 1rem; font-weight: 600; color: #374151; margin-bottom: 1rem;">
                                    Security Status
                                </h4>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <span class="info-label">Login Attempts Today</span>
                                        <span class="info-value">
                                            <span style="color: <?php echo $user['failed_attempts'] > 0 ? '#dc2626' : '#059669'; ?>;">
                                                <?php echo $user['failed_attempts']; ?> failed
                                            </span>
                                        </span>
                                    </div>
                                    
                                    <div class="info-item">
                                        <span class="info-label">Account Verification</span>
                                        <span class="info-value">
                                            <?php if ($user['verified']): ?>
                                                <span style="color: #059669;">✅ Verified</span>
                                            <?php else: ?>
                                                <span style="color: #dc2626;">❌ Unverified</span>
                                            <?php endif; ?>
                                        </span>
                                    </div>
                                    
                                    <div class="info-item">
                                        <span class="info-label">Password Age</span>
                                        <span class="info-value">
                                            <span style="color: <?php echo $user['password_age_days'] > 90 ? '#dc2626' : '#059669'; ?>;">
                                                <?php echo $user['password_age_days']; ?> days
                                            </span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <h4 style="font-size: 1rem; font-weight: 600; color: #374151; margin-bottom: 1rem;">
                                    Activity Summary
                                </h4>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <span class="info-label">Total System Actions</span>
                                        <span class="info-value"><?php echo number_format($activity_stats['total_log_entries']); ?></span>
                                    </div>
                                    
                                    <div class="info-item">
                                        <span class="info-label">Actions Today</span>
                                        <span class="info-value"><?php echo number_format($activity_stats['today_activities']); ?></span>
                                    </div>
                                    
                                    <div class="info-item">
                                        <span class="info-label">Account Status</span>
                                        <span class="info-value">
                                            <?php 
                                            $status_colors = [
                                                'ACTIVE' => '#059669',
                                                'INACTIVE' => '#64748b', 
                                                'SUSPENDED' => '#dc2626'
                                            ];
                                            ?>
                                            <span style="color: <?php echo $status_colors[$user['status']]; ?>;">
                                                <?php echo $user['status']; ?>
                                            </span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Security Recommendations -->
                        <div style="background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 8px; padding: 1rem; margin-top: 2rem;">
                            <h5 style="font-weight: 600; color: #0369a1; margin-bottom: 0.75rem;">
                                <i class="ph-shield-check"></i> Security Recommendations:
                            </h5>
                            <ul style="margin: 0; color: #0369a1; font-size: 0.875rem; line-height: 1.6;">
                                <?php if ($user['password_age_days'] > 90): ?>
                                <li>🔑 Password is over 90 days old - consider requiring password change</li>
                                <?php endif; ?>
                                
                                <?php if ($user['failed_attempts'] > 3): ?>
                                <li>⚠️ Multiple failed login attempts detected - review account security</li>
                                <?php endif; ?>
                                
                                <?php if (!$user['verified']): ?>
                                <li>📧 Email address is not verified - user should verify their email</li>
                                <?php endif; ?>
                                
                                <?php if ($user['days_since_login'] > 30): ?>
                                <li>👤 User hasn't logged in for over 30 days - consider account review</li>
                                <?php endif; ?>
                                
                                <?php if ($user['status'] === 'SUSPENDED'): ?>
                                <li>🚫 Account is suspended - review and activate if appropriate</li>
                                <?php endif; ?>
                                
                                <?php if (
                                    $user['password_age_days'] <= 90 && 
                                    $user['failed_attempts'] <= 3 && 
                                    $user['verified'] && 
                                    $user['days_since_login'] <= 30 && 
                                    $user['status'] === 'ACTIVE'
                                ): ?>
                                <li>✅ Account security looks good - no immediate concerns</li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>

                    <!-- Quick Action Cards -->
                    <div style="background: white; border-radius: 12px; padding: 2rem; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1); border: 1px solid #e2e8f0;">
                        <h3 style="font-size: 1.25rem; font-weight: 700; color: #1e293b; margin-bottom: 1.5rem;">
                            Quick Actions
                        </h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
                            <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" 
                               style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #fef3c7; color: #d97706; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    ✏️
                                </div>
                                <div>
                                    <div style="font-weight: 600;">Edit User Details</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Modify user information</div>
                                </div>
                            </a>
                            
                            <a href="list_users.php" 
                               style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #e0e7ff; color: #4f46e5; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    👥
                                </div>
                                <div>
                                    <div style="font-weight: 600;">All Users</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Back to user list</div>
                                </div>
                            </a>
                            
                            <a href="user_roles.php" 
                               style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #dcfce7; color: #059669; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    🛡️
                                </div>
                                <div>
                                    <div style="font-weight: 600;">Manage Roles</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Role & permissions</div>
                                </div>
                            </a>
                            
                            <a href="activity_logs.php?user_id=<?php echo $user['user_id']; ?>" 
                               style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: #374151; transition: all 0.2s ease;">
                                <div style="width: 40px; height: 40px; background: #f3e8ff; color: #7c3aed; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem;">
                                    📊
                                </div>
                                <div>
                                    <div style="font-weight: 600;">Full Activity Log</div>
                                    <div style="font-size: 0.75rem; color: #64748b;">Complete user history</div>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    
    <script>
        // Add hover effects to interactive elements
        document.addEventListener('DOMContentLoaded', function() {
            // Add hover effects to cards and links
            document.querySelectorAll('a[style*="border: 1px solid"]').forEach(link => {
                link.addEventListener('mouseenter', function() {
                    this.style.borderColor = '#3b82f6';
                    this.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
                    this.style.transform = 'translateY(-2px)';
                });
                
                link.addEventListener('mouseleave', function() {
                    this.style.borderColor = '#e2e8f0';
                    this.style.boxShadow = '';
                    this.style.transform = '';
                });
            });
            
            // Auto-refresh activity if user is viewing their own profile
            <?php if ($target_user_id === $current_user_id): ?>
            setInterval(function() {
                // Refresh activity stats every 5 minutes for current user
                location.reload();
            }, 300000); // 5 minutes
            <?php endif; ?>
        });
    </script>
</body>
</html>