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

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

$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';

// Query tenants from users table (role_id = 4)
$sql = "SELECT u.*, 
               COUNT(DISTINCT l.id) as total_leases,
               COUNT(DISTINCT CASE WHEN l.status = 'active' THEN l.id END) as active_leases,
               tk.occupation, tk.employer_name
        FROM users u
        LEFT JOIN tenant_kyc tk ON u.id = tk.user_id
        LEFT JOIN leases l ON u.id = l.tenant_id
        WHERE u.role_id = 4";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

if (!empty($status_filter)) {
    $sql .= " AND u.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$sql .= " GROUP BY u.id ORDER BY u.first_name, u.last_name ASC";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

// Get status counts for stats
$stats_sql = "SELECT 
                COUNT(*) as total,
                COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
                COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive
              FROM users WHERE role_id = 4";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Tenants')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .stats-card {
            border-left: 4px solid;
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }
        .stats-card.primary {
            border-left-color: #405189;
        }
        .stats-card.success {
            border-left-color: #0ab39c;
        }
        .stats-card.warning {
            border-left-color: #f7b84b;
        }
        .tenant-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 14px;
        }
        .card {
            box-shadow: 0 0.75rem 1.5rem rgba(18,38,63,.03);
            border: 1px solid #e9ebec;
        }
        .search-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        }
        .table thead th {
            background-color: #f3f6f9;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 11px;
            letter-spacing: 0.5px;
            color: #405189;
            border-bottom: 2px solid #e9ebec;
        }
        .table tbody tr {
            transition: all 0.2s ease;
        }
        .table tbody tr:hover {
            background-color: #f8f9fa;
            transform: scale(1.01);
        }
        .badge-custom {
            padding: 6px 12px;
            font-weight: 500;
            font-size: 11px;
        }
        .btn-action {
            transition: all 0.2s ease;
        }
        .btn-action:hover {
            transform: translateY(-2px);
        }
    </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' => 'Tenant Management', 'title' => 'Tenants')); ?>

                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible alert-border-left fade show" role="alert">
                            <i class="ri-check-double-line me-2 align-middle fs-16"></i>
                            <?php echo htmlspecialchars($_SESSION['success_message']); unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="card stats-card primary mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                    <i class="ri-user-3-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Total Tenants</p>
                                            <h4 class="mb-0"><?php echo $stats['total']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card stats-card success mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success text-success rounded-circle fs-3">
                                                    <i class="ri-user-star-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Active Tenants</p>
                                            <h4 class="mb-0"><?php echo $stats['active']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card stats-card warning mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning text-warning rounded-circle fs-3">
                                                    <i class="ri-user-unfollow-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Inactive Tenants</p>
                                            <h4 class="mb-0"><?php echo $stats['inactive']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card search-card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3 align-items-end">
                                        <div class="col-md-5">
                                            <label class="form-label fw-semibold">
                                                <i class="ri-search-line me-1"></i>Search Tenants
                                            </label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by name, email, or phone">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label fw-semibold">
                                                <i class="ri-filter-3-line me-1"></i>Status
                                            </label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                                                <option value="inactive" <?php echo $status_filter == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="banned" <?php echo $status_filter == 'banned' ? 'selected' : ''; ?>>Banned</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-primary w-100 btn-action">
                                                <i class="ri-search-line me-1"></i>Search
                                            </button>
                                        </div>
                                        <div class="col-md-2">
                                            <a href="list_tenants.php" class="btn btn-light w-100">
                                                <i class="ri-refresh-line me-1"></i>Reset
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tenants Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex" style="background: linear-gradient(135deg, #405189 0%, #556ee6 100%); color: white;">
                                    <h4 class="card-title mb-0 flex-grow-1 text-white">
                                        <i class="ri-team-line me-2"></i>All Tenants
                                    </h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_tenant.php" class="btn btn-light btn-action">
                                            <i class="ri-add-line align-bottom me-1"></i>Add Tenant
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Tenant</th>
                                                    <th>Contact</th>
                                                    <th>ID Number</th>
                                                    <th>Occupation</th>
                                                    <th>Leases</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($tenant = $result->fetch_assoc()): ?>
                                                        <?php
                                                        $initials = strtoupper(substr($tenant['first_name'], 0, 1) . substr($tenant['last_name'], 0, 1));
                                                        $colors = ['primary', 'success', 'info', 'warning', 'danger'];
                                                        $color = $colors[array_sum(array_map('ord', str_split($initials))) % count($colors)];
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="tenant-avatar bg-soft-<?php echo $color; ?> text-<?php echo $color; ?> me-2">
                                                                        <?php echo $initials; ?>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="fs-14 mb-0 fw-semibold">
                                                                            <?php echo htmlspecialchars($tenant['first_name'] . ' ' . $tenant['last_name']); ?>
                                                                        </h5>
                                                                        <p class="text-muted mb-0 small"><?php echo htmlspecialchars($tenant['city'] ?? ''); ?></p>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <i class="ri-mail-line text-muted me-1"></i>
                                                                    <span class="small"><?php echo htmlspecialchars($tenant['email'] ?? 'N/A'); ?></span>
                                                                </div>
                                                                <div class="mt-1">
                                                                    <i class="ri-phone-line text-muted me-1"></i>
                                                                    <span class="small"><?php echo htmlspecialchars($tenant['phone'] ?? 'N/A'); ?></span>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-secondary text-secondary badge-custom">
                                                                    <?php echo htmlspecialchars($tenant['id_number'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <span class="fw-medium"><?php echo htmlspecialchars($tenant['occupation'] ?? 'N/A'); ?></span>
                                                                    <?php if (!empty($tenant['employer_name'])): ?>
                                                                        <p class="text-muted mb-0 small">at <?php echo htmlspecialchars($tenant['employer_name']); ?></p>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info badge-custom">
                                                                    <i class="ri-file-list-line me-1"></i>
                                                                    <?php echo $tenant['active_leases'] ?? 0; ?> Active
                                                                </span>
                                                                <small class="text-muted d-block mt-1">
                                                                    <?php echo $tenant['total_leases'] ?? 0; ?> Total
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status = $tenant['status'] ?? 'active';
                                                                $status_colors = [
                                                                    'active' => 'success',
                                                                    'inactive' => 'warning',
                                                                    'banned' => 'danger',
                                                                    'pending_verification' => 'info'
                                                                ];
                                                                $badge_color = $status_colors[$status] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $badge_color; ?> text-<?php echo $badge_color; ?> badge-custom">
                                                                    <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        <i class="ri-more-2-fill"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="tenant_details.php?id=<?php echo $tenant['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View Details
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="add_tenant.php?id=<?php echo $tenant['id']; ?>">
                                                                                <i class="ri-pencil-line align-bottom me-2 text-muted"></i>Edit
                                                                            </a>
                                                                        </li>
                                                                        <li><hr class="dropdown-divider"></li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="create_lease.php?tenant_id=<?php echo $tenant['id']; ?>">
                                                                                <i class="ri-file-add-line align-bottom me-2 text-success"></i>Create Lease
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="tenant_invoices.php?tenant_id=<?php echo $tenant['id']; ?>">
                                                                                <i class="ri-bill-line align-bottom me-2 text-info"></i>View Invoices
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-5">
                                                            <div class="text-muted">
                                                                <i class="ri-user-add-line fs-48 text-primary"></i>
                                                                <p class="mt-3 fs-15">No tenants found</p>
                                                                <a href="add_tenant.php" class="btn btn-primary mt-2">
                                                                    <i class="ri-add-line me-1"></i>Add Your First Tenant
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

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