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

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

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

if (empty($tenant_id)) {
    header('Location: tenant_screening.php');
    exit();
}

// Get tenant details
$sql = "SELECT t.*, u.username, u.email as user_email
        FROM tenants t
        LEFT JOIN users u ON t.user_id = u.id
        WHERE t.tenant_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
$tenant = $result->fetch_assoc();

if (!$tenant) {
    header('Location: tenant_screening.php');
    exit();
}

// Get lease history
$sql_leases = "SELECT l.*, u.unit_number, p.property_name,
               COUNT(DISTINCT i.invoice_id) as total_invoices,
               COUNT(DISTINCT CASE WHEN i.status = 'OVERDUE' THEN i.invoice_id END) as overdue_invoices
               FROM leases l
               JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
               JOIN units u ON l.unit_id = u.unit_id
               JOIN properties p ON u.property_id = p.property_id
               LEFT JOIN invoices i ON l.lease_id = i.lease_id
               WHERE lt.tenant_id = ?
               GROUP BY l.lease_id
               ORDER BY l.start_date DESC";

$stmt_leases = $conn->prepare($sql_leases);
$stmt_leases->bind_param("i", $tenant_id);
$stmt_leases->execute();
$result_leases = $stmt_leases->get_result();

// Calculate risk score
$overdue_count = 0;
$active_leases = 0;
$total_leases = 0;
while($lease = $result_leases->fetch_assoc()) {
    $total_leases++;
    if ($lease['lease_status'] == 'ACTIVE') {
        $active_leases++;
    }
    $overdue_count += $lease['overdue_invoices'] ?? 0;
}
$result_leases->data_seek(0);

$risk_score = 0;
if ($overdue_count > 0) $risk_score += 30;
if ($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';
}

// Get payment history summary
$sql_payments = "SELECT 
                    COUNT(*) as total_payments,
                    SUM(amount) as total_paid,
                    MIN(payment_date) as first_payment,
                    MAX(payment_date) as last_payment
                 FROM rent_payments rp
                 JOIN leases l ON rp.lease_id = l.lease_id
                 JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
                 WHERE lt.tenant_id = ? AND rp.payment_status = 'COMPLETED'";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $tenant_id);
$stmt_payments->execute();
$result_payments = $stmt_payments->get_result();
$payment_stats = $result_payments->fetch_assoc();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="tenant_screening.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Screening
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <?php echo htmlspecialchars($tenant['first_name'] . ' ' . $tenant['last_name']); ?>
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Email:</strong> <?php echo htmlspecialchars($tenant['email'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>Phone:</strong> <?php echo htmlspecialchars($tenant['phone'] ?? 'N/A'); ?></p>
                                            <p class="mb-2"><strong>ID Number:</strong> <?php echo htmlspecialchars($tenant['id_number'] ?? 'Not provided'); ?></p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Emergency Contact:</strong> <?php echo htmlspecialchars($tenant['emergency_contact_name'] ?? 'Not provided'); ?></p>
                                            <p class="mb-2"><strong>Emergency Phone:</strong> <?php echo htmlspecialchars($tenant['emergency_contact_phone'] ?? 'N/A'); ?></p>
                                        </div>
                                    </div>

                                    <div class="alert alert-<?php echo $risk_color; ?> mb-3">
                                        <h5>Risk Assessment</h5>
                                        <p class="mb-0">
                                            <strong>Risk Level:</strong> <?php echo $risk_level; ?> (<?php echo $risk_score; ?>%)
                                            <br><strong>Score Breakdown:</strong>
                                            <?php if ($overdue_count > 0): ?>Overdue invoices: +30%<?php endif; ?>
                                            <?php if ($active_leases > 1): ?>Multiple active leases: +20%<?php endif; ?>
                                            <?php if (empty($tenant['id_number'])): ?>Missing ID: +25%<?php endif; ?>
                                            <?php if (empty($tenant['emergency_contact_name'])): ?>Missing emergency contact: +25%<?php endif; ?>
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Lease History</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Property/Unit</th>
                                                    <th>Period</th>
                                                    <th>Status</th>
                                                    <th>Invoices</th>
                                                    <th>Overdue</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_leases && $result_leases->num_rows > 0): ?>
                                                    <?php while($lease = $result_leases->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($lease['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($lease['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php echo date('M Y', strtotime($lease['start_date'])); ?> - 
                                                                <?php echo date('M Y', strtotime($lease['end_date'])); ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo strtolower($lease['lease_status']) == 'active' ? 'success' : 'secondary'; ?>">
                                                                    <?php echo htmlspecialchars($lease['lease_status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $lease['total_invoices']; ?></td>
                                                            <td>
                                                                <?php if ($lease['overdue_invoices'] > 0): ?>
                                                                    <span class="badge bg-soft-danger"><?php echo $lease['overdue_invoices']; ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-success">0</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No lease history</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Payment Statistics</h4>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <p class="mb-1 text-muted">Total Payments</p>
                                        <h4 class="mb-0"><?php echo $payment_stats['total_payments'] ?? 0; ?></h4>
                                    </div>
                                    <div class="mb-3">
                                        <p class="mb-1 text-muted">Total Paid</p>
                                        <h4 class="mb-0 text-success">KES <?php echo number_format($payment_stats['total_paid'] ?? 0, 2); ?></h4>
                                    </div>
                                    <?php if ($payment_stats['first_payment']): ?>
                                        <div class="mb-3">
                                            <p class="mb-1 text-muted">First Payment</p>
                                            <p class="mb-0"><?php echo date('M d, Y', strtotime($payment_stats['first_payment'])); ?></p>
                                        </div>
                                        <div class="mb-3">
                                            <p class="mb-1 text-muted">Last Payment</p>
                                            <p class="mb-0"><?php echo date('M d, Y', strtotime($payment_stats['last_payment'])); ?></p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

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