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

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

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

$sql = "SELECT l.*, p.property_name, p.property_code, u.unit_number, 
               t.first_name, t.last_name, t.email, t.phone
        FROM leases l
        JOIN units u ON l.unit_id = u.unit_id
        JOIN properties p ON u.property_id = p.property_id
        JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
        JOIN tenants t ON lt.tenant_id = t.tenant_id
        WHERE 1=1";

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

if (!empty($search)) {
    $sql .= " AND (l.lease_code LIKE ? OR t.first_name LIKE ? OR t.last_name LIKE ? OR p.property_name LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

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

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

$sql .= " ORDER BY l.created_at DESC";

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY property_name";
$result_properties = $conn->query($sql_properties);

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' => 'Leases')); ?>
    <?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' => 'Lease Management', 'title' => 'Lease Agreements')); ?>

                    <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-4">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by lease code, tenant, or property">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Property</label>
                                            <select class="form-select" name="property_id">
                                                <option value="">All Properties</option>
                                                <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                    <option value="<?php echo $prop['property_id']; ?>" 
                                                            <?php echo $property_id == $prop['property_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['property_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">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="EXPIRED" <?php echo $status_filter == 'EXPIRED' ? 'selected' : ''; ?>>Expired</option>
                                                <option value="TERMINATED" <?php echo $status_filter == 'TERMINATED' ? 'selected' : ''; ?>>Terminated</option>
                                            </select>
                                        </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>Filter
                                                </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">All Leases</h4>
                                    <div class="flex-shrink-0">
                                        <a href="create_lease.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i>Create Lease
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Lease Code</th>
                                                    <th>Tenant</th>
                                                    <th>Property/Unit</th>
                                                    <th>Start Date</th>
                                                    <th>End Date</th>
                                                    <th>Rent Amount</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($lease = $result->fetch_assoc()): ?>
                                                        <?php
                                                        $end_date = strtotime($lease['end_date']);
                                                        $today = strtotime('today');
                                                        $days_left = round(($end_date - $today) / (60 * 60 * 24));
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($lease['lease_code']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($lease['first_name'] . ' ' . $lease['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($lease['email']); ?></p>
                                                                </div>
                                                            </td>
                                                            <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 d, Y', strtotime($lease['start_date'])); ?></td>
                                                            <td>
                                                                <?php if ($days_left < 0): ?>
                                                                    <span class="text-danger"><?php echo date('M d, Y', $end_date); ?></span>
                                                                    <small class="d-block text-danger">Expired</small>
                                                                <?php elseif ($days_left <= 30): ?>
                                                                    <span class="text-warning"><?php echo date('M d, Y', $end_date); ?></span>
                                                                    <small class="d-block text-warning"><?php echo $days_left; ?> days left</small>
                                                                <?php else: ?>
                                                                    <?php echo date('M d, Y', $end_date); ?>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($lease['rent_amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'ACTIVE' => 'success',
                                                                    'EXPIRED' => 'danger',
                                                                    'TERMINATED' => 'secondary'
                                                                ];
                                                                $color = $status_colors[$lease['lease_status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo $lease['lease_status']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="lease_details.php?id=<?php echo $lease['lease_id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="create_lease.php?id=<?php echo $lease['lease_id']; ?>">
                                                                                <i class="ri-pencil-line align-bottom me-2 text-muted"></i>Edit
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </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 leases found</p>
                                                                <a href="create_lease.php" class="btn btn-primary btn-sm mt-2">
                                                                    <i class="ri-add-line me-1"></i>Create First Lease
                                                                </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>
