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

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

$tenant_id = $_GET['tenant_id'] ?? '';
$search = $_GET['search'] ?? '';

$sql = "SELECT t.*, 
               COUNT(DISTINCT l.lease_id) as total_leases,
               COUNT(DISTINCT CASE WHEN l.lease_status = 'ACTIVE' THEN l.lease_id END) as active_leases,
               COUNT(DISTINCT i.invoice_id) as total_invoices,
               COUNT(DISTINCT CASE WHEN i.status = 'OVERDUE' THEN i.invoice_id END) as overdue_invoices
        FROM tenants t
        LEFT JOIN lease_tenants lt ON t.tenant_id = lt.tenant_id
        LEFT JOIN leases l ON lt.lease_id = l.lease_id
        LEFT JOIN invoices i ON l.lease_id = i.lease_id
        WHERE 1=1";

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

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

if (!empty($tenant_id)) {
    $sql .= " AND t.tenant_id = ?";
    $params[] = $tenant_id;
    $types .= 'i';
}

$sql .= " GROUP BY t.tenant_id ORDER BY t.first_name, t.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);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Tenant Screening')); ?>
    <?php include 'layouts/head-css.php'; ?>
</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' => 'Tenant Screening')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-10">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by name, email, phone, or ID number">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Search
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Tenant Screening Report</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Tenant</th>
                                                    <th>Contact</th>
                                                    <th>ID Number</th>
                                                    <th>Active Leases</th>
                                                    <th>Total Invoices</th>
                                                    <th>Overdue</th>
                                                    <th>Risk Score</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($tenant = $result->fetch_assoc()): 
                                                        $overdue_count = $tenant['overdue_invoices'] ?? 0;
                                                        $risk_score = 0;
                                                        if ($overdue_count > 0) $risk_score += 30;
                                                        if ($tenant['active_leases'] > 1) $risk_score += 20;
                                                        if (empty($tenant['id_number'])) $risk_score += 25;
                                                        if (empty($tenant['emergency_contact_name'])) $risk_score += 25;
                                                        
                                                        $risk_level = 'Low';
                                                        $risk_color = 'success';
                                                        if ($risk_score >= 50) {
                                                            $risk_level = 'High';
                                                            $risk_color = 'danger';
                                                        } elseif ($risk_score >= 30) {
                                                            $risk_level = 'Medium';
                                                            $risk_color = 'warning';
                                                        }
                                                    ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="avatar-xs me-2">
                                                                        <span class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                                            <?php echo strtoupper(substr($tenant['first_name'], 0, 1) . substr($tenant['last_name'], 0, 1)); ?>
                                                                        </span>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="fs-14 mb-0">
                                                                            <?php echo htmlspecialchars($tenant['first_name'] . ' ' . $tenant['last_name']); ?>
                                                                        </h5>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <p class="mb-0"><?php echo htmlspecialchars($tenant['email'] ?? 'N/A'); ?></p>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($tenant['phone'] ?? 'N/A'); ?></small>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($tenant['id_number'] ?? 'Not provided'); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo $tenant['active_leases'] ?? 0; ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $tenant['total_invoices'] ?? 0; ?></td>
                                                            <td>
                                                                <?php if ($overdue_count > 0): ?>
                                                                    <span class="badge bg-soft-danger text-danger">
                                                                        <?php echo $overdue_count; ?> Overdue
                                                                    </span>
                                                                <?php else: ?>
                                                                    <span class="text-success">None</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $risk_color; ?> text-<?php echo $risk_color; ?>">
                                                                    <?php echo $risk_level; ?> (<?php echo $risk_score; ?>%)
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="tenant_screening_details.php?id=<?php echo $tenant['tenant_id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i> View Details
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No tenants found</p>
                                                            </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>
