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

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

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

if (empty($lease_id)) {
    header('Location: list_leases.php');
    exit();
}

// Get lease details
$sql = "SELECT l.*, u.unit_number, u.bedrooms, u.bathrooms, p.property_name, p.property_code, p.location_area
        FROM leases l
        JOIN units u ON l.unit_id = u.unit_id
        JOIN properties p ON u.property_id = p.property_id
        WHERE l.lease_id = ?";

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

if (!$lease) {
    header('Location: list_leases.php');
    exit();
}

// Get tenants on this lease
$sql_tenants = "SELECT t.*, lt.is_primary
                FROM tenants t
                JOIN lease_tenants lt ON t.tenant_id = lt.tenant_id
                WHERE lt.lease_id = ?
                ORDER BY lt.is_primary DESC";

$stmt_tenants = $conn->prepare($sql_tenants);
$stmt_tenants->bind_param("i", $lease_id);
$stmt_tenants->execute();
$result_tenants = $stmt_tenants->get_result();

// Get invoices
$sql_invoices = "SELECT * FROM invoices 
                 WHERE lease_id = ? 
                 ORDER BY due_date DESC LIMIT 12";

$stmt_invoices = $conn->prepare($sql_invoices);
$stmt_invoices->bind_param("i", $lease_id);
$stmt_invoices->execute();
$result_invoices = $stmt_invoices->get_result();

// Get payments
$sql_payments = "SELECT * FROM rent_payments 
                 WHERE lease_id = ? 
                 ORDER BY payment_date DESC LIMIT 12";

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

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

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_leases.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Leases
                            </a>
                            <a href="create_lease.php?id=<?php echo $lease_id; ?>" class="btn btn-primary ms-2">
                                <i class="ri-edit-line me-1"></i>Edit Lease
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Lease <?php echo htmlspecialchars($lease['lease_code']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Property:</strong> 
                                                <a href="property_details.php?id=<?php echo $lease['property_id']; ?>">
                                                    <?php echo htmlspecialchars($lease['property_name']); ?>
                                                </a>
                                            </p>
                                            <p class="mb-2"><strong>Unit:</strong> 
                                                <a href="unit_details.php?id=<?php echo $lease['unit_id']; ?>">
                                                    <?php echo htmlspecialchars($lease['unit_number']); ?>
                                                </a>
                                            </p>
                                            <p class="mb-2"><strong>Location:</strong> <?php echo htmlspecialchars($lease['location_area']); ?></p>
                                            <p class="mb-2"><strong>Lease Period:</strong> 
                                                <?php echo date('M d, Y', strtotime($lease['start_date'])); ?> to 
                                                <?php echo date('M d, Y', strtotime($lease['end_date'])); ?>
                                            </p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Rent Amount:</strong> KES <?php echo number_format($lease['rent_amount'], 2); ?> / <?php echo htmlspecialchars($lease['payment_frequency'] ?? 'month'); ?></p>
                                            <p class="mb-2"><strong>Due Day:</strong> <?php echo $lease['due_day'] ?? 'N/A'; ?> of each month</p>
                                            <p class="mb-2"><strong>Status:</strong> 
                                                <span class="badge bg-soft-<?php echo strtolower($lease['lease_status']) == 'active' ? 'success' : 'secondary'; ?>">
                                                    <?php echo htmlspecialchars($lease['lease_status']); ?>
                                                </span>
                                            </p>
                                            <p class="mb-2"><strong>Security Deposit:</strong> KES <?php echo number_format($lease['security_deposit'] ?? 0, 2); ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Tenants</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Type</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_tenants && $result_tenants->num_rows > 0): ?>
                                                    <?php while($tenant = $result_tenants->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($tenant['first_name'] . ' ' . $tenant['last_name']); ?>
                                                                    </h5>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($tenant['email'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($tenant['phone'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <?php if ($tenant['is_primary']): ?>
                                                                    <span class="badge bg-soft-primary">Primary</span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-soft-secondary">Co-tenant</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No tenants assigned</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Invoices</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Amount</th>
                                                    <th>Balance</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_invoices && $result_invoices->num_rows > 0): ?>
                                                    <?php while($invoice = $result_invoices->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                                            <td>KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="fw-semibold <?php echo $invoice['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $invoice['status'] == 'paid' ? 'success' : 'danger'; ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="invoice_details.php?id=<?php echo $invoice['invoice_id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <div class="text-muted">No invoices found</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">Recent Payments</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Amount</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_payments && $result_payments->num_rows > 0): ?>
                                                    <?php while($payment = $result_payments->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-success"><?php echo htmlspecialchars($payment['payment_status']); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="3" class="text-center py-4">
                                                            <div class="text-muted">No payments found</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>
