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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

// Verify user has permission to view users
$current_user_id = $_SESSION['user_id'];
$current_user_role_sql = "SELECT ur.role_name, ur.role_id 
                          FROM users u 
                          JOIN user_roles ur ON u.role_id = ur.role_id 
                          WHERE u.user_id = ?";
$stmt = $conn->prepare($current_user_role_sql);
$stmt->bind_param("i", $current_user_id);
$stmt->execute();
$current_role_result = $stmt->get_result();
$current_user_role = $current_role_result->fetch_assoc();

$can_view_users = false;
if ($current_user_role) {
    if ($current_user_role['role_name'] === 'Super Admin' || $current_user_role['role_name'] === 'Administrator') {
        $can_view_users = true;
    } else {
        $perm_sql = "SELECT can_view 
                     FROM role_permissions 
                     WHERE role_id = ? AND menu_id = (SELECT menu_id FROM menu_items WHERE menu_url = 'users.php' LIMIT 1)";
        $perm_stmt = $conn->prepare($perm_sql);
        $perm_stmt->bind_param("i", $current_user_role['role_id']);
        $perm_stmt->execute();
        $perm_result = $perm_stmt->get_result();
        $permissions = $perm_result->fetch_assoc();
        
        if ($permissions && $permissions['can_view'] == 1) {
            $can_view_users = true;
        }
    }
}

if (!$can_view_users) {
    echo '<div class="alert alert-danger">You do not have permission to view user details</div>';
    exit();
}

// Get user ID
$user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

if (!$user_id) {
    echo '<div class="alert alert-danger">Invalid user ID</div>';
    exit();
}

// Fetch comprehensive user details
$user_sql = "SELECT 
    u.user_id, 
    u.username, 
    u.email, 
    u.full_name, 
    u.phone_primary, 
    u.phone_secondary,
    u.staff_number,
    u.license_number,
    u.license_expiry,
    u.user_type,
    u.status,
    u.role_id,
    u.branch_id,
    u.supervisor_id,
    u.hire_date,
    u.date_of_birth,
    u.gender,
    u.national_id,
    u.address,
    u.emergency_contact_name,
    u.emergency_contact_phone,
    u.profile_picture,
    u.last_login,
    u.login_attempts,
    u.created_at,
    u.updated_at,
    ur.role_name,
    ur.role_code,
    hb.branch_name,
    hb.branch_code,
    CONCAT(sup.full_name) as supervisor_name,
    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
FROM users u
LEFT JOIN user_roles ur ON u.role_id = ur.role_id
LEFT JOIN hospital_branches hb ON u.branch_id = hb.branch_id
LEFT JOIN users sup ON u.supervisor_id = sup.user_id
WHERE u.user_id = ?";

$stmt = $conn->prepare($user_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo '<div class="alert alert-danger">User not found</div>';
    exit();
}

$user = $result->fetch_assoc();

// Check if user has additional profiles
$is_doctor = false;
$is_nurse = false;
$is_lab_tech = false;
$doctor_info = null;
$nurse_info = null;
$tech_info = null;

// Check doctor profile
$doctor_check_sql = "SELECT d.*, s.specialization_name 
                     FROM doctors d
                     LEFT JOIN specializations s ON d.specialization_id = s.specialization_id
                     WHERE d.user_id = ?";
$stmt = $conn->prepare($doctor_check_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$doctor_result = $stmt->get_result();
if ($doctor_result->num_rows > 0) {
    $is_doctor = true;
    $doctor_info = $doctor_result->fetch_assoc();
}

// Check nurse profile
$nurse_check_sql = "SELECT * FROM nurses WHERE user_id = ?";
$stmt = $conn->prepare($nurse_check_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$nurse_result = $stmt->get_result();
if ($nurse_result->num_rows > 0) {
    $is_nurse = true;
    $nurse_info = $nurse_result->fetch_assoc();
}

// Check lab tech profile
$tech_check_sql = "SELECT * FROM lab_technicians WHERE user_id = ?";
$stmt = $conn->prepare($tech_check_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$tech_result = $stmt->get_result();
if ($tech_result->num_rows > 0) {
    $is_lab_tech = true;
    $tech_info = $tech_result->fetch_assoc();
}

// Get recent activity logs
$activity_sql = "SELECT action, entity_type, description, created_at 
                 FROM activity_logs 
                 WHERE user_id = ? 
                 ORDER BY created_at DESC 
                 LIMIT 10";
$stmt = $conn->prepare($activity_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$activity_result = $stmt->get_result();
?>

<style>
.detail-row {
    padding: 0.75rem 0;
    border-bottom: 1px solid #e9ecef;
}
.detail-row:last-child {
    border-bottom: none;
}
.detail-label {
    font-weight: 600;
    color: #495057;
    margin-bottom: 0.25rem;
}
.detail-value {
    color: #6c757d;
}
.user-badge {
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 600;
}
.section-title {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 0.75rem 1rem;
    border-radius: 6px;
    margin-bottom: 1rem;
    font-size: 1rem;
    font-weight: 600;
}
</style>

<div class="container-fluid">
    <div class="row mb-3">
        <div class="col-12 text-center">
            <div class="user-avatar" style="width: 80px; height: 80px; font-size: 2rem; margin: 0 auto 1rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%; color: white; display: flex; align-items: center; justify-content: center;">
                <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
            </div>
            <h5><?php echo htmlspecialchars($user['full_name']); ?></h5>
            <p class="text-muted mb-2"><?php echo htmlspecialchars($user['role_name']); ?></p>
            
            <?php
            $status_class = match($user['status']) {
                'ACTIVE' => 'bg-success text-white',
                'INACTIVE' => 'bg-secondary text-white',
                'PENDING' => 'bg-warning text-dark',
                'SUSPENDED' => 'bg-danger text-white',
                default => 'bg-secondary text-white'
            };
            ?>
            <span class="user-badge <?php echo $status_class; ?>">
                <?php echo ucfirst(strtolower($user['status'])); ?>
            </span>
            
            <?php if ($is_doctor): ?>
            <span class="user-badge bg-primary text-white ms-2">
                <i class="ri-stethoscope-line me-1"></i> Doctor
            </span>
            <?php endif; ?>
            
            <?php if ($is_nurse): ?>
            <span class="user-badge bg-success text-white ms-2">
                <i class="ri-nurse-line me-1"></i> Nurse
            </span>
            <?php endif; ?>
            
            <?php if ($is_lab_tech): ?>
            <span class="user-badge bg-info text-white ms-2">
                <i class="ri-microscope-line me-1"></i> Lab Tech
            </span>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <div class="section-title">
                <i class="ri-user-line me-2"></i>Personal Information
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Staff Number</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['staff_number'] ?: 'N/A'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Date of Birth</div>
                <div class="detail-value">
                    <?php echo $user['date_of_birth'] ? date('M j, Y', strtotime($user['date_of_birth'])) . ' (' . $user['age'] . ' years)' : 'N/A'; ?>
                </div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Gender</div>
                <div class="detail-value"><?php echo $user['gender'] ? ucfirst(strtolower($user['gender'])) : 'N/A'; ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">National ID</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['national_id'] ?: 'N/A'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Address</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['address'] ?: 'N/A'); ?></div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="section-title">
                <i class="ri-phone-line me-2"></i>Contact Information
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Email</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['email']); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Username</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['username'] ?: 'N/A'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Primary Phone</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['phone_primary']); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Secondary Phone</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['phone_secondary'] ?: 'N/A'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Emergency Contact</div>
                <div class="detail-value">
                    <?php 
                    if ($user['emergency_contact_name']) {
                        echo htmlspecialchars($user['emergency_contact_name']);
                        if ($user['emergency_contact_phone']) {
                            echo ' (' . htmlspecialchars($user['emergency_contact_phone']) . ')';
                        }
                    } else {
                        echo 'N/A';
                    }
                    ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-md-6">
            <div class="section-title">
                <i class="ri-briefcase-line me-2"></i>Employment Details
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Role</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['role_name']); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Branch</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['branch_name'] ?: 'Not Assigned'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Supervisor</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['supervisor_name'] ?: 'None'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Hire Date</div>
                <div class="detail-value"><?php echo $user['hire_date'] ? date('M j, Y', strtotime($user['hire_date'])) : 'N/A'; ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">License Number</div>
                <div class="detail-value"><?php echo htmlspecialchars($user['license_number'] ?: 'N/A'); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">License Expiry</div>
                <div class="detail-value">
                    <?php 
                    if ($user['license_expiry']) {
                        echo date('M j, Y', strtotime($user['license_expiry']));
                        if (strtotime($user['license_expiry']) < time()) {
                            echo ' <span class="badge bg-danger text-white">Expired</span>';
                        }
                    } else {
                        echo 'N/A';
                    }
                    ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="section-title">
                <i class="ri-time-line me-2"></i>Account Information
            </div>
            
            <div class="detail-row">
                <div class="detail-label">User Type</div>
                <div class="detail-value"><?php echo ucfirst(strtolower($user['user_type'])); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Last Login</div>
                <div class="detail-value">
                    <?php 
                    if ($user['last_login']) {
                        echo date('M j, Y g:i A', strtotime($user['last_login']));
                    } else {
                        echo 'Never logged in';
                    }
                    ?>
                </div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Failed Login Attempts</div>
                <div class="detail-value"><?php echo $user['login_attempts']; ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Account Created</div>
                <div class="detail-value"><?php echo date('M j, Y g:i A', strtotime($user['created_at'])); ?></div>
            </div>
            
            <div class="detail-row">
                <div class="detail-label">Last Updated</div>
                <div class="detail-value"><?php echo date('M j, Y g:i A', strtotime($user['updated_at'])); ?></div>
            </div>
        </div>
    </div>
    
    <?php if ($is_doctor && $doctor_info): ?>
    <div class="row mt-3">
        <div class="col-12">
            <div class="section-title">
                <i class="ri-stethoscope-line me-2"></i>Doctor Profile
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="detail-row">
                        <div class="detail-label">Specialization</div>
                        <div class="detail-value"><?php echo htmlspecialchars($doctor_info['specialization_name'] ?: 'N/A'); ?></div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="detail-row">
                        <div class="detail-label">Consultation Fee</div>
                        <div class="detail-value">KES <?php echo number_format($doctor_info['consultation_fee'], 2); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if ($activity_result->num_rows > 0): ?>
    <div class="row mt-3">
        <div class="col-12">
            <div class="section-title">
                <i class="ri-history-line me-2"></i>Recent Activity
            </div>
            
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Action</th>
                            <th>Entity</th>
                            <th>Description</th>
                            <th>Date/Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($activity = $activity_result->fetch_assoc()): ?>
                        <tr>
                            <td><span class="badge bg-primary"><?php echo $activity['action']; ?></span></td>
                            <td><?php echo ucfirst($activity['entity_type']); ?></td>
                            <td><?php echo htmlspecialchars($activity['description']); ?></td>
                            <td><small><?php echo date('M j, g:i A', strtotime($activity['created_at'])); ?></small></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php
$conn->close();
?>