{% extends 'buybackprogram/page.html' %}
{% load i18n %}
{% load django_bootstrap5 %}
{% load static %}

{% block body %}
<div class="card">
    <h5 class="card-header">{% trans "Edit Reverse Buyback Program" %}</h5>
    <div class="card-body">
        <form class="form" action="{% url 'buybackprogram:reverse_program_edit' program_pk=program.id %}" method="POST">
            {% csrf_token %}
            {% bootstrap_form form %}
            <button type="submit" class="btn btn-primary">{% trans "Save Changes" %}</button>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_css %}
{% include "buybackprogram/bundles/buybackprogram-css-light.html" %}
{% endblock %}

{% block extra_javascript %}
<script>
const hangarUrl = "{% url 'buybackprogram:hangar_division_autocomplete' %}";

function loadHangars(ownerId, selectedId) {
    const hangarSelect = document.getElementById('id_hangar_division');
    hangarSelect.innerHTML = '<option value="">---------</option>';
    if (!ownerId) return;

    fetch(hangarUrl + '?owner_id=' + ownerId)
        .then(r => {
            console.log('Hangar fetch status:', r.status, 'URL:', r.url);
            return r.json();
        })
        .then(data => {
            console.log('Hangar data:', data);
            data.forEach(h => {
                const opt = document.createElement('option');
                opt.value = h.id;
                opt.textContent = h.name;
                if (selectedId && h.id == selectedId) opt.selected = true;
                hangarSelect.appendChild(opt);
            });
        })
        .catch(err => console.error('Hangar fetch error:', err));
}

document.addEventListener('DOMContentLoaded', function () {
    const ownerSelect = document.getElementById('id_owner');
    const currentHangar = document.getElementById('id_hangar_division').value;

    ownerSelect.addEventListener('change', function () {
        loadHangars(this.value, null);
    });

    // On edit page load, populate hangars for the already-selected owner
    if (ownerSelect.value) {
        loadHangars(ownerSelect.value, currentHangar);
    }
});
</script>
{% endblock %}
