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

{% block details %}

{% if selected_items %}

<div class="card text-white bg-success">
    <div class="card-header">{% trans "Request Summary" %}</div>
    <div class="card-body">
        <p class="mb-1">
            <strong>{% trans "Availability:" %}</strong>
            <span id="owner-name">{% if program.is_corporation %}{{ program.owner.corporation }}{% else %}{{ program.owner.character.character }}{% endif %}</span>
            <button class="btn btn-sm btn-light ms-2" onclick="copyText('owner-name')">
                <i class="fas fa-copy"></i> {% trans "Copy" %}
            </button>
        </p>
        <p class="mb-1">
            <strong>{% trans "I will pay:" %}</strong>
            <span id="total-price">{{ contract_net_total|floatformat:0 }}</span> ISK
            <button class="btn btn-sm btn-light ms-2" onclick="copyText('total-price')">
                <i class="fas fa-copy"></i> {% trans "Copy" %}
            </button>
        </p>
        {% if tracking_number %}
        <p class="mb-1">
            <strong>{% trans "Tracking number:" %}</strong>
            <span id="tracking-number" style="font-family: monospace;">{{ tracking_number }}</span>
            <button class="btn btn-sm btn-light ms-2" onclick="copyText('tracking-number')">
                <i class="fas fa-copy"></i> {% trans "Copy" %}
            </button>
        </p>
        {% endif %}
    </div>
</div>

<div class="card bg-info text-white" style="margin-top:10px;">
    <div class="card-body">
        <i class="fas fa-info-circle"></i>
        <strong>{% trans "How to create the contract:" %}</strong>
        <ol class="mb-0 mt-2">
            <li>{% trans "Open contracts ingame and click" %} <strong>{% trans "Create Contract" %}</strong></li>
            <li>{% trans "Select" %} <strong>{% trans "Item Exchange" %}</strong> {% trans "and search for" %} <strong>{% if program.is_corporation %}{{ program.owner.corporation }}{% else %}{{ program.owner.character.character }}{% endif %}</strong></li>
            <li>{% trans "Check the" %} <strong>{% trans "Also request items from buyer" %}</strong> {% trans "checkbox" %}</li>
            <li>{% trans "On the items page, click" %} <strong>{% trans "I will pay" %}</strong> {% trans "and enter" %} <strong>{{ contract_net_total|floatformat:0|intcomma }} ISK</strong></li>
            <li>{% trans "Click" %} <strong>{% trans "I will receive" %}</strong> {% trans "and add all the items listed below from the requested items list" %}</li>
            <li>{% trans "Set the contract title to your tracking number:" %} <strong style="font-family:monospace;">{{ tracking_number }}</strong></li>
            <li>{% trans "Set expiration to" %} <strong>{{ program.expiration }}</strong> {% trans "and submit" %}</li>
        </ol>
    </div>
</div>

<div class="card" style="margin-top:10px;">
    <div class="card-header"><h5>{% trans "Requested Items" %}</h5></div>
    <div class="card-body">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>{% trans "Item" %}</th>
                    <th>{% trans "Quantity" %}</th>
                    <th>{% trans "Unit Price" %}</th>
                    <th>{% trans "Total" %}</th>
                    <th>{% trans "Notes" %}</th>
                </tr>
            </thead>
            <tbody>
                {% for item in selected_items %}
                <tr>
                    <td>
                        <img src="https://images.evetech.net/types/{{ item.type_id }}/icon?size=32" style="height:28px;border-radius:4px;margin-right:6px;" alt="{{ item.name }}">{{ item.name }}
                        <button class="btn btn-sm btn-outline-secondary ms-1 py-0 px-1"
                                onclick="copyValue('{{ item.name }}')"
                                title="{% trans 'Copy item name' %}">
                            <i class="fas fa-copy" style="font-size:0.7rem;"></i>
                        </button>
                    </td>
                    <td>{{ item.quantity|intcomma }}</td>
                    <td>{{ item.unit_price|floatformat:2|intcomma }} ISK</td>
                    <td>{{ item.total_price|floatformat:2|intcomma }} ISK</td>
                    <td>
                        {% for note in item.notes %}
                            <i style="color: {{ note.color }};" class="fas {{ note.icon }}" title="{{ note.message }}"></i>
                        {% endfor %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3"><strong>{% trans "Total" %}</strong></td>
                    <td><strong>{{ contract_net_total|floatformat:2|intcomma }} ISK</strong></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

{% endif %}

<div class="card" style="margin-top:10px;">
    <h5 class="card-header">
        <i class="fas fa-exchange-alt"></i> {% trans "Available Stock" %}
        {% if program.name %} — {{ program.name }}{% endif %}
    </h5>
    <div class="card-body">
        <div class="alert alert-secondary">
            <i class="fas fa-info-circle"></i>
            {% trans "Select the items you wish to purchase and submit a buy request to get a tracking number. In-game, create a contract to the seller and enable the \"I will receive\" option to request the items listed in the calculator. Set the contract price to the calculated ISK amount." %}
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <input type="text" id="stock-search" class="form-control" placeholder="{% trans 'Search items...' %}">
            </div>
            <div class="col-md-3">
                <select id="category-filter" class="form-select">
                    <option value="">{% trans "All Categories" %}</option>
                </select>
            </div>
        </div>

        <table class="table table-striped table-hover" id="stock-table">
            <thead>
                <tr>
                    <th>{% trans "Item" %}</th>
                    <th>{% trans "Group" %}</th>
                    <th>{% trans "Available" %}</th>
                    <th>{% trans "Reserved" %}</th>
                    <th>{% trans "Unit Price (ISK)" %}</th>
                    <th>{% trans "Quantity" %}</th>
                    <th>{% trans "Add" %}</th>
                </tr>
            </thead>
            <tbody id="stock-body">
            </tbody>
        </table>
    </div>
</div>

<div class="card" style="margin-top:10px;" id="cart-card">
    <h5 class="card-header">
        <i class="fas fa-shopping-cart"></i> {% trans "Selected Items" %}
        <span class="badge bg-primary ms-2" id="cart-count">0</span>
    </h5>
    <div class="card-body">
        <table class="table table-hover" id="cart-table">
            <thead>
                <tr>
                    <th>{% trans "Item" %}</th>
                    <th>{% trans "Quantity" %}</th>
                    <th>{% trans "Unit Price" %}</th>
                    <th>{% trans "Total" %}</th>
                    <th>{% trans "Remove" %}</th>
                </tr>
            </thead>
            <tbody id="cart-body">
                <tr id="cart-empty-row">
                    <td colspan="5" class="text-center text-muted">{% trans "No items selected yet." %}</td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3"><strong>{% trans "Grand Total" %}</strong></td>
                    <td><strong id="cart-total">0 ISK</strong></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>

        <form method="POST" action="{% url 'buybackprogram:reverse_program_calculate' program_pk=program.id %}">
            {% csrf_token %}
            <input type="hidden" name="selected_items" id="selected-items-input">
            <button type="submit" class="btn btn-primary" id="submit-btn" disabled>
                <i class="fas fa-calculator"></i> {% trans "Check Total Price" %}
            </button>
        </form>
    </div>
    <div class="card-footer text-muted">
        <b>{% trans "Program:" %}</b>
        {% if program.name %}{{ program.name }}, {% endif %}
        {% trans "managed by" %}
        {% if program.is_corporation %}{{ program.owner.corporation }}{% else %}{{ program.owner.character.character }}{% endif %}
        — <b>{% trans "Markup:" %}</b> {{ program.markup }}%
        — <b>{% trans "Price type:" %}</b> {{ program.price_type }}
    </div>
</div>

{% endblock %}

{% block extra_javascript %}
<script>
const stockData = {{ stock_data_json|safe }};
let cart = {};

function copyText(elementId) {
    const text = document.getElementById(elementId).innerText.trim();
    copyValue(text);
}

function copyValue(text) {
    navigator.clipboard.writeText(text).catch(() => {
        // Fallback for older browsers
        const tmp = document.createElement('textarea');
        tmp.value = text;
        tmp.style.position = 'absolute';
        tmp.style.left = '-9999px';
        document.body.appendChild(tmp);
        tmp.select();
        document.execCommand('copy');
        document.body.removeChild(tmp);
    });
}

function formatNumber(n) {
    return n.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

function buildCategoryFilter() {
    const categories = [...new Set(stockData.map(i => i.category).filter(Boolean))].sort();
    const select = document.getElementById('category-filter');
    categories.forEach(cat => {
        const opt = document.createElement('option');
        opt.value = cat;
        opt.textContent = cat;
        select.appendChild(opt);
    });
}

function renderStockTable() {
    const search = document.getElementById('stock-search').value.toLowerCase();
    const category = document.getElementById('category-filter').value;
    const tbody = document.getElementById('stock-body');
    tbody.innerHTML = '';

    const filtered = stockData.filter(item => {
        const matchSearch = item.name.toLowerCase().includes(search);
        const matchCat = !category || item.category === category;
        return matchSearch && matchCat;
    });

    if (filtered.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">{% trans "No items found." %}</td></tr>';
        return;
    }

    filtered.forEach(item => {
        const avail = item.available_display !== undefined ? item.available_display : item.available;
        const reserved = item.reserved || 0;
        const availClass = avail <= 0 ? 'text-danger fw-bold' : '';
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td><img src="https://images.evetech.net/types/${item.type_id}/icon?size=32" style="height:28px;border-radius:4px;margin-right:6px;">${item.name}</td>
            <td>${item.group}</td>
            <td class="${availClass}">${avail.toLocaleString()}</td>
            <td><span class="text-warning">${reserved > 0 ? reserved.toLocaleString() : '—'}</span></td>
            <td>${formatNumber(item.unit_price)}</td>
            <td><input type="number" class="form-control form-control-sm" style="width:90px;"
                min="1" max="${avail}" value="1" id="qty-${item.type_id}" ${avail <= 0 ? 'disabled' : ''}></td>
            <td><button class="btn btn-success btn-sm" onclick="addToCart(${item.type_id})" ${avail <= 0 ? 'disabled' : ''}>
                <i class="fas fa-plus"></i>
            </button></td>
        `;
        tbody.appendChild(tr);
    });
}

function addToCart(typeId) {
    const item = stockData.find(i => i.type_id === typeId);
    if (!item) return;
    const qtyInput = document.getElementById('qty-' + typeId);
    const qty = parseInt(qtyInput ? qtyInput.value : 1);
    if (qty <= 0) return;

    const avail = item.available_display !== undefined ? item.available_display : item.available;
    if (avail <= 0) return;

    if (cart[typeId]) {
        cart[typeId].quantity += qty;
        if (cart[typeId].quantity > avail) {
            cart[typeId].quantity = avail;
        }
    } else {
        cart[typeId] = {
            type_id: typeId,
            name: item.name,
            quantity: Math.min(qty, avail),
            unit_price: item.unit_price,
            available: avail,
        };
    }
    renderCart();
}

function removeFromCart(typeId) {
    delete cart[typeId];
    renderCart();
}

function renderCart() {
    const tbody = document.getElementById('cart-body');
    const keys = Object.keys(cart);

    tbody.innerHTML = '';

    if (keys.length === 0) {
        tbody.innerHTML = '<tr id="cart-empty-row"><td colspan="5" class="text-center text-muted">{% trans "No items selected yet." %}</td></tr>';
        document.getElementById('submit-btn').disabled = true;
        document.getElementById('cart-count').textContent = '0';
        document.getElementById('cart-total').textContent = '0 ISK';
        return;
    }

    let grandTotal = 0;
    keys.forEach(typeId => {
        const item = cart[typeId];
        const total = item.quantity * item.unit_price;
        grandTotal += total;
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td><img src="https://images.evetech.net/types/${item.type_id}/icon?size=32" style="height:28px;border-radius:4px;margin-right:6px;">${item.name}</td>
            <td>
                <input type="number" class="form-control form-control-sm" style="width:90px;"
                    min="1" max="${item.available}" value="${item.quantity}"
                    onchange="updateQty(${typeId}, this.value)">
            </td>
            <td>${formatNumber(item.unit_price)} ISK</td>
            <td>${formatNumber(total)} ISK</td>
            <td><button class="btn btn-danger btn-sm" onclick="removeFromCart(${typeId})">
                <i class="fas fa-trash"></i>
            </button></td>
        `;
        tbody.appendChild(tr);
    });

    document.getElementById('cart-count').textContent = keys.length;
    document.getElementById('cart-total').textContent = formatNumber(grandTotal) + ' ISK';
    document.getElementById('submit-btn').disabled = false;

    const payload = Object.values(cart).map(i => ({type_id: i.type_id, quantity: i.quantity}));
    document.getElementById('selected-items-input').value = JSON.stringify(payload);
}

function updateQty(typeId, value) {
    const qty = parseInt(value);
    if (!cart[typeId] || qty <= 0) return;
    cart[typeId].quantity = Math.min(qty, cart[typeId].available);
    renderCart();
}

document.getElementById('stock-search').addEventListener('input', renderStockTable);
document.getElementById('category-filter').addEventListener('change', renderStockTable);

buildCategoryFilter();
renderStockTable();
</script>
{% endblock %}

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

{% block extra_script %}
{% endblock %}
