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

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

// Get logged-in user details
$logged_user_id = $_SESSION['user_id'];
$sql_logged_user = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = ?";
$stmt_logged = $conn->prepare($sql_logged_user);
$stmt_logged->bind_param('i', $logged_user_id);
$stmt_logged->execute();
$result_logged_user = $stmt_logged->get_result();

if ($result_logged_user && $row_logged_user = $result_logged_user->fetch_assoc()) {
    $logged_username = $row_logged_user['username'];
    $logged_user_role = $row_logged_user['user_role'];
    $logged_full_name = $row_logged_user['full_name'];
    $logged_email = $row_logged_user['email'];
    $logged_role_id = $row_logged_user['role_id'];
} else {
    // Handle the case if logged user details are not found
    header('Location: login.php');
    exit();
}

// Check if user has permission to view user details
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view_users', 'edit_users', 'delete_users'], // Admin has all permissions
        '2' => ['view_users'], // General Manager can view users
        '3' => [], // Operations
        '4' => [], // Finance
        '5' => [], // Declaration Officer
        '6' => [], // Shipping Line Clerk
        '7' => [], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// IMPORTANT CHANGE: Make sure we're explicitly getting the ID parameter and prioritizing it
$user_id = $logged_user_id; // Default to logged-in user
if (isset($_GET['user_id']) && !empty($_GET['user_id'])) {
    $user_id = intval($_GET['user_id']);
}

// Check if viewing own profile or has permission to view others
if ($user_id != $logged_user_id && !hasPermission($logged_role_id, 'view_users')) {
    $_SESSION['error_message'] = "You don't have permission to view other user profiles";
    header('Location: index.php');
    exit();
}

// Get user details - using prepared statement to prevent SQL injection
$sql_user = "SELECT u.*, ur.role_name 
             FROM users u 
             LEFT JOIN user_role ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt = $conn->prepare($sql_user);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "User not found";
    header('Location: all_users.php'); // Changed to be consistent
    exit();
}

$user = $result->fetch_assoc();

// Get login activity
$sql_login = "SELECT login_date, last_login_attempts, session_duration 
              FROM login_activity_log 
              WHERE user_id = ? 
              ORDER BY login_date DESC 
              LIMIT 5";
$stmt_login = $conn->prepare($sql_login);
$stmt_login->bind_param('i', $user_id);
$stmt_login->execute();
$login_result = $stmt_login->get_result();

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d H:i:s', strtotime($date));
}

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'User Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .user-profile-card {
            margin-bottom: 1.5rem;
        }
        .profile-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e9e9ef;
            background-color: #f8f9fa;
        }
        .profile-avatar {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 50%;
            margin-bottom: 1rem;
        }
        .profile-label {
            font-weight: 600;
            color: #495057;
        }
        .profile-value {
            color: #343a40;
        }
        .activity-list {
            list-style: none;
            padding-left: 0;
        }
        .activity-item {
            padding: 0.75rem 0;
            border-bottom: 1px solid #e9e9ef;
        }
        .activity-item:last-child {
            border-bottom: none;
        }
        .activity-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 1rem;
        }
        .role-badge {
            font-size: 0.75rem;
            padding: 0.3rem 0.5rem;
        }
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
        }
        .status-active {
            background-color: #28a745;
        }
        .status-inactive {
            background-color: #dc3545;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'User Management', 'title' => 'User Profile')); ?>

                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-4">
                            <!-- User Profile Card -->
                            <div class="card user-profile-card">
                                <div class="profile-header text-center">
                                    <img src="assets/images/user/avatar-1.jpg" alt="User Avatar" class="profile-avatar">
                                    <h5 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h5>
                                    <p class="text-muted mb-2"><?php echo htmlspecialchars($user['email']); ?></p>
                                    <div class="d-flex justify-content-center">
                                        <span class="badge bg-<?php 
                                            switch($user['role_id']) {
                                                case 1: echo 'danger'; break;
                                                case 2: echo 'primary'; break;
                                                case 3: echo 'info'; break;
                                                case 4: echo 'warning'; break;
                                                case 5: echo 'success'; break;
                                                default: echo 'secondary'; break;
                                            }
                                        ?> role-badge">
                                            <?php echo htmlspecialchars($user['role_name']); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-12">
                                            <p class="mb-2">
                                                <span class="status-indicator <?php echo $user['verified'] == 1 ? 'status-active' : 'status-inactive'; ?>"></span>
                                                <span class="fw-semibold">Status:</span>
                                                <span class="ms-2"><?php echo $user['verified'] == 1 ? 'Active' : 'Inactive'; ?></span>
                                            </p>
                                            <p class="mb-2">
                                                <span class="fw-semibold">Username:</span>
                                                <span class="ms-2"><?php echo htmlspecialchars($user['username']); ?></span>
                                            </p>
                                            <p class="mb-2">
                                                <span class="fw-semibold">Last Active:</span>
                                                <span class="ms-2"><?php echo $user['last_active'] ? formatDate($user['last_active']) : 'Never'; ?></span>
                                            </p>
                                            <p class="mb-2">
                                                <span class="fw-semibold">Account Created:</span>
                                                <span class="ms-2"><?php echo formatDate($user['created_at']); ?></span>
                                            </p>
                                            <p class="mb-0">
                                                <span class="fw-semibold">Last Password Change:</span>
                                                <span class="ms-2"><?php echo formatDate($user['last_password_change']); ?></span>
                                            </p>
                                        </div>
                                    </div>

                                    <hr class="my-4">

                                    <div class="text-center">
                                        <?php if ($user_id == $logged_user_id || hasPermission($logged_role_id, 'edit_users')): ?>
                                            <a href="edit_user.php?id=<?php echo $user_id; ?>" class="btn btn-primary me-2">
                                                <i class="ri-edit-box-line align-bottom me-1"></i> Edit Profile
                                            </a>
                                        <?php endif; ?>
                                        
                                        <?php if ($user_id == $logged_user_id): ?>
                                            <a href="change_password.php" class="btn btn-info">
                                                <i class="ri-lock-password-line align-bottom me-1"></i> Change Password
                                            </a>
                                        <?php elseif (hasPermission($logged_role_id, 'edit_users')): ?>
                                            <a href="reset_password.php?id=<?php echo $user_id; ?>" class="btn btn-warning">
                                                <i class="ri-refresh-line align-bottom me-1"></i> Reset Password
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <!-- End User Profile Card -->

                            <!-- Quick Links Card -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Quick Links</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="list-group list-group-flush">
                                        <li class="list-group-item px-0 py-2">
                                            <a href="all_users.php" class="d-flex align-items-center">
                                                <i class="ri-user-line fs-16 align-middle me-2"></i> All Users
                                            </a>
                                        </li>
                                        <?php if (hasPermission($logged_role_id, 'edit_users')): ?>
                                        <li class="list-group-item px-0 py-2">
                                            <a href="add_user.php" class="d-flex align-items-center">
                                                <i class="ri-user-add-line fs-16 align-middle me-2"></i> Add New User
                                            </a>
                                        </li>
                                        <?php endif; ?>
                                        <li class="list-group-item px-0 py-2">
                                            <a href="user_view.php?id=<?php echo $logged_user_id; ?>" class="d-flex align-items-center">
                                                <i class="ri-account-circle-line fs-16 align-middle me-2"></i> My Profile
                                            </a>
                                        </li>
                                        <li class="list-group-item px-0 py-2">
                                            <a href="change_password.php" class="d-flex align-items-center">
                                                <i class="ri-lock-password-line fs-16 align-middle me-2"></i> Change Password
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <!-- End Quick Links Card -->
                        </div>

                        <div class="col-xl-8">
                            <!-- User Information Card -->
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">User Information</h5>
                                        <div>
                                            <a href="all_users.php" class="btn btn-sm btn-primary">
                                                <i class="ri-arrow-left-line align-bottom me-1"></i> Back to List
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Full Name</label>
                                            <p class="profile-value"><?php echo htmlspecialchars($user['full_name']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Email</label>
                                            <p class="profile-value"><?php echo htmlspecialchars($user['email']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Username</label>
                                            <p class="profile-value"><?php echo htmlspecialchars($user['username']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Role</label>
                                            <p class="profile-value"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Created Date</label>
                                            <p class="profile-value"><?php echo formatDate($user['created_at']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Last Active</label>
                                            <p class="profile-value"><?php echo $user['last_active'] ? formatDate($user['last_active']) : 'Never'; ?></p>
                                        </div>
                                    </div>

                                    <div class="row mt-3">
                                        <div class="col-12">
                                            <h5 class="border-bottom pb-2">Security Information</h5>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Account Status</label>
                                            <p class="profile-value">
                                                <span class="badge bg-<?php echo $user['verified'] == 1 ? 'success' : 'danger'; ?>">
                                                    <?php echo $user['verified'] == 1 ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Failed Login Attempts</label>
                                            <p class="profile-value">
                                                <span class="badge bg-<?php echo $user['failed_attempts'] > 2 ? 'warning' : 'info'; ?>">
                                                    <?php echo $user['failed_attempts']; ?>
                                                </span>
                                            </p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Last Password Change</label>
                                            <p class="profile-value"><?php echo formatDate($user['last_password_change']); ?></p>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="profile-label">Last Login Attempt</label>
                                            <p class="profile-value"><?php echo $user['last_attempt_time'] ? formatDate($user['last_attempt_time']) : 'Never'; ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- End User Information Card -->

                            <!-- Login Activity Card -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Login Activity</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($login_result && $login_result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover table-nowrap mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">Login Date</th>
                                                    <th scope="col">Session Duration</th>
                                                    <th scope="col">Login Attempts</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($row = $login_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo formatDate($row['login_date']); ?></td>
                                                    <td><?php echo $row['session_duration'] ?? 'N/A'; ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $row['last_login_attempts'] > 0 ? 'warning' : 'success'; ?>">
                                                            <?php echo $row['last_login_attempts'] > 0 ? $row['last_login_attempts'] . ' attempts' : 'Success'; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="text-center py-4">
                                        <div class="avatar-md mx-auto mb-3">
                                            <div class="avatar-title bg-light text-primary rounded-circle">
                                                <i class="ri-history-line fs-24"></i>
                                            </div>
                                        </div>
                                        <h5 class="text-muted mb-2">No login activity found</h5>
                                        <p class="text-muted mb-0">This user does not have any recorded login activity.</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <!-- End Login Activity Card -->

                            <!-- Role Information Card -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Role Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex mb-4">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <div class="avatar-title bg-soft-<?php 
                                                    switch($user['role_id']) {
                                                        case 1: echo 'danger'; break;
                                                        case 2: echo 'primary'; break;
                                                        case 3: echo 'info'; break;
                                                        case 4: echo 'warning'; break;
                                                        case 5: echo 'success'; break;
                                                        default: echo 'secondary'; break;
                                                    }
                                                ?> text-<?php 
                                                    switch($user['role_id']) {
                                                        case 1: echo 'danger'; break;
                                                        case 2: echo 'primary'; break;
                                                        case 3: echo 'info'; break;
                                                        case 4: echo 'warning'; break;
                                                        case 5: echo 'success'; break;
                                                        default: echo 'secondary'; break;
                                                    }
                                                ?> rounded-3">
                                                    <i class="ri-shield-user-line fs-20"></i>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h5 class="mb-1"><?php echo htmlspecialchars($user['role_name']); ?></h5>
                                            <p class="text-muted mb-0">
                                                <?php
                                                switch($user['role_id']) {
                                                    case 1:
                                                        echo 'Administrator with full system access and permissions';
                                                        break;
                                                    case 2:
                                                        echo 'General Manager with management and approval capabilities';
                                                        break;
                                                    case 3:
                                                        echo 'Operations staff with shipment handling permissions';
                                                        break;
                                                    case 4:
                                                        echo 'Finance staff with invoicing and billing access';
                                                        break;
                                                    case 5:
                                                        echo 'Declaration Officer with documents handling capabilities';
                                                        break;
                                                    case 6:
                                                        echo 'Shipping Line Clerk with shipping-related permissions';
                                                        break;
                                                    case 7:
                                                        echo 'Transport Supervisor with transport monitoring capabilities';
                                                        break;
                                                    default:
                                                        echo 'Standard user with basic permissions';
                                                }
                                                ?>
                                            </p>
                                        </div>
                                    </div>

                                    <h6 class="mb-3">Role Permissions</h6>

                                    <?php
                                    // Define permissions based on role
                                    $permissions = [
                                        // Administrator
                                        1 => [
                                            ['name' => 'User Management', 'description' => 'Create, view, edit, and delete users', 'icon' => 'ri-user-settings-line'],
                                            ['name' => 'System Settings', 'description' => 'Configure global system settings', 'icon' => 'ri-settings-4-line'],
                                            ['name' => 'All Shipments', 'description' => 'Full access to all shipment data', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Invoicing', 'description' => 'Create and manage all invoices', 'icon' => 'ri-bill-line'],
                                            ['name' => 'Reports', 'description' => 'Access all system reports', 'icon' => 'ri-file-chart-line'],
                                            ['name' => 'Delete Records', 'description' => 'Can permanently delete records', 'icon' => 'ri-delete-bin-line']
                                        ],
                                        // General Manager
                                        2 => [
                                            ['name' => 'View Users', 'description' => 'View user information', 'icon' => 'ri-user-search-line'],
                                            ['name' => 'All Shipments', 'description' => 'Full access to all shipment data', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Invoicing', 'description' => 'Create and manage all invoices', 'icon' => 'ri-bill-line'],
                                            ['name' => 'Reports', 'description' => 'Access all system reports', 'icon' => 'ri-file-chart-line'],
                                            ['name' => 'Approve Charges', 'description' => 'Approve shipping costs', 'icon' => 'ri-check-double-line']
                                        ],
                                        // Operations
                                        3 => [
                                            ['name' => 'Manage Shipments', 'description' => 'Create and update shipment records', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Create Invoices', 'description' => 'Create new invoices', 'icon' => 'ri-bill-line'],
                                            ['name' => 'View Reports', 'description' => 'Access operational reports', 'icon' => 'ri-file-chart-line']
                                        ],
                                        // Finance
                                        4 => [
                                            ['name' => 'View Shipments', 'description' => 'View shipment details', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Manage Invoices', 'description' => 'Create and manage invoices', 'icon' => 'ri-bill-line'],
                                            ['name' => 'Financial Reports', 'description' => 'Access financial reports', 'icon' => 'ri-file-chart-line'],
                                            ['name' => 'Expense Management', 'description' => 'Manage operational expenses', 'icon' => 'ri-money-dollar-circle-line']
                                        ],
                                        // Declaration Officer
                                        5 => [
                                            ['name' => 'View Shipments', 'description' => 'View shipment details', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Update Shipments', 'description' => 'Update shipment status', 'icon' => 'ri-refresh-line'],
                                            ['name' => 'Document Management', 'description' => 'Upload and manage documents', 'icon' => 'ri-file-upload-line']
                                        ],
                                        // Shipping Line Clerk
                                        6 => [
                                            ['name' => 'View Shipments', 'description' => 'View shipment details', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Shipping Line Data', 'description' => 'Manage shipping line information', 'icon' => 'ri-ship-2-line']
                                        ],
                                        // Transport Supervisor
                                        7 => [
                                            ['name' => 'View Shipments', 'description' => 'View shipment details', 'icon' => 'ri-ship-line'],
                                            ['name' => 'Manage Transport', 'description' => 'Assign and monitor trucks', 'icon' => 'ri-truck-line']
                                        ]
                                    ];

                                    $rolePermissions = $permissions[$user['role_id']] ?? [];
                                    ?>

                                    <div class="row">
                                        <?php foreach ($rolePermissions as $permission): ?>
                                        <div class="col-md-6 mb-3">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0">
                                                    <div class="avatar-xs">
                                                        <div class="avatar-title bg-light text-primary rounded">
                                                            <i class="<?php echo $permission['icon']; ?>"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 ms-3">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($permission['name']); ?></h6>
                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($permission['description']); ?></p>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <!-- End Role Information Card -->
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>