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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Super Admin') {
    header('Location: index.php');
    exit();
}

$user_id = $_GET['id'] ?? 0;

// Get user details
$sql = "SELECT u.*, r.role_name,
        CONCAT(u.first_name, ' ', COALESCE(u.middle_name, ''), ' ', u.last_name) as full_name
        FROM users u
        INNER JOIN roles r ON u.role_id = r.id
        WHERE u.id = ?";
$stmt = $conn->prepare($sql);
$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: list_users.php');
    exit();
}

$user = $result->fetch_assoc();

// Get user activity logs
$activity_sql = "SELECT * FROM activity_logs 
                 WHERE user_id = ? 
                 ORDER BY timestamp DESC 
                 LIMIT 20";
$activity_stmt = $conn->prepare($activity_sql);
$activity_stmt->bind_param("i", $user_id);
$activity_stmt->execute();
$activity_result = $activity_stmt->get_result();

// Get user-specific data based on role
$role_data = [];
if ($user['role_name'] === 'Tenant') {
    // Get tenant-specific data
    $tenant_sql = "SELECT * FROM tenant_kyc WHERE user_id = ?";
    $tenant_stmt = $conn->prepare($tenant_sql);
    $tenant_stmt->bind_param("i", $user_id);
    $tenant_stmt->execute();
    $role_data['kyc'] = $tenant_stmt->get_result()->fetch_assoc();
    
    // Get active leases
    $lease_sql = "SELECT l.*, u.unit_number, p.name as property_name 
                  FROM leases l
                  JOIN units u ON l.unit_id = u.id
                  JOIN properties p ON u.property_id = p.id
                  WHERE l.tenant_id = ?
                  ORDER BY l.start_date DESC";
    $lease_stmt = $conn->prepare($lease_sql);
    $lease_stmt->bind_param("i", $user_id);
    $lease_stmt->execute();
    $role_data['leases'] = $lease_stmt->get_result();
} elseif ($user['role_name'] === 'Landlord') {
    // Get landlord properties
    $property_sql = "SELECT * FROM properties WHERE owner_id = ?";
    $property_stmt = $conn->prepare($property_sql);
    $property_stmt->bind_param("i", $user_id);
    $property_stmt->execute();
    $role_data['properties'] = $property_stmt->get_result();
} elseif ($user['role_name'] === 'Vendor') {
    // Get vendor info
    $vendor_sql = "SELECT * FROM vendors WHERE id = 
                   (SELECT id FROM vendors WHERE contact_person = ? OR email = ? LIMIT 1)";
    $vendor_stmt = $conn->prepare($vendor_sql);
    $vendor_stmt->bind_param("ss", $user['full_name'], $user['email']);
    $vendor_stmt->execute();
    $role_data['vendor'] = $vendor_stmt->get_result()->fetch_assoc();
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View User')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 0.5rem 0.5rem 0 0;
            color: white;
        }
        
        .profile-avatar {
            width: 120px;
            height: 120px;
            border: 5px solid white;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .info-card {
            border-left: 3px solid #667eea;
        }
        
        .activity-item {
            padding: 1rem;
            border-left: 2px solid #e9ecef;
            margin-left: 1rem;
            position: relative;
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: -6px;
            top: 1.5rem;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #667eea;
        }
    </style>
</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' => 'View User')); ?>

                    <div class="row">
                        <!-- Left Column - User Profile -->
                        <div class="col-lg-4">
                            <div class="card">
                                <div class="profile-header text-center">
                                    <?php if ($user['profile_photo_url']): ?>
                                        <img src="<?php echo htmlspecialchars($user['profile_photo_url']); ?>" 
                                             alt="<?php echo htmlspecialchars($user['full_name']); ?>" 
                                             class="rounded-circle profile-avatar">
                                    <?php else: ?>
                                        <div class="avatar-xl mx-auto mb-3">
                                            <span class="avatar-title rounded-circle bg-white text-primary fs-1">
                                                <?php 
                                                $name = trim($user['full_name']);
                                                $parts = explode(' ', $name);
                                                $initials = '';
                                                foreach($parts as $part) {
                                                    if (!empty($part)) {
                                                        $initials .= strtoupper(substr($part, 0, 1));
                                                        if (strlen($initials) >= 2) break;
                                                    }
                                                }
                                                echo $initials ?: 'U';
                                                ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                    <h4 class="text-white mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h4>
                                    <p class="text-white-50 mb-2"><?php echo htmlspecialchars($user['role_name']); ?></p>
                                    <?php
                                    $status = $user['status'] ?? 'active';
                                    $status_colors = [
                                        'active' => 'success',
                                        'inactive' => 'secondary',
                                        'pending_verification' => 'warning',
                                        'banned' => 'danger'
                                    ];
                                    $status_color = $status_colors[$status] ?? 'secondary';
                                    ?>
                                    <span class="badge bg-<?php echo $status_color; ?> mb-2">
                                        <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                    </span>
                                </div>
                                <div class="card-body">
                                    <h5 class="card-title mb-3">Contact Information</h5>
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="text-muted">Email</td>
                                                    <td class="fw-medium">
                                                        <a href="mailto:<?php echo htmlspecialchars($user['email']); ?>">
                                                            <?php echo htmlspecialchars($user['email']); ?>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Phone</td>
                                                    <td class="fw-medium">
                                                        <?php if ($user['phone']): ?>
                                                            <a href="tel:<?php echo htmlspecialchars($user['phone']); ?>">
                                                                <?php echo htmlspecialchars($user['phone']); ?>
                                                            </a>
                                                        <?php else: ?>
                                                            <span class="text-muted">Not provided</span>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php if ($user['phone_secondary']): ?>
                                                <tr>
                                                    <td class="text-muted">Phone 2</td>
                                                    <td class="fw-medium">
                                                        <a href="tel:<?php echo htmlspecialchars($user['phone_secondary']); ?>">
                                                            <?php echo htmlspecialchars($user['phone_secondary']); ?>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                                <tr>
                                                    <td class="text-muted">Gender</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['gender'] ?? 'Not specified'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Date of Birth</td>
                                                    <td class="fw-medium">
                                                        <?php echo $user['dob'] ? date('M d, Y', strtotime($user['dob'])) : 'Not provided'; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Nationality</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['nationality'] ?? 'Not specified'); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                    <h5 class="card-title mb-3 mt-4">Address</h5>
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="text-muted">Postal Address</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['address_postal'] ?? 'Not provided'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">City</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['city'] ?? 'Not provided'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Country</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['country'] ?? 'Kenya'); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                    <h5 class="card-title mb-3 mt-4">Identification</h5>
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="text-muted">ID Type</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['id_type'] ?? 'National ID'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">ID Number</td>
                                                    <td class="fw-medium"><?php echo htmlspecialchars($user['id_number'] ?? 'Not provided'); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                    <h5 class="card-title mb-3 mt-4">Account Info</h5>
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <td class="text-muted">User ID</td>
                                                    <td class="fw-medium"><?php echo $user['id']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Created</td>
                                                    <td class="fw-medium">
                                                        <?php echo date('M d, Y', strtotime($user['created_at'])); ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Last Updated</td>
                                                    <td class="fw-medium">
                                                        <?php echo date('M d, Y', strtotime($user['updated_at'])); ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Last Login</td>
                                                    <td class="fw-medium">
                                                        <?php echo $user['last_login'] ? date('M d, Y h:i A', strtotime($user['last_login'])) : 'Never'; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">2FA</td>
                                                    <td class="fw-medium">
                                                        <?php echo $user['two_factor_enabled'] ? 
                                                            '<span class="badge bg-success">Enabled</span>' : 
                                                            '<span class="badge bg-secondary">Disabled</span>'; ?>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="mt-4">
                                        <a href="edit_user.php?id=<?php echo $user['id']; ?>" class="btn btn-primary w-100 mb-2">
                                            <i class="ri-pencil-line me-1"></i>Edit User
                                        </a>
                                        <a href="reset_password.php?id=<?php echo $user['id']; ?>" class="btn btn-soft-warning w-100 mb-2">
                                            <i class="ri-lock-password-line me-1"></i>Reset Password
                                        </a>
                                        <?php if ($user['status'] == 'active'): ?>
                                        <a href="deactivate_user.php?id=<?php echo $user['id']; ?>" 
                                           class="btn btn-soft-danger w-100"
                                           onclick="return confirm('Deactivate this user?')">
                                            <i class="ri-user-unfollow-line me-1"></i>Deactivate User
                                        </a>
                                        <?php else: ?>
                                        <a href="activate_user.php?id=<?php echo $user['id']; ?>" 
                                           class="btn btn-soft-success w-100"
                                           onclick="return confirm('Activate this user?')">
                                            <i class="ri-user-add-line me-1"></i>Activate User
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column - Additional Info -->
                        <div class="col-lg-8">
                            <!-- Role-Specific Information -->
                            <?php if ($user['role_name'] === 'Tenant' && isset($role_data['kyc'])): ?>
                            <div class="card info-card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Tenant KYC Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>KRA PIN:</strong> <?php echo htmlspecialchars($role_data['kyc']['kra_pin'] ?? 'N/A'); ?></p>
                                            <p><strong>Occupation:</strong> <?php echo htmlspecialchars($role_data['kyc']['occupation'] ?? 'N/A'); ?></p>
                                            <p><strong>Employer:</strong> <?php echo htmlspecialchars($role_data['kyc']['employer_name'] ?? 'N/A'); ?></p>
                                            <p><strong>Monthly Income:</strong> <?php echo htmlspecialchars($role_data['kyc']['monthly_income_range'] ?? 'N/A'); ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>Next of Kin:</strong> <?php echo htmlspecialchars($role_data['kyc']['nok_name'] ?? 'N/A'); ?></p>
                                            <p><strong>Relation:</strong> <?php echo htmlspecialchars($role_data['kyc']['nok_relation'] ?? 'N/A'); ?></p>
                                            <p><strong>NOK Phone:</strong> <?php echo htmlspecialchars($role_data['kyc']['nok_phone'] ?? 'N/A'); ?></p>
                                            <p><strong>Has Pets:</strong> <?php echo $role_data['kyc']['has_pets'] ? 'Yes - ' . $role_data['kyc']['pet_details'] : 'No'; ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <?php if (isset($role_data['leases']) && $role_data['leases']->num_rows > 0): ?>
                            <div class="card info-card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Lease History</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-sm">
                                            <thead>
                                                <tr>
                                                    <th>Property</th>
                                                    <th>Unit</th>
                                                    <th>Start Date</th>
                                                    <th>End Date</th>
                                                    <th>Rent</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($lease = $role_data['leases']->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($lease['property_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($lease['unit_number']); ?></td>
                                                    <td><?php echo date('M d, Y', strtotime($lease['start_date'])); ?></td>
                                                    <td><?php echo date('M d, Y', strtotime($lease['end_date'])); ?></td>
                                                    <td>KSh <?php echo number_format($lease['rent_amount'], 2); ?></td>
                                                    <td><span class="badge bg-<?php echo $lease['status'] == 'active' ? 'success' : 'secondary'; ?>">
                                                        <?php echo ucfirst($lease['status']); ?>
                                                    </span></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php elseif ($user['role_name'] === 'Landlord' && isset($role_data['properties'])): ?>
                            <div class="card info-card mb-3">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Owned Properties</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($role_data['properties']->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-sm">
                                            <thead>
                                                <tr>
                                                    <th>Property Name</th>
                                                    <th>Type</th>
                                                    <th>Location</th>
                                                    <th>Units</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($property = $role_data['properties']->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($property['name']); ?></td>
                                                    <td><?php echo htmlspecialchars($property['type']); ?></td>
                                                    <td><?php echo htmlspecialchars($property['location_area']); ?></td>
                                                    <td><?php echo $property['total_units']; ?></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <p class="text-muted">No properties owned yet</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Activity Log -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Recent Activity</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($activity_result && $activity_result->num_rows > 0): ?>
                                        <?php while($activity = $activity_result->fetch_assoc()): ?>
                                        <div class="activity-item mb-3">
                                            <div class="d-flex justify-content-between">
                                                <div>
                                                    <h6 class="mb-1">
                                                        <?php echo htmlspecialchars($activity['action_type']); ?> - 
                                                        <?php echo htmlspecialchars($activity['module']); ?>
                                                    </h6>
                                                    <?php if ($activity['ip_address']): ?>
                                                    <small class="text-muted">
                                                        IP: <?php echo htmlspecialchars($activity['ip_address']); ?>
                                                    </small>
                                                    <?php endif; ?>
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo date('M d, Y h:i A', strtotime($activity['timestamp'])); ?>
                                                </small>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <p class="text-muted text-center py-3">No activity recorded yet</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>