<?php
$title = 'Ongoing Projects Management';
$active = 'projects';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// These variables should come from the controller
$projects = isset($projects) ? $projects : [];
$statistics = isset($statistics) ? $statistics : [
    'total' => 0,
    'by_status' => [],
    'total_value' => 0,
    'overdue' => 0
];

// Zones should be passed from the controller
$zones = isset($zones) ? $zones : [];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-hard-hat"></i>
                Ongoing Projects Management
            </h1>
            <p>Manage all construction and development projects</p>
        </div>
        <div class="header-actions">
            <?php if (Auth::can('projects.create')): ?>
            <a href="<?php echo BASE_URL; ?>/projects/create" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> Add New Project
            </a>
            <?php endif; ?>
            <?php if (Auth::can('reports.export')): ?>
            <a href="<?php echo BASE_URL; ?>/projects/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 -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon total">
            <i class="fas fa-hard-hat"></i>
        </div>
        <div class="stat-details">
            <h4>Total Projects</h4>
            <p class="stat-number"><?php echo number_format($statistics['total'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon planning">
            <i class="fas fa-pencil-ruler"></i>
        </div>
        <div class="stat-details">
            <h4>Planning</h4>
            <p class="stat-number"><?php echo number_format($statistics['by_status']['Planning']['count'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon progress">
            <i class="fas fa-spinner"></i>
        </div>
        <div class="stat-details">
            <h4>In Progress</h4>
            <p class="stat-number"><?php echo number_format($statistics['by_status']['In Progress']['count'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
     <div class="stat-icon abandoned">
    <i class="fas fa-times-circle"></i>
</div>
        <div class="stat-details">
            <h4>Abandoned</h4>
            <p class="stat-number"><?php echo number_format($statistics['by_status']['Abandoned']['count'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon completed">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-details">
            <h4>Completed</h4>
            <p class="stat-number"><?php echo number_format($statistics['by_status']['Completed']['count'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon terminated">
            <i class="fas fa-ban"></i>
        </div>
        <div class="stat-details">
            <h4>Terminated</h4>
            <p class="stat-number"><?php echo number_format($statistics['by_status']['Terminated']['count'] ?? 0); ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon value">
            <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="stat-details">
            <h4>Total Value</h4>
            <p class="stat-number value-large">₦<?php echo number_format($statistics['total_value'] ?? 0, 2); ?></p>
        </div>
    </div>
</div>

    <!-- Filters -->
    <div class="filter-section">
        <div class="filter-header" onclick="toggleFilters()">
            <h3><i class="fas fa-filter"></i> Filter Projects</h3>
            <i class="fas fa-chevron-down" id="filterToggleIcon"></i>
        </div>
        <div class="filter-body" id="filterBody" style="display: block;">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" id="searchProjects" class="form-control" placeholder="Search by title, code, contractor...">
                </div>
                <div class="filter-group">
                    <label>Project Type</label>
                    <select id="filterType" class="form-control">
                        <option value="">All Types</option>
                        <option value="Construction">Construction</option>
                        <option value="Renovation">Renovation</option>
                        <option value="Rehabilitation">Rehabilitation</option>
                        <option value="Expansion">Expansion</option>
                        <!--<option value="Infrastructure">Infrastructure</option>-->
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select id="filterStatus" class="form-control">
                        <option value="">All Status</option>
                        <option value="Planning">Planning</option>
                        <option value="In Progress">In Progress</option>
                        <option value="Abandoned">Abandoned</option>
                        <option value="Completed">Completed</option>
                        <option value="Terminated">Terminated</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Zone</label>
                    <select id="filterZone" class="form-control">
                        <option value="">All Zones</option>
                        <?php if (!empty($zones) && is_array($zones)): ?>
                            <?php foreach ($zones as $zone): ?>
                                <option value="<?php echo $zone['id'] ?? ''; ?>">
                                    <?php echo Security::escape($zone['zone_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
                <!--<div class="filter-group">-->
                <!--    <label>Funding Source</label>-->
                <!--    <select id="filterFunding" class="form-control">-->
                <!--        <option value="">All Sources</option>-->
                <!--        <option value="Capital Appropriation">Capital Appropriation</option>-->
                <!--        <option value="Special Intervention">Special Intervention</option>-->
                <!--        <option value="Donor">Donor</option>-->
                <!--        <option value="IGR">IGR</option>-->
                <!--    </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>

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

        <div class="table-responsive">
            <?php if (empty($projects)): ?>
                <div class="empty-state">
                    <i class="fas fa-hard-hat"></i>
                    <p>No projects found</p>
                    <?php if (Auth::can('projects.create')): ?>
                    <a href="<?php echo BASE_URL; ?>/projects/create" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add First Project
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="projectsTable">
                <thead>
                    <tr>
                        <th data-sort="text">S/N</th>
                        <th data-sort="text">Project Code</th>
                        <th data-sort="text">Project Title</th>
                        <th data-sort="text">Type</th>
                        <th data-sort="text">Contractor</th>
                        <th data-sort="text">Location</th>
                        <th data-sort="number">Contract Sum (₦)</th>
                        <th data-sort="text">Progress</th>
                        <th data-sort="text">Status</th>
                        <th data-sort="date">Completion</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($projects as $index => $project): ?>
                    <?php 
                    $overdue = false;
                    if (!empty($project['expected_completion_date']) && strtotime($project['expected_completion_date']) < time() && !in_array($project['status'], ['Completed', 'Cancelled'])) {
                        $overdue = true;
                    }
                    ?>
                    <tr data-type="<?php echo strtolower($project['project_type'] ?? ''); ?>" 
                        data-status="<?php echo strtolower($project['status'] ?? ''); ?>"
                        data-zone="<?php echo $project['zone_id'] ?? ''; ?>"
                        data-funding="<?php echo strtolower($project['source_funding'] ?? ''); ?>"
                        class="<?php echo $overdue ? 'overdue-row' : ''; ?>">
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <span class="asset-code"><?php echo Security::escape($project['project_code'] ?? ''); ?></span>
                        </td>
                        <td><?php echo Security::escape($project['project_title'] ?? ''); ?></td>
                        <td>
                            <span class="badge badge-info"><?php echo Security::escape($project['project_type'] ?? ''); ?></span>
                        </td>
                        <td><?php echo Security::escape($project['contractor'] ?? '-'); ?></td>
                        <td>
                            <?php 
                            $location = [];
                            if (!empty($project['lga_name'])) $location[] = $project['lga_name'];
                            if (!empty($project['state_name'])) $location[] = $project['state_name'];
                            echo Security::escape(implode(', ', $location));
                            ?>
                        </td>
                        <td class="text-right">₦<?php echo number_format($project['contract_sum'] ?? 0, 2); ?></td>
                        <td>
                            <div class="progress-container">
                                <div class="progress-bar" style="width: <?php echo $project['physical_progress'] ?? 0; ?>%;"></div>
                                <span class="progress-text"><?php echo $project['physical_progress'] ?? 0; ?>%</span>
                            </div>
                        </td>
                        <td>
                            <?php 
                            $status = $project['status'] ?? '';
                            $statusClass = '';
                            if ($status == 'Planning') $statusClass = 'status-info';
                            elseif ($status == 'In Progress') $statusClass = 'status-warning';
                            elseif ($status == 'Abandoned') $statusClass = 'status-abandoned';
                            elseif ($status == 'Completed') $statusClass = 'status-success';
                            elseif ($status == 'Terminated') $statusClass = 'status-terminated';
                            ?>
                            <span class="status-badge <?php echo $statusClass; ?>">
                                <?php echo Security::escape($status); ?>
                            </span>
                        </td>
                        <td>
                            <?php if (!empty($project['expected_completion_date'])): ?>
                                <?php echo date('d/m/Y', strtotime($project['expected_completion_date'])); ?>
                                <?php if ($overdue): ?>
                                    <br><small class="days-badge overdue">Overdue</small>
                                <?php endif; ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?php echo BASE_URL; ?>/projects/show/<?php echo $project['id'] ?? ''; ?>" 
                                   class="btn-icon" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (Auth::can('projects.edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/projects/edit/<?php echo $project['id'] ?? ''; ?>" 
                                   class="btn-icon" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (Auth::can('projects.delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/projects/delete/<?php echo $project['id'] ?? ''; ?>" 
                                   class="btn-icon delete" title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this project?')">
                                    <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>
/* Statistics Cards - Two Rows Layout */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

/* Make the Total Value card span properly in the second row */
.stats-grid .stat-card:last-child {
    grid-column: span 1;
}

/* For the 7 cards to display in two rows (4 + 3) */
@media (min-width: 1200px) {
    .stats-grid {
        grid-template-columns: repeat(4, 1fr);
    }
    /* This automatically creates 2 rows: first row 4 cards, second row 3 cards */
}

@media (max-width: 1199px) and (min-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
    }
    /* On medium screens: 3 columns = 3 rows (3, 3, 1) */
}

@media (max-width: 767px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }
    /* On tablets: 2 columns = 4 rows (2, 2, 2, 1) */
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    /* On mobile: 1 column = 7 rows */
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 18px 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    border: 1px solid #eef2f6;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.12);
    border-color: #e0e7ed;
}

.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.6rem;
    flex-shrink: 0;
}

.stat-icon.total {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdef5 100%);
    color: #1565c0;
}

.stat-icon.planning {
    background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 100%);
    color: #00695c;
}

.stat-icon.progress {
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    color: #e65100;
}

.stat-icon.abandoned {
    background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
    color: #6a1b9a;
}

.stat-icon.completed {
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    color: #2e7d32;
}

.stat-icon.terminated {
    background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
    color: #c62828;
}

.stat-icon.value {
    background: linear-gradient(135deg, #e0f2f1 0%, #b2dfdb 100%);
    color: #00695c;
}

.stat-details {
    flex: 1;
    min-width: 0;
}

.stat-details h4 {
    margin: 0 0 5px 0;
    font-size: 0.85rem;
    font-weight: 600;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.stat-number {
    font-size: 1.8rem;
    font-weight: 700;
    margin: 0;
    color: #1a2c3e;
    line-height: 1.2;
}

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

/* Responsive font sizes */
@media (max-width: 1200px) {
    .stat-number {
        font-size: 1.5rem;
    }
    .stat-number.value-large {
        font-size: 1.3rem;
    }
    .stat-icon {
        width: 48px;
        height: 48px;
        font-size: 1.4rem;
    }
    .stat-card {
        padding: 15px 12px;
        gap: 12px;
    }
}

@media (max-width: 992px) {
    .stat-number {
        font-size: 1.3rem;
    }
    .stat-number.value-large {
        font-size: 1.2rem;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
        font-size: 1.3rem;
    }
    .stat-details h4 {
        font-size: 0.75rem;
    }
}

@media (max-width: 768px) {
    .stat-number {
        font-size: 1.2rem;
    }
    .stat-number.value-large {
        font-size: 1.1rem;
    }
    .stat-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }
    .stat-card {
        padding: 12px 10px;
        gap: 10px;
    }
    .stat-details h4 {
        font-size: 0.7rem;
    }
}

@media (max-width: 480px) {
    .stat-number {
        font-size: 1.1rem;
    }
    .stat-number.value-large {
        font-size: 1rem;
    }
    .stat-icon {
        width: 36px;
        height: 36px;
        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: 15px 20px;
    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: 1rem;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-header i {
    transition: transform 0.3s ease;
}

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

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

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

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

.filter-group input,
.filter-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 0.9rem;
}

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

/* Progress Bar */
.progress-container {
    width: 100px;
    height: 20px;
    background: var(--light-bg);
    border-radius: 10px;
    position: relative;
    overflow: hidden;
}

.progress-bar {
    height: 100%;
    background: var(--success-color);
    border-radius: 10px;
    transition: width 0.3s ease;
}

.progress-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 0.7rem;
    font-weight: 600;
    color: var(--text-primary);
    text-shadow: 0 0 2px white;
}

/* Badge Styles */
.badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.75rem;
    font-weight: 500;
}

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

/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}

.status-info {
    background: #d1ecf1;
    color: #0c5460;
}

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

.status-secondary {
    background: #e2e3e5;
    color: #383d41;
}

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

.status-danger {
    background: #f8d7da;
    color: #721c24;
}
.status-abandoned {
    background: #f3e5f5;
    color: #7b1fa2;
}

.status-terminated {
    background: #ffebee;
    color: #c62828;
}

/* Days badge */
.days-badge {
    display: inline-block;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 0.7rem;
    font-weight: 600;
}

.days-badge.overdue {
    background: #f8d7da;
    color: #721c24;
}

.overdue-row {
    background-color: #fff3e0;
}

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

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

.page-link {
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s;
    cursor: pointer;
}

.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-link:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

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

/* Empty State */
.empty-state {
    text-align: center;
    padding: 40px;
    color: var(--text-secondary);
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 15px;
    opacity: 0.5;
}

.empty-state p {
    font-size: 1rem;
    margin: 0 0 15px 0;
}

.record-count {
    font-size: 0.9rem;
    color: var(--text-secondary);
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .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('searchProjects').value.toLowerCase().trim();
    const type = document.getElementById('filterType').value.toLowerCase();
    const status = document.getElementById('filterStatus').value.toLowerCase();
    const zone = document.getElementById('filterZone').value;
    const funding = document.getElementById('filterFunding').value.toLowerCase();
    
    const rows = document.querySelectorAll('#projectsTable tbody tr');
    filteredRows = [];
    
    rows.forEach(row => {
        let show = true;
        
        // Search filter
        if (searchTerm !== '') {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        // Type filter
        if (type !== '' && show) {
            const rowType = row.dataset.type;
            show = show && rowType === type;
        }
        
        // Status filter
        if (status !== '' && show) {
            const rowStatus = row.dataset.status;
            show = show && rowStatus === status;
        }
        
        // Zone filter
        if (zone !== '' && show) {
            show = row.dataset.zone === zone;
        }
        
        // Funding filter
        if (funding !== '' && show) {
            const rowFunding = row.dataset.funding;
            show = show && rowFunding === funding;
        }
        
        if (show) {
            filteredRows.push(row);
        }
    });
    
    updateDisplay();
}

function resetFilters() {
    document.getElementById('searchProjects').value = '';
    document.getElementById('filterType').value = '';
    document.getElementById('filterStatus').value = '';
    document.getElementById('filterZone').value = '';
    document.getElementById('filterFunding').value = '';
    
    const rows = document.querySelectorAll('#projectsTable tbody tr');
    filteredRows = Array.from(rows);
    
    updateDisplay();
}

function updateDisplay() {
    const totalRecords = filteredRows.length;
    document.getElementById('recordCount').textContent = totalRecords;
    
    // Hide all rows first
    document.querySelectorAll('#projectsTable tbody tr').forEach(row => {
        row.style.display = 'none';
    });
    
    if (totalRecords === 0) {
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    
    // Show only current page
    const start = (currentPage - 1) * rowsPerPage;
    const end = Math.min(start + rowsPerPage, totalRecords);
    
    for (let i = start; i < end; i++) {
        if (filteredRows[i]) {
            filteredRows[i].style.display = '';
        }
    }
    
    updatePagination(totalRecords);
}

function updatePagination(totalRecords) {
    const totalPages = Math.ceil(totalRecords / 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;
}

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

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

// Debounced search
let searchTimeout;
document.getElementById('searchProjects').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        currentPage = 1;
        applyFilters();
    }, 300);
});

document.getElementById('filterType').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

document.getElementById('filterStatus').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

document.getElementById('filterZone').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

document.getElementById('filterFunding').addEventListener('change', function() {
    currentPage = 1;
    applyFilters();
});

// Auto-hide success/error messages after 5 seconds - FIXED VERSION
document.addEventListener('DOMContentLoaded', function() {
    // Function to hide alerts with fade out effect
    function hideAlert(alertElement) {
        if (alertElement && alertElement.style.display !== 'none') {
            // Add fade out animation
            alertElement.style.transition = 'opacity 0.5s ease';
            alertElement.style.opacity = '0';
            
            // Remove after animation completes
            setTimeout(function() {
                alertElement.style.display = 'none';
            }, 500);
        }
    }
    
    // Check for success alert
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            hideAlert(successAlert);
        }, 5000);
    }
    
    // Check for error alert
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        setTimeout(function() {
            hideAlert(errorAlert);
        }, 5000);
    }
    
    // Add click handlers for close buttons (alternative method)
    const closeButtons = document.querySelectorAll('.btn-close');
    closeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const alert = this.closest('.alert');
            if (alert) {
                hideAlert(alert);
            }
        });
    });
});

// Also check if alerts exist after any AJAX updates
function checkAndSetupAutoHide() {
    const successAlert = document.getElementById('successAlert');
    if (successAlert && !successAlert.hasAttribute('data-auto-hide-set')) {
        successAlert.setAttribute('data-auto-hide-set', 'true');
        setTimeout(function() {
            if (successAlert && successAlert.style.display !== 'none') {
                successAlert.style.transition = 'opacity 0.5s ease';
                successAlert.style.opacity = '0';
                setTimeout(function() {
                    if (successAlert) successAlert.style.display = 'none';
                }, 500);
            }
        }, 5000);
    }
    
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert && !errorAlert.hasAttribute('data-auto-hide-set')) {
        errorAlert.setAttribute('data-auto-hide-set', 'true');
        setTimeout(function() {
            if (errorAlert && errorAlert.style.display !== 'none') {
                errorAlert.style.transition = 'opacity 0.5s ease';
                errorAlert.style.opacity = '0';
                setTimeout(function() {
                    if (errorAlert) errorAlert.style.display = 'none';
                }, 500);
            }
        }, 5000);
    }
}

// Run on page load and after any potential AJAX updates
document.addEventListener('DOMContentLoaded', function() {
    checkAndSetupAutoHide();
});

</script>

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