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

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Get user ID from URL
$user_id = isset($_GET['id']) ? $_GET['id'] : null;
if (!$user_id) {
    header('Location: users.php');
    exit();
}

// Get user details with role
$sql = "SELECT u.*, ur.role_name,
        CASE 
            WHEN u.verified = 1 AND u.failed_attempts < 3 THEN 'ACTIVE'
            WHEN u.verified = 0 THEN 'PENDING'
            WHEN u.failed_attempts >= 3 THEN 'SUSPENDED'
        END as status
        FROM users u 
        LEFT JOIN user_role 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();

// Get user's recent activity
$sql = "SELECT * FROM activity_log 
        WHERE user_id = ? 
        ORDER BY action_date DESC 
        LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$recent_activity = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Users', 'title' => 'User Profile')); ?>

                    <div class="row">
                        <div class="col-xxl-3">
                            <div class="card">
                                <div class="card-body">
                                    <div class="text-center">
                                        <div class="profile-user position-relative d-inline-block mx-auto mb-4">
                                            <div class="avatar-lg">
                                                <div class="avatar-title bg-light rounded-circle text-primary fs-24">
                                                    <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                                                </div>
                                            </div>
                                        </div>
                                        <h5 class="fs-16 mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h5>
                                        <p class="text-muted mb-0"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <span class="text-muted">Status:</span>
                                            <span class="badge bg-<?php 
                                                echo $user['status'] === 'ACTIVE' ? 'success' : 
                                                    ($user['status'] === 'PENDING' ? 'warning' : 'danger'); 
                                            ?>">
                                                <?php echo $user['status']; ?>
                                            </span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <span class="text-muted">Last Active:</span>
                                            <span><?php echo $user['last_active'] ? 
                                                date('d M Y H:i', strtotime($user['last_active'])) : 
                                                'Never'; ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="text-muted">Created On:</span>
                                            <span><?php echo date('d M Y', strtotime($user['created_at'])); ?></span>
                                        </div>
                                    </div>

                                    <div class="mt-4">
                                        <a href="user_profile.php?id=<?php echo $user['user_id']; ?>" 
                                           class="btn btn-primary w-100">
                                            <i class="ri-pencil-line align-bottom me-1"></i> Edit Profile
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xxl-9">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">User Information</h4>
                                    <div class="flex-shrink-0">
                                        <div class="dropdown">
                                            <button class="btn btn-soft-primary btn-sm" type="button" data-bs-toggle="dropdown">
                                                <i class="ri-more-fill align-middle"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <?php if ($user['status'] === 'SUSPENDED'): ?>
                                                    <li>
                                                        <a href="javascript:void(0);" 
                                                           class="dropdown-item" 
                                                           onclick="activateUser(<?php echo $user['user_id']; ?>)">
                                                            <i class="ri-check-double-line align-bottom me-2 text-success"></i>
                                                            Activate User
                                                        </a>
                                                    </li>
                                                <?php else: ?>
                                                    <li>
                                                        <a href="javascript:void(0);" 
                                                           class="dropdown-item" 
                                                           onclick="suspendUser(<?php echo $user['user_id']; ?>)">
                                                            <i class="ri-close-circle-line align-bottom me-2 text-danger"></i>
                                                            Suspend User
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                                <li>
                                                    <a href="javascript:void(0);" 
                                                       class="dropdown-item"
                                                       onclick="resetPassword(<?php echo $user['user_id']; ?>)">
                                                        <i class="ri-lock-password-line align-bottom me-2 text-muted"></i>
                                                        Reset Password
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <th class="ps-0" scope="row">Full Name :</th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($user['full_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th class="ps-0" scope="row">Username :</th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($user['username']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th class="ps-0" scope="row">Email :</th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($user['email']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th class="ps-0" scope="row">Role :</th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($user['role_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <th class="ps-0" scope="row">Last Password Change :</th>
                                                    <td class="text-muted">
                                                        <?php echo $user['last_password_change'] ? 
                                                            date('d M Y H:i', strtotime($user['last_password_change'])) : 
                                                            'Never'; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <th class="ps-0" scope="row">Failed Login Attempts :</th>
                                                    <td class="text-muted"><?php echo $user['failed_attempts']; ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Activity</h4>
                                </div>

                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless table-nowrap">
                                            <thead>
                                                <tr>
                                                    <th scope="col">Action</th>
                                                    <th scope="col">Details</th>
                                                    <th scope="col">IP Address</th>
                                                    <th scope="col">Date/Time</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($recent_activity as $activity): ?>
                                                <tr>
                                                    <td>
                                                        <span class="badge bg-primary">
                                                            <?php echo $activity['action']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        echo "{$activity['table_name']} - {$activity['record_id']}";
                                                        if ($activity['additional_info']) {
                                                            echo "<br><small class='text-muted'>" . 
                                                                htmlspecialchars($activity['additional_info']) . 
                                                                "</small>";
                                                        }
                                                        ?>
                                                    </td>
                                                    <td><?php echo $activity['ip_address']; ?></td>
                                                    <td><?php echo date('d M Y H:i', strtotime($activity['action_date'])); ?></td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        // Re-use the same functions for suspending/activating/resetting password
        // from the users.php page
    </script>
</body>
</html>