<?php
$title = 'Rented Properties Management';
$active = 'rented';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// Ensure variables are defined with proper fallbacks
$properties = isset($properties) ? $properties : [];
$statistics = isset($statistics) ? $statistics : [
    'total' => 0,
    'total_annual_rent' => 0,
    'expiring_soon' => 0,
    'expired' => 0,
    'by_status' => []
];

// Get expiring and expired properties from the passed data
$expiringSoon = [];
$expired = [];

foreach ($properties as $property) {
    if (!empty($property['expiry_date'])) {
        $today = date('Y-m-d');
        $expiryDate = $property['expiry_date'];
        
        if ($expiryDate < $today) {
            $expired[] = $property;
        } elseif ($expiryDate <= date('Y-m-d', strtotime('+30 days'))) {
            $expiringSoon[] = $property;
        }
    }
}

// Ensure each property has a status value (from create.php)
foreach ($properties as &$property) {
    // If status is not set in the property data, default to 'Developed' or empty
    if (!isset($property['status']) || empty($property['status'])) {
        $property['status'] = 'Developed'; // Default status
    }
}

// Limit to 5 each for display
$expiringSoon = array_slice($expiringSoon, 0, 5);
$expired = array_slice($expired, 0, 5);
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-house-user"></i>
                Rented Properties Management
            </h1>
            <p>Manage all leased and rented properties</p>
        </div>
        <div class="header-actions">
            <?php if (Auth::can('rented.create')): ?>
            <a href="<?php echo BASE_URL; ?>/rented/create" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> Add New Property
            </a>
            <?php endif; ?>
            <?php if (Auth::can('reports.export')): ?>
            <a href="<?php echo BASE_URL; ?>/rented/export" class="btn btn-outline">
                <i class="fas fa-download"></i> Export
            </a>
            <?php endif; ?>
        </div>
    </div>
    
    
    <!-- Success Message Display -->
<?php
$successMessage = Session::get('success', '');
if (!empty($successMessage)):
?>
<div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert">
    <i class="fas fa-check-circle"></i>
    <?php echo Security::escape($successMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('success');
endif; 
?>

<?php
$errorMessage = Session::get('error', '');
if (!empty($errorMessage)):
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert">
    <i class="fas fa-exclamation-circle"></i>
    <?php echo Security::escape($errorMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('error');
endif; 
?>

<!-- Statistics Cards - Using New Styling -->
<div class="stats-grid">
    <!-- Total Properties Card -->
    <div class="stat-card">
        <div class="stat-icon total">
            <i class="fas fa-building"></i>
        </div>
        <div class="stat-details">
            <h4>Total Properties</h4>
            <p class="stat-number"><?php echo number_format($statistics['total'] ?? 0); ?></p>
        </div>
    </div>
    
    <!-- Annual Rent Card -->
    <div class="stat-card">
        <div class="stat-icon value">
            <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="stat-details">
            <h4>Annual Rent</h4>
            <p class="stat-number value-large">₦<?php echo number_format($statistics['total_annual_rent'] ?? 0, 2); ?></p>
        </div>
    </div>
    
    <!-- Expired Properties Card -->
    <div class="stat-card">
        <div class="stat-icon maintenance">
            <i class="fas fa-exclamation-circle"></i>
        </div>
        <div class="stat-details">
            <h4>Expired</h4>
            <p class="stat-number"><?php echo number_format($statistics['expired'] ?? 0); ?></p>
        </div>
    </div>
    
    <!-- Property Status Cards -->
    <?php 
$statusIcons = [
    'Developed' => ['icon' => 'fa-check-circle', 'class' => 'total'],
    'Under Developed' => ['icon' => 'fa-chart-line', 'class' => 'maintenance'],
    'Fenced' => ['icon' => 'fa-shield-alt', 'class' => 'in-use'],
    'Not Fenced' => ['icon' => 'fa-ban', 'class' => 'maintenance'],
    'Under Litigation' => ['icon' => 'fa-gavel', 'class' => 'value']
];
    
    // Define statuses to display (order matters)
    $displayStatuses = ['Developed', 'Under Developed', 'Fenced', 'Not Fenced', 'Under Litigation'];
    
    foreach ($displayStatuses as $status):
        $count = $statistics['by_status'][$status] ?? 0;
        $icon = $statusIcons[$status]['icon'] ?? 'fa-chart-simple';
        $iconClass = $statusIcons[$status]['class'] ?? 'total';
    ?>
    <div class="stat-card">
        <div class="stat-icon <?php echo $iconClass; ?>">
            <i class="fas <?php echo $icon; ?>"></i>
        </div>
        <div class="stat-details">
            <h4><?php echo $status; ?></h4>
            <p class="stat-number"><?php echo number_format($count); ?></p>
        </div>
    </div>
    <?php endforeach; ?>
</div>


<!-- Alerts for Expiring/Expired Leases -->
<!--<?php if (!empty($expiringSoon) || !empty($expired)): ?>-->
<!--<div class="alerts-row">-->
<!--    <?php if (!empty($expiringSoon)): ?>-->
<!--        <div class="alert alert-warning alert-inline">-->
<!--            <i class="fas fa-clock"></i>-->
<!--            <div class="alert-content">-->
<!--                <strong>Leases Expiring Soon:</strong>-->
<!--                <ul>-->
<!--                    <?php foreach ($expiringSoon as $prop): ?>-->
<!--                    <li>-->
<!--                        <?php echo Security::escape($prop['property_address'] ?? ''); ?> - -->
<!--                        Expires <?php echo date('d/m/Y', strtotime($prop['expiry_date'])); ?>-->
<!--                        (<?php echo (int)((strtotime($prop['expiry_date']) - time()) / 86400); ?> days)-->
<!--                    </li>-->
<!--                    <?php endforeach; ?>-->
<!--                </ul>-->
<!--            </div>-->
<!--        </div>-->
<!--    <?php endif; ?>-->
    
<!--    <?php if (!empty($expired)): ?>-->
<!--        <div class="alert alert-danger alert-inline">-->
<!--            <i class="fas fa-exclamation-circle"></i>-->
<!--            <div class="alert-content">-->
<!--                <strong>Expired Leases:</strong>-->
<!--                <ul>-->
<!--                    <?php foreach ($expired as $prop): ?>-->
<!--                    <li>-->
<!--                        <?php echo Security::escape($prop['property_address'] ?? ''); ?> - -->
<!--                        Expired <?php echo date('d/m/Y', strtotime($prop['expiry_date'])); ?>-->
<!--                    </li>-->
<!--                    <?php endforeach; ?>-->
<!--                </ul>-->
<!--            </div>-->
<!--        </div>-->
<!--    <?php endif; ?>-->
<!--</div>-->
<!--<?php endif; ?>-->

    <!-- Filters -->
    <div class="filter-section">
        <div class="filter-header" onclick="toggleFilters()">
            <h3><i class="fas fa-filter"></i> Filter Properties</h3>
            <i class="fas fa-chevron-down" id="filterToggleIcon"></i>
        </div>
        <div class="filter-body" id="filterBody" style="display: none;">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" id="searchProperties" placeholder="Search by address, lessor...">
                </div>
                <div class="filter-group">
                    <label>Purpose</label>
                    <select id="filterPurpose">
                        <option value="">All Purposes</option>
                        <option value="Command/Formation">Command/Formation</option>
                        <option value="Area Office">Area Office</option>
                        <option value="Divitional Office">Divitional Office</option>
                        <option value="PPT Office">PPT Office</option>
                        <option value="Control Post">Control Post</option>
                        <option value="Barracks/Transit Camp">Barracks/Transit Camp</option>
                        <option value="FOM/MOB">FOM/MOB</option>
                        <option value="E-Border">E-Border</option>
                        <option value="Flag House">Flag House</option>
                        <option value="Zonal Command">Zonal Command</option>
                        <option value="Migrant Holding Center">Migrant Holding Center</option>
                        <option value="Staff Quarters">Staff Quarters</option>
                        <option value="Office Space">Office Space</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select id="filterStatus">
                        <option value="">All Status</option>
                        <option value="Developed">Developed</option>
                        <option value="Under Developed">Under Developed</option>
                        <option value="Fenced">Fenced</option>
                        <option value="Not Fenced">Not Fenced</option>
                        <option value="Under Litigation">Under Litigation</option>
                        <option value="Others">Others</option>
                        <option value="Active">Active (Rental)</option>
                        <option value="Expiring Soon">Expiring Soon</option>
                        <option value="Expired">Expired</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Zone</label>
                    <select id="filterZone">
                        <option value="">All Zones</option>
                        <?php
                        // This should come from controller, but for now we'll keep it
                        // In a real MVC app, this should also be passed from controller
                        $zones = Database::fetchAll("SELECT * FROM zones ORDER BY zone_name");
                        if ($zones && is_array($zones)):
                            foreach ($zones as $zone):
                        ?>
                        <option value="<?php echo $zone['id']; ?>"><?php echo Security::escape($zone['zone_name']); ?></option>
                        <?php 
                            endforeach;
                        endif;
                        ?>
                    </select>
                </div>
            </div>
            <div class="filter-actions">
                <button class="btn btn-primary" onclick="applyFilters()">
                    <i class="fas fa-filter"></i> Apply Filters
                </button>
                <button class="btn btn-outline" onclick="resetFilters()">
                    <i class="fas fa-times"></i> Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Properties Table -->
    <div class="content-card">
        <div class="section-title">
            <h2><i class="fas fa-list"></i> Rented Properties Register</h2>
            <div class="card-actions">
                <span class="record-count">Showing <span id="recordCount"><?php echo count($properties); ?></span> records</span>
            </div>
        </div>

        <div class="table-responsive">
            <?php if (empty($properties)): ?>
                <div class="empty-state">
                    <i class="fas fa-house-user"></i>
                    <p>No rented properties found</p>
                    <?php if (Auth::can('rented.create')): ?>
                    <a href="<?php echo BASE_URL; ?>/rented/create" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add First Property
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="propertiesTable">
                <thead>
                    <tr>
                        <th data-sort="text">S/N</th>
                        <th data-sort="text">Asset Code</th>
                        <th data-sort="text">Address</th>
                        <th data-sort="text">Lessor</th>
                        <th data-sort="text">Purpose</th>
                        <th data-sort="date">Start Date</th>
                        <th data-sort="date">Expiry Date</th>
                        <th data-sort="number">Annual Rent (₦)</th>
                        <th data-sort="text">Status</th>
                        <th data-sort="text">Documents</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($properties as $index => $property): 
                        $today = time();
                        $expiry = !empty($property['expiry_date']) ? strtotime($property['expiry_date']) : null;
                        $daysRemaining = $expiry ? floor(($expiry - $today) / 86400) : null;
                        
                        $statusClass = 'status-active';
                        $statusText = 'Active';
                        
                        if ($expiry && $expiry < $today) {
                            $statusClass = 'status-rejected';
                            $statusText = 'Expired';
                        } elseif ($expiry && $daysRemaining <= 30 && $daysRemaining > 0) {
                            $statusClass = 'status-warning';
                            $statusText = 'Expiring Soon';
                        }
                    ?>
                    <tr data-purpose="<?php echo $property['purpose'] ?? ''; ?>" 
                        data-status="<?php echo $property['status'] ?? ''; ?>"
                        data-rental-status="<?php echo $statusText; ?>"
                        data-zone="<?php echo $property['zone_id'] ?? ''; ?>"
                        data-expiry="<?php echo $property['expiry_date'] ?? ''; ?>">
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <span class="asset-code"><?php echo Security::escape($property['asset_code'] ?? ''); ?></span>
                        </td>
                        <td><?php echo Security::escape(substr($property['property_address'] ?? '', 0, 50)) . (strlen($property['property_address'] ?? '') > 50 ? '...' : ''); ?></td>
                        <td><?php echo Security::escape($property['owner_lessor_name'] ?? ''); ?></td>
                        <td>
                            <span class="badge badge-info"><?php echo Security::escape($property['purpose'] ?? ''); ?></span>
                        </td>
                        <td><?php echo !empty($property['start_date']) ? date('d/m/Y', strtotime($property['start_date'])) : '-'; ?></td>
                        <td>
                            <?php if (!empty($property['expiry_date'])): ?>
                                <span class="<?php echo $statusClass === 'status-warning' ? 'expiry-warning' : ($statusClass === 'status-rejected' ? 'expiry-danger' : ''); ?>">
                                    <?php echo date('d/m/Y', strtotime($property['expiry_date'])); ?>
                                    <?php if ($daysRemaining && $daysRemaining <= 30 && $daysRemaining > 0): ?>
                                        <br><small class="expiry-warning"><?php echo $daysRemaining; ?> days left</small>
                                    <?php elseif ($expiry && $expiry < $today): ?>
                                        <br><small class="expiry-danger">Expired</small>
                                    <?php endif; ?>
                                </span>
                            <?php else: ?>
                                N/A
                            <?php endif; ?>
                        </td>
                        <td class="text-right">₦<?php echo number_format($property['annual_rent'] ?? 0, 2); ?></td>
                        <td>
                            <span class="status-badge <?php echo $statusClass; ?>">
                                <?php echo $statusText; ?>
                            </span>
                        </td>
                        <td>
                            <?php 
                            // Document count - this should ideally come from controller
                            $docCount = 0;
                            ?>
                            <?php if ($docCount > 0): ?>
                                <span class="document-badge" title="<?php echo $docCount; ?> document(s)">
                                    <i class="fas fa-paperclip"></i> <?php echo $docCount; ?>
                                </span>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?php echo BASE_URL; ?>/rented/show/<?php echo $property['id'] ?? ''; ?>" 
                                   class="btn-icon" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (Auth::can('rented.edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/rented/edit/<?php echo $property['id'] ?? ''; ?>" 
                                   class="btn-icon" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (Auth::can('rented.delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/rented/delete/<?php echo $property['id'] ?? ''; ?>" 
                                   class="btn-icon delete" title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this property?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        
        <!-- Pagination -->
        <div class="pagination" id="pagination"></div>
    </div>
</div>

<style>
/* Stats Grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 25px;
}

.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.stat-icon.total {
    background: #e3f2fd;
    color: #1976d2;
}

.stat-icon.in-use {
    background: #e8f5e9;
    color: #388e3c;
}

.stat-icon.maintenance {
    background: #fff3e0;
    color: #f57c00;
}

.stat-icon.value {
    background: #e0f2f1;
    color: #00796b;
}

.stat-details h4 {
    margin: 0 0 5px 0;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.stat-number {
    font-size: 1.8rem;
    font-weight: bold;
    margin: 0;
    color: var(--text-primary);
    line-height: 1.2;
}

/* Large value handling */
.stat-number.value-large {
    font-size: 1.4rem;
    word-break: break-word;
    overflow-wrap: break-word;
    max-width: 100%;
    line-height: 1.3;
}

@media (max-width: 1200px) {
    .stat-number.value-large {
        font-size: 1.2rem;
    }
}

@media (max-width: 768px) {
    .stat-number.value-large {
        font-size: 1rem;
    }
}


/* Filter Section */
.filter-section {
    background: white;
    border-radius: 10px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    overflow: hidden;
}

.filter-header {
    padding: 12px 15px;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
    color: white;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.filter-header h3 {
    margin: 0;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 6px;
}

.filter-body {
    padding: 15px;
    border-bottom: 1px solid var(--border-color);
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
    margin-bottom: 12px;
}

.filter-group {
    display: flex;
    flex-direction: column;
}

.filter-group label {
    font-size: 0.75rem;
    color: var(--text-secondary);
    margin-bottom: 3px;
    font-weight: 600;
}

.filter-group input,
.filter-group select {
    padding: 6px 10px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    font-size: 0.8rem;
}

.filter-actions {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
}

/* Badge Styles */
.badge {
    display: inline-block;
    padding: 3px 6px;
    border-radius: 3px;
    font-size: 0.7rem;
    font-weight: 500;
}

.badge-info {
    background: #e0f2f1;
    color: #00695c;
}

/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: 600;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-warning {
    background: #fff3cd;
    color: #856404;
}

.status-rejected {
    background: #f8d7da;
    color: #721c24;
}

/* Expiry Styles */
.expiry-warning {
    color: #f39c12;
    font-weight: 600;
}

.expiry-danger {
    color: #e74c3c;
    font-weight: 600;
}

/* Document Badge */
.document-badge {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    padding: 3px 6px;
    background: #e8f5e8;
    color: var(--success-color);
    border-radius: 10px;
    font-size: 0.7rem;
    font-weight: 500;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid var(--border-color);
}

.page-link {
    padding: 6px 10px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s;
    font-size: 0.8rem;
}

.page-link:hover {
    background: var(--light-bg);
    border-color: var(--success-color);
}

.page-link.active {
    background: var(--success-color);
    color: white;
    border-color: var(--success-color);
}

.page-info {
    color: var(--text-secondary);
    font-size: 0.8rem;
}

.text-center {
    text-align: center;
}

.text-right {
    text-align: right;
}

@media (max-width: 768px) {
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-actions {
        flex-direction: column;
    }
}

/* Alert Styles */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.alert i {
    font-size: 1.2rem;
}

.btn-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
}

.btn-close:hover {
    opacity: 1;
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}
</style>

<script>
let currentPage = 1;
const rowsPerPage = 10;
let filteredRows = [];

function toggleFilters() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    
    if (filterBody.style.display === 'none') {
        filterBody.style.display = 'block';
        toggleIcon.className = 'fas fa-chevron-up';
    } else {
        filterBody.style.display = 'none';
        toggleIcon.className = 'fas fa-chevron-down';
    }
}

function applyFilters() {
    const searchTerm = document.getElementById('searchProperties').value.toLowerCase();
    const purpose = document.getElementById('filterPurpose').value;
    const status = document.getElementById('filterStatus').value;
    const zone = document.getElementById('filterZone').value;
    
    const rows = document.querySelectorAll('#propertiesTable tbody tr');
    filteredRows = [];
    
    rows.forEach(row => {
        let show = true;
        
        // Search filter
        if (searchTerm) {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        // Purpose filter
        if (purpose && show) {
            const purposeCell = row.querySelector('.badge');
            if (purposeCell) {
                const propertyPurpose = purposeCell.textContent.trim();
                // Check if purpose matches (including 'Other' case)
                show = propertyPurpose === purpose;
                // If purpose is 'Other', also check if it matches any custom purpose
                if (!show && purpose === 'Other') {
                    show = propertyPurpose !== 'Command/Formation' && propertyPurpose !== 'Area Office' && 
                           propertyPurpose !== 'Divitional Office' && propertyPurpose !== 'PPT Office' &&
                           propertyPurpose !== 'Control Post' && propertyPurpose !== 'Barracks/Transit Camp' &&
                           propertyPurpose !== 'FOM/MOB' && propertyPurpose !== 'E-Border' &&
                           propertyPurpose !== 'Flag House' && propertyPurpose !== 'Zonal Command' &&
                           propertyPurpose !== 'Migrant Holding Center' && propertyPurpose !== 'Staff Quarters' &&
                           propertyPurpose !== 'Office Space';
                }
            } else {
                show = false;
            }
        }
        
        // Status filter
        if (status && show) {
            const propertyStatus = row.dataset.status;
            
            // Special handling for 'Active', 'Expiring Soon', 'Expired' which are rental statuses
            if (status === 'Active' || status === 'Expiring Soon' || status === 'Expired') {
                const rentalStatus = row.dataset.rentalStatus;
                show = rentalStatus === status;
            } else {
                // Filter by property status (Under Litigation, Developed, Under Developed, Fenced, Not Fenced, Others)
                show = propertyStatus === status;
                
                // If status is 'Undeveloped' (from filter) and property has 'Under Developed'
                if (!show && status === 'Undeveloped' && propertyStatus === 'Under Developed') {
                    show = true;
                }
                // If status is 'Under Developed' and property has 'Under Developed'
                if (!show && status === 'Under Developed' && propertyStatus === 'Under Developed') {
                    show = true;
                }
            }
        }
        
        // Zone filter
        if (zone && show) {
            show = row.dataset.zone === zone;
        }
        
        row.style.display = show ? '' : 'none';
        if (show) filteredRows.push(row);
    });
    
    document.getElementById('recordCount').textContent = filteredRows.length;
    updatePagination();
}

function resetFilters() {
    document.getElementById('searchProperties').value = '';
    document.getElementById('filterPurpose').value = '';
    document.getElementById('filterStatus').value = '';
    document.getElementById('filterZone').value = '';
    
    const rows = document.querySelectorAll('#propertiesTable tbody tr');
    rows.forEach(row => row.style.display = '');
    filteredRows = Array.from(rows);
    
    document.getElementById('recordCount').textContent = filteredRows.length;
    updatePagination();
}

function updatePagination() {
    const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = `
        <button class="page-link" onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i> Previous
        </button>
        <span class="page-info">Page ${currentPage} of ${totalPages}</span>
        <button class="page-link" onclick="changePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>
            Next <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = html;
    
    // Show only current page rows
    const start = (currentPage - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    
    filteredRows.forEach((row, index) => {
        row.style.display = (index >= start && index < end) ? '' : 'none';
    });
}

function changePage(page) {
    currentPage = page;
    updatePagination();
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#propertiesTable tbody tr');
    filteredRows = Array.from(rows);
    document.getElementById('recordCount').textContent = filteredRows.length;
});

// Live search with debounce
let searchTimeout;
const searchInput = document.getElementById('searchProperties');
if (searchInput) {
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(applyFilters, 300);
    });
}

const purposeFilter = document.getElementById('filterPurpose');
if (purposeFilter) purposeFilter.addEventListener('change', applyFilters);

const statusFilter = document.getElementById('filterStatus');
if (statusFilter) statusFilter.addEventListener('change', applyFilters);

const zoneFilter = document.getElementById('filterZone');
if (zoneFilter) zoneFilter.addEventListener('change', applyFilters);
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>