<!-- Вкладка заявок на источники -->
<div class="card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-list-task"></i> Заявки на источники</h5>
        <button type="button" class="btn btn-success btn-sm" onclick="openCreateRequestModal()">
            <i class="bi bi-plus-circle"></i> Создать заявку
        </button>
    </div>
    <div class="card-body">
        <!-- Фильтры заявок -->
        <form method="get" class="row g-2 mb-3" id="requestsFilterForm">
            <div class="col-md-2">
                <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Все статусы</option>
                    {% for value, label in status_choices %}
                    <option value="{{ value }}" {% if current_status == value %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <select name="priority" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Все приоритеты</option>
                    {% for value, label in priority_choices %}
                    <option value="{{ value }}" {% if current_priority == value %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <select name="gso_success" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">ГСО: все</option>
                    <option value="true" {% if request.GET.gso_success == 'true' %}selected{% endif %}>ГСО: Да</option>
                    <option value="false" {% if request.GET.gso_success == 'false' %}selected{% endif %}>ГСО: Нет</option>
                </select>
            </div>
            <div class="col-md-2">
                <select name="kubsat_success" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">Кубсат: все</option>
                    <option value="true" {% if request.GET.kubsat_success == 'true' %}selected{% endif %}>Кубсат: Да</option>
                    <option value="false" {% if request.GET.kubsat_success == 'false' %}selected{% endif %}>Кубсат: Нет</option>
                </select>
            </div>
        </form>
        
        <!-- Клиентский поиск по имени точки -->
        <div class="row mb-3">
            <div class="col-md-4">
                <div class="input-group input-group-sm">
                    <input type="text" id="searchRequestObjitemName" class="form-control" 
                        placeholder="Поиск по имени точки..." 
                        oninput="filterRequestsByName()">
                    <button type="button" class="btn btn-outline-secondary" onclick="clearRequestSearch()">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-8">
                <span class="text-muted small" id="requestsCounter">
                    Показано заявок: {{ requests|length }}
                </span>
            </div>
        </div>
        
        <!-- Таблица заявок -->
        <div class="table-responsive" style="max-height: 60vh; overflow-y: auto;">
            <table class="table table-striped table-hover table-sm table-bordered" style="font-size: 0.85rem;">
                <thead class="table-dark sticky-top">
                    <tr>
                        <th style="min-width: 60px;">ID</th>
                        <th style="min-width: 80px;">Источник</th>
                        <th style="min-width: 120px;">Статус</th>
                        <th style="min-width: 80px;">Приоритет</th>
                        <th style="min-width: 150px;">Координаты</th>
                        <th style="min-width: 150px;">Имя точки</th>
                        <th style="min-width: 100px;">Модуляция</th>
                        <th style="min-width: 100px;">Симв. скор.</th>
                        <th style="min-width: 130px;">Дата планирования</th>
                        <th style="min-width: 80px;">ГСО</th>
                        <th style="min-width: 80px;">Кубсат</th>
                        <th style="min-width: 130px;">Обновлено</th>
                        <th style="min-width: 120px;">Действия</th>
                    </tr>
                </thead>
                <tbody>
                    {% for req in requests %}
                    <tr data-objitem-name="{{ req.objitem_name|default:'' }}">
                        <td>{{ req.id }}</td>
                        <td>
                            <a href="{% url 'mainapp:source_update' req.source_id %}" target="_blank">
                                #{{ req.source_id }}
                            </a>
                        </td>
                        <td>
                            <span class="badge 
                                {% if req.status == 'successful' or req.status == 'result_received' %}bg-success
                                {% elif req.status == 'unsuccessful' or req.status == 'no_correlation' or req.status == 'no_signal' %}bg-danger
                                {% elif req.status == 'planned' %}bg-primary
                                {% elif req.status == 'downloading' or req.status == 'processing' %}bg-warning text-dark
                                {% else %}bg-secondary{% endif %}">
                                {{ req.get_status_display }}
                            </span>
                        </td>
                        <td>
                            <span class="badge 
                                {% if req.priority == 'high' %}bg-danger
                                {% elif req.priority == 'medium' %}bg-warning text-dark
                                {% else %}bg-secondary{% endif %}">
                                {{ req.get_priority_display }}
                            </span>
                        </td>
                        <td>
                            {% if req.coords %}
                                <small>{{ req.coords.y|floatformat:6 }}, {{ req.coords.x|floatformat:6 }}</small>
                            {% else %}-{% endif %}
                        </td>
                        <td>{{ req.objitem_name|default:"-" }}</td>
                        <td>{{ req.modulation|default:"-" }}</td>
                        <td>{{ req.symbol_rate|default:"-" }}</td>
                        <td>{{ req.planned_at|date:"d.m.Y H:i"|default:"-" }}</td>
                        <td class="text-center">
                            {% if req.gso_success is True %}
                            <span class="badge bg-success">Да</span>
                            {% elif req.gso_success is False %}
                            <span class="badge bg-danger">Нет</span>
                            {% else %}-{% endif %}
                        </td>
                        <td class="text-center">
                            {% if req.kubsat_success is True %}
                            <span class="badge bg-success">Да</span>
                            {% elif req.kubsat_success is False %}
                            <span class="badge bg-danger">Нет</span>
                            {% else %}-{% endif %}
                        </td>
                        <td>{{ req.status_updated_at|date:"d.m.Y H:i"|default:"-" }}</td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-info" onclick="showHistory({{ req.id }})" title="История">
                                    <i class="bi bi-clock-history"></i>
                                </button>
                                <button type="button" class="btn btn-outline-warning" onclick="openEditRequestModal({{ req.id }})" title="Редактировать">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button type="button" class="btn btn-outline-danger" onclick="deleteRequest({{ req.id }})" title="Удалить">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="13" class="text-center text-muted">Нет заявок</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Пагинация -->
        {% if page_obj %}
        <nav aria-label="Пагинация" class="mt-3">
            <ul class="pagination pagination-sm justify-content-center">
                {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if current_priority %}&priority={{ current_priority }}{% endif %}">
                        &laquo;
                    </a>
                </li>
                {% endif %}
                
                <li class="page-item disabled">
                    <span class="page-link">{{ page_obj.number }} из {{ page_obj.paginator.num_pages }}</span>
                </li>
                
                {% if page_obj.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if current_priority %}&priority={{ current_priority }}{% endif %}">
                        &raquo;
                    </a>
                </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<script>
// Фильтрация таблицы заявок по имени точки
function filterRequestsByName() {
    const searchValue = document.getElementById('searchRequestObjitemName').value.toLowerCase().trim();
    const tbody = document.querySelector('.table tbody');
    const rows = tbody.querySelectorAll('tr');
    
    let visibleCount = 0;
    
    rows.forEach(row => {
        // Пропускаем строку "Нет заявок"
        if (row.querySelector('td[colspan]')) {
            return;
        }
        
        const objitemName = (row.dataset.objitemName || '').toLowerCase();
        
        if (!searchValue || objitemName.includes(searchValue)) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
        }
    });
    
    updateRequestsCounter(visibleCount);
}

// Обновление счётчика заявок
function updateRequestsCounter(count) {
    const counter = document.getElementById('requestsCounter');
    if (counter) {
        counter.textContent = `Показано заявок: ${count}`;
    }
}

// Очистка поиска
function clearRequestSearch() {
    document.getElementById('searchRequestObjitemName').value = '';
    filterRequestsByName();
}

// Инициализация счётчика при загрузке
document.addEventListener('DOMContentLoaded', function() {
    const tbody = document.querySelector('.table tbody');
    if (tbody) {
        const rows = tbody.querySelectorAll('tr:not([style*="display: none"])');
        // Исключаем строку "Нет заявок"
        const visibleRows = Array.from(rows).filter(row => !row.querySelector('td[colspan]'));
        updateRequestsCounter(visibleRows.length);
    }
});
</script>
