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

{% block details %}

<div class="row g-3 mb-3">

    <div class="col-md-3">
        <div class="card h-100">
            <div class="card-header">
                <i class="fas fa-chart-pie me-1"></i> {% trans "Top Items — Last 3 Months" %}
            </div>
            <div class="card-body d-flex align-items-center justify-content-center">
                <div id="lastthree" style="width:100%;"></div>
            </div>
        </div>
    </div>

    <div class="col-md-9">
        <div class="card h-100">
            <div class="card-header">
                <i class="fas fa-chart-line me-1"></i> {% trans "ISK & Donation Performance" %}
            </div>
            <div class="card-body">
                <div id="isk"></div>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-chart-bar me-1"></i> {% trans "Contract & Donation Count" %}
            </div>
            <div class="card-body">
                <div id="donations"></div>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <i class="fas fa-coins me-1"></i> {% trans "ISK per Item Category" %}
            </div>
            <div class="card-body">
                <div id="categoryisk"></div>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card h-100">
            <div class="card-header">
                <i class="fas fa-boxes me-1"></i> {% trans "Quantity per Item Category" %}
            </div>
            <div class="card-body">
                <div id="categoryq"></div>
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="fas fa-layer-group me-1"></i> {% trans "Statistics per Item Category" %}</span>
                <button class="btn btn-sm btn-outline-secondary" onclick="exportdata()">
                    <i class="fas fa-download me-1"></i> {% trans "Export CSV" %}
                </button>
            </div>
            <div class="card-body">
                <div id="categories" class="d-flex flex-wrap gap-2 mb-3"></div>
                <div class="row g-3">
                    <div class="col-md-12">
                        <div class="card border-0 bg-light">
                            <div class="card-header bg-light fw-semibold">{% trans "ISK per Category" %}</div>
                            <div class="card-body">
                                <div id="itemisk"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="card border-0 bg-light">
                            <div class="card-header bg-light fw-semibold">{% trans "Quantity per Category" %}</div>
                            <div class="card-body">
                                <div id="itemq"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

{% endblock %}

{% block extra_javascript %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.6.1/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/billboard.js/3.5.1/billboard.min.js"></script>
<script>
{% autoescape off %}

const bbTheme = {
    color: {
        pattern: ["#0d6efd","#20c997","#fd7e14","#dc3545","#6f42c1","#0dcaf0","#ffc107","#198754"]
    },
    grid: { y: { show: true } },
    point: { r: 3, focus: { expand: { r: 5 } } },
    legend: { position: "bottom" },
};

function exportToCsv(filename, rows) {
    var csv = rows.map(row =>
        row.map(val => {
            val = val === null ? '' : String(val);
            if (/[",\n]/.test(val)) val = '"' + val.replace(/"/g, '""') + '"';
            return val;
        }).join(',')
    ).join('\n');
    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    var link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function render(k) {
    const cat2items = {{categories}};

    var itemisk = bb.generate(Object.assign({}, bbTheme, {
        data: { x: "x", columns: [], type: "line" },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: {
                tick: { format: x => hscaling["items"] === "" ? d3.format(",")(x) : d3.format(",")(x) + " " + hscaling["items"][0] },
                label: "ISK (" + hscaling["items"] + ")",
            },
        },
        bindto: "#itemisk"
    }));

    var itemq = bb.generate(Object.assign({}, bbTheme, {
        data: { x: "x", columns: [], type: "line" },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: { tick: { format: x => d3.format(",")(x) }, label: "Quantity" },
        },
        bindto: "#itemq"
    }));

    cat2items[k].forEach(it => {
        itemisk.load({ columns: [data['x'], data["items"][it][0]] });
        itemq.load({ columns: [data['x'], data["items"][it][1]] });
    });
}

function exportdata() {
    exportToCsv("buyback.csv", {{export}});
}

var data;
var hscaling;

(function () {
    data = {{stats}};
    hscaling = {{hscaling}};

    bb.generate(Object.assign({}, bbTheme, {
        data: {
            x: "x",
            columns: [data["x"], data["overall"]["all"][0], data["donations"]["all"][0]],
        },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: {
                tick: { format: x => hscaling["overall"] === "" ? d3.format(",")(x) : d3.format(",")(x) + " " + hscaling["overall"][0] },
                label: "ISK (" + hscaling["overall"] + ")",
            },
        },
        bindto: "#isk"
    }));

    bb.generate(Object.assign({}, bbTheme, {
        data: {
            x: "x",
            columns: [data["x"], data["overall"]["all"][1], data["donations"]["all"][1]],
        },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: { tick: { format: x => d3.format(",")(x) }, label: "Count" },
        },
        bindto: "#donations"
    }));

    var catisk = bb.generate(Object.assign({}, bbTheme, {
        data: { x: "x", columns: [], type: "line" },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: {
                tick: { format: x => hscaling["categories"] === "" ? d3.format(",")(x) : d3.format(",")(x) + " " + hscaling["categories"][0] },
                label: "ISK (" + hscaling["categories"] + ")",
            },
        },
        bindto: "#categoryisk"
    }));

    var catq = bb.generate(Object.assign({}, bbTheme, {
        data: { x: "x", columns: [], type: "line" },
        axis: {
            x: { type: "timeseries", tick: { format: "%Y-%m" } },
            y: { tick: { format: x => d3.format(",")(x) }, label: "Quantity" },
        },
        bindto: "#categoryq"
    }));

    bb.generate(Object.assign({}, bbTheme, {
        data: {
            columns: {{lastthree}},
            type: "donut",
        },
        donut: { title: "" },
        bindto: "#lastthree"
    }));

    var html = "";
    for (const [key, value] of Object.entries(data.categories)) {
        html += `<button type="button" class="btn btn-sm btn-outline-primary" onclick="render('${key}')">${key}</button>`;
        catisk.load({ columns: [data['x'], value[0]] });
        catq.load({ columns: [data['x'], value[1]] });
    }
    document.getElementById("categories").innerHTML = html;

})();
{% endautoescape %}
</script>
{% endblock %}

{% block extra_css %}
{% include "buybackprogram/bundles/buybackprogram-css-light.html" %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/billboard.js/3.5.1/billboard.min.css">
{% endblock %}
