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

{% block details %}

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Reports
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
    <li><a href="#" onClick="switchview('#basic')">Basic</a></li>
    <li><a href="#" onClick="switchview('#sys_stats')">Stats by System</a></li>
    <li><a href="#" onClick="switchview('#corp_moons')">Corp Moon Audits</a></li>
  </ul>
</div>
<br/>


<div id="basic">
<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Overall Monthly Tax Revenue</h3>
			</div>
			<div class="panel-body">
			    <div id="taxrevenue"></div>
			    <button type="button" class="btn-sm btn-primary pull-right" id="taxcsv">Export CSV</button>
			</div>
		</div>
	</div>
</div>


<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Monthly Taxes by Users</h3>
			</div>
			<div class="panel-body">
			    <div id="isk"></div>
			    <button type="button" class="btn-sm btn-primary pull-right" id="csv">Export CSV</button>
			</div>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Taxes by User</h3>
			</div>
			<div class="panel-body">
    <div class="table-responsive">
        <table class="table table-striped table-width-fix" id="mains">
            <thead>
                <tr>
                    <th>{% translate 'Name' %}</th>
                    <th>{% translate 'Corp' %}</th>
                    <th>{% translate 'Balance' %}</th>
                    <th>{% translate 'Last Paid' %}</th>
		    <th>{% translate 'Actions' %}</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
			</div>
		</div>
	</div>
</div>
<!--
<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Taxes by Character</h3>
			</div>
			<div class="panel-body">
    <div class="table-responsive">
        <table class="table table-striped table-width-fix" id="chars">
            <thead>
                <tr>
                    <th>{% translate 'Name' %}</th>
                    <th>{% translate 'Corp' %}</th>
                    <th>{% translate 'Main' %}</th>
                    <th>{% translate 'Taxes' %}</th>
                    <th>{% translate 'Credits' %}</th>
                    <th>{% translate 'Balance' %}</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
			</div>
		</div>
	</div>
</div>
-->

<div class="modal" id="modalCredit" tabindex="-1" role="dialog" aria-labelledby="modalCredit">
    <div class="modal-dialog  modal-sm" role="document" id="modalCredit">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">
                    &times;
                </span></button>
                <h4 class="modal-title" id="myModalLabel">Tax Credits</h4>
            </div>

	    <form class="form-horizontal" method=POST action="{% url 'miningtaxes:admin_tables' %}">
            {% csrf_token %}
            <div class="modal-body">
			    <div class="form-group">
				    <label for="user">Recipient:</label>
				    <span id="user"></span>
				    <input type="hidden" id="userid" name="userid">
			    </div>
			    <div class="form-group">
				    <label for="creditbox">Tax credit amount:</label>
				    <input type="text" class="form-control" id="creditbox" name="creditbox">
			    </div>
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">
                    {% translate 'Submit' %}
                </button>
            </div>
	    </form>
        </div>
    </div>
</div>

<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Corp Ledgers</h3>
			</div>
			<div class="panel-body">
			    <div class="table-responsive">
				<table class="table table-striped table-width-fix" id="corp_ledgers">
				    <thead>
					<tr>
					    <th>{% translate 'Date' %}</th>
					    <th>{% translate 'Name' %}</th>
					    <th>{% translate 'Amount' %}</th>
					    <th>{% translate 'Reason' %}</th>
					</tr>
				    </thead>
				    <tbody></tbody>
				</table>
			    </div>
			</div>
		</div>
	</div>
</div>
</div>

<div id="sys_stats" class='hidden'>
<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Average Monthly ISK by System</h3>
			</div>
			<div class="panel-body">
			    <div id="sys_avg_isk"></div>
			</div>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Average Monthly Units of Ore by System</h3>
			</div>
			<div class="panel-body">
			    <div id="sys_avg_q"></div>
			</div>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Average Monthly Taxes by System</h3>
			</div>
			<div class="panel-body">
			    <div id="sys_avg_tax"></div>
			</div>
		</div>
	</div>
</div>

<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
				<button class="btn btn-default" onclick="prior()"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span></button>
				<h3 class="panel-title"><span id='sys_month_disp'></span></h3>
				<button class="btn btn-default" onclick="next()"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></button>
			</div>
			<div class="panel-body">
			    <div class="table-responsive">

				<table class="table table-striped table-width-fix" id="sys_month">
				    <thead>
					<tr>
					    <th>{% translate 'System' %}</th>
					    <th>{% translate 'Ore Type' %}</th>
					    <th>{% translate 'Value' %}</th>
					    <th>{% translate 'Taxes' %}</th>
					</tr>
				    </thead>
				    <tbody></tbody>
				</table>
			    </div>
			</div>
		</div>
	</div>
</div>
<br/>
			    <button type="button" class="btn-sm btn-primary pull-right" id="syscsv">Export All Mining Activity CSV</button>
</div>


<div id="corp_moons" class='hidden'>
<div class="row">
	<div class="col-md-6">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Unregistered Characters (Missing from MiningTax) </h3>
			</div>
			<div class="panel-body">
			    <div class="table-responsive">
				<table class="table table-striped table-width-fix" id="unregistered">
				    <thead>
					<tr>
					    <th>{% translate 'Name' %}</th>
					    <th>{% translate 'Approx. ISK' %}</th>
					    <th>{% translate 'Ore Units' %}</th>
					    <th>{% translate 'Last Mined' %}</th>
					</tr>
				    </thead>
				    <tbody></tbody>
				</table>
			    </div>
			</div>
		</div>
	</div>
	<div class="col-md-6">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Unknown Characters (Missing from Auth)</h3>
			</div>
			<div class="panel-body">
			    <div class="table-responsive">
				<table class="table table-striped table-width-fix" id="unknown">
				    <thead>
					<tr>
					    <th>{% translate 'Name' %}</th>
					    <th>{% translate 'Approx. ISK' %}</th>
					    <th>{% translate 'Ore Units' %}</th>
					    <th>{% translate 'Last Mined' %}</th>
					</tr>
				    </thead>
				    <tbody></tbody>
				</table>
			    </div>
			</div>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-md-12">
    		<div class="panel panel-default">
			<div class="panel-heading" style="display:flex;">
			    <h3 class="panel-title">Corp Moon Records</h3>
			</div>
			<div class="panel-body">
			    <div class="table-responsive">
				<table class="table table-striped table-width-fix" id="corpmoon">
				    <thead>
					<tr>
					    <th>{% translate 'Date' %}</th>
					    <th>{% translate 'Name' %}</th>
					    <th>{% translate 'Ore' %}</th>
					    <th>{% translate 'Quantity' %}</th>
					    <th>{% translate 'Location' %}</th>
					</tr>
				    </thead>
				    <tbody></tbody>
				</table>
			    </div>
			</div>
		</div>
	</div>
</div>
</div>

{% endblock details %}

{% block extra_javascript %}
{% include 'bundles/datatables-js.html' %}
<script type="text/javascript" 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" integrity="sha512-D8lwQ1l9jYC7cgPTITQkT2LZYlyx0kc+oBuLMfh1HGxwoO84e3U/RDuvbNJR1+A7HGmAIf5LMqWIlSl2UfKr7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
{% endblock %}

{% block extra_css %}
{% if NIGHT_MODE %}
        <link rel="stylesheet" type="text/css" href="{% static 'miningtaxes/css/billboards_dark.css' %}">
{% else %}
        <link rel="stylesheet" type="text/css" href="{% static 'miningtaxes/css/billboards_light.css' %}">
{% endif %}
    <link rel="stylesheet" href="{% static 'miningtaxes/css/global.css' %}" type="text/css">
    <link rel="stylesheet" href="{% static 'miningtaxes/css/miningtaxes.css' %}" type="text/css">
    <link rel="stylesheet" href="{% static 'miningtaxes/css/launcher.css' %}" type="text/css">
{% endblock %}

{% block extra_script %}
var user_data;
var user_table;
var unregistered_table;
var unknown_table;
var corpmoon_table;
var csv_data;
var tax_csv_data;
var tax_sys_data;
var curshown = "#basic";
var firstdraw = {"#sys_stats" : true, "#corp_moons" : true, "#basic": false};
var sys_stats_data;

function switchview(pane) {
	if (pane == curshown) { return; }
	$(curshown).addClass("hidden");
	$(pane).removeClass("hidden");
	curshown = pane;
	if (firstdraw[pane]) {
		if (pane == "#sys_stats") { draw_sys_stats(); }
		if (pane == "#corp_moons") { draw_corp_moons(); }
		firstdraw[pane] = false;
	}
}

function exportsysdata() {
        exportToCsv("miningtaxes-allactivity.csv", tax_sys_data);
}


function exporttaxdata() {
        exportToCsv("miningtaxes-revenue.csv", tax_csv_data);
}

function exportdata() {
        exportToCsv("miningtaxes-usertaxes.csv", csv_data);
}

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '\n';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

function populate(rowi) {
	$("#user").html(user_data[rowi].name);
	$("#userid").val(user_data[rowi].user);
	const bal = Math.round((user_data[rowi].balance + Number.EPSILON) * 100) / 100
	$("#creditbox").val(bal);
}
function draw_corp_moons() {
	$.getJSON("{% url 'miningtaxes:admin_corp_mining_history' %}", function (d) {
		unregistered_table = $('#unregistered').DataTable({
		    columns: [
			{ data: 'name' },
			{
			    data: 'isk',
			    render: $.fn.dataTable.render.number(',', '.', 2)
			},
			{
			    data: 'quantity',
			    render: $.fn.dataTable.render.number(',', '.', 0)
			},
			{ data: 'last' },
		    ],
		    order: [[3, "desc"]]
		});
		unknown_table = $('#unknown').DataTable({
		    columns: [
			{ data: 'name' },
			{
			    data: 'isk',
			    render: $.fn.dataTable.render.number(',', '.', 2)
			},
			{
			    data: 'quantity',
			    render: $.fn.dataTable.render.number(',', '.', 0)
			},
			{ data: 'last' },
		    ],
		    order: [[3, "desc"]]
		});
		corpmoon_table = $('#corpmoon').DataTable({
		    columns: [
			{ data: 'date' },
			{ data: 'name' },
			{ data: 'ore' },
			{
			    data: 'quantity',
			    render: $.fn.dataTable.render.number(',', '.', 0)
			},
			{ data: 'location' },
		    ],
		    order: [[0, "desc"]]
		});

		unknown_data = d["unknown_data"];
		unknown_data.forEach( function(row) {
			unknown_table.row.add(row);
		});
		unknown_table.draw();

		unregistered_data = d["unregistered_data"];
		unregistered_data.forEach( function(row) {
			unregistered_table.row.add(row);
		});
		unregistered_table.draw();

		mining_data = d["mining_log"];
		mining_data.forEach( function(row) {
			corpmoon_table.row.add(row);
		});
		corpmoon_table.draw();
	});

}

var sys_months_data;
var sys_months_curi;
var sys_months_order;
var sys_month_table;

function prior() {
if (sys_months_curi == 0) { return;}
sys_months_curi--;
render_sys_month_table();
}

function next() {
if (sys_months_curi == sys_months_order.length - 1) { return;}
sys_months_curi++;
render_sys_month_table();
}

function render_sys_month_table() {
	const m = sys_months_order[sys_months_curi];
	sys_month_table.clear();
	$("#sys_month_disp").html(m);
	Object.keys(sys_months_data[m]).forEach( function(s) {
		Object.keys(sys_months_data[m][s]).forEach( function(g) {
		sys_month_table.row.add({"name": s, "ore": g, "isk": sys_months_data[m][s][g].isk, "tax": sys_months_data[m][s][g].tax});
		});
	});
	sys_month_table.draw();
}

function draw_sys_stats() {
	$.getJSON("{% url 'miningtaxes:admin_mining_by_sys_json' %}", function (d) {
		sys_months_data = d['tables'];
		sys_months_order = Object.keys(sys_months_data).sort();
		sys_months_curi = sys_months_order.length - 1;

		sys_month_table = $('#sys_month').DataTable({
		    columns: [
			{ data: 'name' },
			{ data: 'ore' },
			{
			    data: 'isk',
			    render: $.fn.dataTable.render.number(',', '.', 2)
			},
			{
			    data: 'tax',
			    render: $.fn.dataTable.render.number(',', '.', 2)
			}
		    ],
		    order: [[3, "desc"]]
		});
		render_sys_month_table();

var isk = bb.generate({
data: {
x: "x",
      columns: [],
      type: "bar",
	     },
	     bar: {
	     width: {
	     ratio: 0.5
	     }
	     },
	     axis: {
	     x: {type: "category"},
			y: {
			tick: { format: function(x) {
			return d3.format(",")(x);
					  } },
					  label: "ISK"
						  },
						  },
						  bindto:"#sys_avg_isk"
							  });
							  isk.load({columns: d['anal']['isk']});

var isk = bb.generate({
data: {
x: "x",
      columns: [],
      type: "bar",
	     },
	     bar: {
	     width: {
	     ratio: 0.5
	     }
	     },
	     axis: {
	     x: {type: "category"},
			y: {
			tick: { format: function(x) {
			return d3.format(",")(x);
					  } },
					  label: "ISK"
						  },
						  },
						  bindto:"#sys_avg_tax"
							  });
							  isk.load({columns: d['anal']['tax']});

var isk = bb.generate({
data: {
x: "x",
      columns: [],
      type: "bar",
	     },
	     bar: {
	     width: {
	     ratio: 0.5
	     }
	     },
	     axis: {
	     x: {type: "category"},
			y: {
			tick: { format: function(x) {
			return d3.format(",")(x);
					  } },
					  label: "Quantity"
						  },
						  },
						  bindto:"#sys_avg_q"
							  });
							  isk.load({columns: d['anal']['q']});


tax_sys_data = d["csv"];
$("#syscsv").click(exportsysdata);
			 });
			 }

$(document).ready(function () {
	$.getJSON("{% url 'miningtaxes:admin_tax_revenue_json' %}", function (d) {
		var taxrevenue = bb.generate({
			data: {
				x: "x",
				columns: [],
				axes: { isk: "y"},
				type: "bar",
			},
			bar: {
			    width: {
			      ratio: 0.5
			    }
			},
		        legend: { show: false },
			axis: {
				x: {
					padding: { right: 5000*60*60*12 },
					type: "timeseries",
					tick: { format: "%Y-%m", rotate: 45 }
				},
				y: {
					tick: { format: function(x) {
						return d3.format(",")(x);
					} },
					label: "ISK"
				},
			},
			bindto:"#taxrevenue"
		});
		taxrevenue.load({columns: [d['xdata'], d['ydata']]});
		tax_csv_data = d["csv"];
		$("#taxcsv").click(exporttaxdata);
		} );
	$.getJSON("{% url 'miningtaxes:admin_month_json' %}", function (d) {
		var iskchart = bb.generate({
			data: {
				x: "x",
				columns: [],
				axes: { isk: "y"},
			},
			axis: {
				x: {
					padding: { right: 5000*60*60*12 },
					type: "timeseries",
					tick: { format: "%Y-%m", rotate: 45 }
				},
				y: {
					tick: { format: function(x) {
						return d3.format(",")(x);
					} },
					label: "ISK"
				},
			},
			bindto:"#isk"
		});
		for (var i = 0 ; i < d["ydata"].length; i++) {
			iskchart.load({columns: [d['xdata'], d['ydata'][i]]});
		}
		csv_data = d["csv"];
		$("#csv").click(exportdata);
		} );
	$.getJSON("{% url 'miningtaxes:admin_main_json' %}", function (d) {
		user_data = d["data"];
		user_data.forEach( function(row) {
			user_table.row.add(row);
		});
		user_table.draw();
	});
        user_table = $('#mains').DataTable({
            columns: [
                { data: 'name' },
                { data: 'corp' },
                {
                    data: 'balance',
                    render: $.fn.dataTable.render.number(',', '.', 2)
                },
		{ data: 'last_paid' },
		{ data: 'action' },
            ],
            order: [[2, "desc"]]
        });
        $('#corp_ledgers').DataTable({
            ajax: {
                url: "{% url 'miningtaxes:admin_corp_ledger' %}",
                dataSrc: 'data',
                cache: false
            },
            columns: [
                { data: 'date' },
                { data: 'name' },
                {
                    data: 'amount',
                    render: $.fn.dataTable.render.number(',', '.', 2)
                },
                { data: 'reason' },
            ],
            order: [[0, "desc"]]
        });
      /*
        $('#chars').DataTable({
            ajax: {
                url: "{% url 'miningtaxes:admin_char_json' %}",
                dataSrc: 'data',
                cache: false
            },
            columns: [
                { data: 'name' },
                { data: 'corp' },
                { data: 'main_name' },
                {
                    data: 'taxes',
                    render: $.fn.dataTable.render.number(',', '.', 2)
                },
                {
                    data: 'credits',
                    render: $.fn.dataTable.render.number(',', '.', 2)
                },
                {
                    data: 'balance',
                    render: $.fn.dataTable.render.number(',', '.', 2)
                }
            ],
            order: [[5, "desc"]]
        });
									      */
});
{% endblock %}
