{% extends 'index.html' %}
{% load static %}
{% load l10n %}
{% load humanize %}

<head>
    {% block title %}Dashboard{% endblock %}
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        .nav-pills .nav-link.active {
            background-color: #007bff;
            border-color: #007bff;
        }
        .table th {
            background-color: #f8f9fa;
            color: #495057;
            font-weight: 600;
        }
        .table td {
            vertical-align: middle;
        }
        .table-hover tbody tr:hover {
            background-color: #f1f1f1;
        }
        .btn-info {
            background-color: #17a2b8;
            border-color: #17a2b8;
        }
        .btn-info:hover {
            background-color: #138496;
            border-color: #117a8b;
        }
        .btn-sm {
            font-size: 0.875rem;
            padding: 0.375rem 0.75rem;
        }
        .section-heading {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }
        .financial-settings {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
        }
        .financial-settings .btn {
            border-radius: 5px;
        }
        .financial-settings .row .col-md-3 {
            margin-bottom: 15px;
        }
        .sort-arrow {
            display: none;
            margin-left: 5px;
            font-size: 0.8em;
        }
        .fa-arrow-up {
            color: green;
        }
        .fa-arrow-down {
            color: red;
        }
    </style>
</head>

{% block content %}
</body>
<div class="container mt-5">
    <!-- Tab Navigation -->
    <ul class="nav nav-pills justify-content-center my-3" role="tablist">
        <li class="nav-item" role="presentation">
            <a class="nav-link active" data-bs-toggle="tab" href="#transactions_list" aria-selected="true" role="tab">
                <i class="fa-solid fa-list"></i> Transactions
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" data-bs-toggle="tab" href="#unpaid_invoices" aria-selected="false" role="tab">
                <i class="fa-solid fa-file-invoice-dollar"></i> Unpaid Invoices
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" data-bs-toggle="tab" href="#recent_invoices" aria-selected="false" role="tab">
                <i class="fa-solid fa-clock-rotate-left"></i> Recent Invoices
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" data-bs-toggle="tab" href="#revenue" aria-selected="false" role="tab">
                <i class="fa-solid fa-chart-line"></i> YTD
            </a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link" data-bs-toggle="tab" href="#mileage_tab" aria-selected="false" role="tab">
                <i class="fa-solid fa-car"></i> Mileage
            </a>
        </li>
    </ul>

    <!-- Tab Content -->
    <div id="myTabContent" class="tab-content">

        <!-- Transactions List -->
        <div class="tab-pane fade show active" id="transactions_list" role="tabpanel">
            <h4 class="section-heading">Recent Transactions</h4>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr class="table-primary">
                            <th>Date</th>
                            <th>Type</th>
                            <th>Subcategory</th>
                            <th>Amount</th>
                            <th>Invoice #</th>
                            <th>Description</th>
                            <th>View</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for transaction in transactions %}
                        <tr>
                            <td>{{ transaction.date }}</td>
                            <td>{{ transaction.trans_type.trans_type }}</td>
                            <td>{{ transaction.sub_cat }}</td>
                            <td>$ {{ transaction.amount|floatformat:2|intcomma }}</td>
                            <td>{{ transaction.invoice_numb }}</td>
                            <td>{{ transaction.transaction }}</td>
                            <td>
                                <a href="{% url 'transaction_detail' transaction.id %}">
                                    <i class="fa-solid fa-eye text-success"></i>
                                </a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Unpaid Invoices -->
        <div class="tab-pane fade" id="unpaid_invoices" role="tabpanel">
            <h4 class="section-heading">Unpaid Invoices</h4>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr class="table-primary">
                            <th>Invoice #</th>
                            <th>Client</th>
                            <th>Event</th>
                            <th>Amount</th>
                            <th>Due Date</th>
                            <th>View</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for invoice in unpaid_invoices %}
                        <tr>
                            <td>{{ invoice.invoice_numb }}</td>
                            <td>{{ invoice.client }}</td>
                            <td>{{ invoice.event }}</td>
                            <td>$ {{ invoice.amount|floatformat:2|intcomma }}</td>
                            <td>{{ invoice.due }}</td>
                            <td>
                                <a href="{% url 'invoice_detail' invoice.id %}">
                                    <i class="fa-solid fa-eye text-success"></i>
                                </a>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="6" class="text-center text-muted">No unpaid invoices found.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Recent Invoices -->
        <div class="tab-pane fade" id="recent_invoices" role="tabpanel">
            <h4 class="section-heading">Recent Invoices</h4>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr class="table-primary">
                            <th>Invoice #</th>
                            <th>Client</th>
                            <th>Event</th>
                            <th>Amount</th>
                            <th>Date</th>
                            <th>Due Date</th>
                            <th>Paid</th>
                            <th>View</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for invoice in recent_invoices %}
                        <tr>
                            <td>{{ invoice.invoice_numb }}</td>
                            <td>{{ invoice.client }}</td>
                            <td>{{ invoice.event }}</td>
                            <td>$ {{ invoice.amount|floatformat:2|intcomma }}</td>
                            <td>{{ invoice.date }}</td>
                            <td>{{ invoice.due }}</td>
                            <td>
                                {% if invoice.paid == "Yes" %}
                                  <span class="badge bg-success">Paid</span>
                                {% else %}
                                  <span class="badge bg-danger">Unpaid</span>
                                {% endif %}
                            </td>
                            <td>
                                <a href="{% url 'invoice_detail' invoice.id %}">
                                    <i class="fa-solid fa-eye text-success"></i>
                                </a>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="8" class="text-center text-muted">No recent invoices found.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Revenue (Income & Expense) for Current Month -->
        <div class="tab-pane fade" id="revenue" role="tabpanel">
            <!-- Card for Current Month Revenue Summary -->
            <div class="card shadow-sm mb-4 bg-light">
                <div class="card-body">
                    <h4 class="card-title mb-3">Current Month</h4>
                    <p class="mb-2">
                        <strong>Total Income:</strong>
                        <span class="text-success">$ {{ income_total|floatformat:2|intcomma }}</span>
                    </p>
                    <p class="mb-0">
                        <strong>Total Expense:</strong>
                        <span class="text-danger">$ {{ expense_total|floatformat:2|intcomma }}</span>
                    </p>
                </div>
            </div>

            <!-- Year-To-Date Subcategory Totals -->
            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title">YTD Summary ({{ current_year }})</h5>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover mt-3 mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th scope="col">Subcategory</th>
                                    <th scope="col">Type</th>
                                    <th scope="col">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for item in ytd_subcategory_totals %}
                                    <tr>
                                        <td>{{ item.sub_cat__sub_cat }}</td>
                                        <td>
                                            <span class="badge {% if item.trans_type__trans_type == 'Income' %}bg-success{% else %}bg-danger{% endif %}">
                                                {{ item.trans_type__trans_type }}
                                            </span>
                                        </td>
                                        <td class="{% if item.trans_type__trans_type == 'Income' %}text-success{% else %}text-danger{% endif %}">
                                            $ {{ item.total|floatformat:1|intcomma }}
                                        </td>
                                    </tr>
                                {% empty %}
                                    <tr>
                                        <td colspan="3" class="text-center text-muted">No data available.</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                            <tfoot>
                                {% if ytd_subcategory_totals %}
                                    <tr class="fw-bold">
                                        <td colspan="2" class="text-end fs-4">Total:</td>
                                        <td class="fs-4 text-success strong">$ {{ ytd_subcategory_grand_total|floatformat:2|intcomma }}</td>
                                    </td>
                                {% endif %}
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <!-- Mileage Log Table -->
        <div class="tab-pane fade" id="mileage_tab" role="tabpanel">
                <hr>
            <h3 class="section-heading text-center mt-2">Mileage Log</h3>
            <div class="row px-3 text-center mb-3">
                <a href="{% url 'mileage_create' %}" class="btn btn-success">
                    <i class="fa-solid fa-plus"></i> Add Mileage
                </a>
                <a href="{% url 'update_mileage_rate' %}" class="btn btn-warning btn-sm">
                    <i class="fa-solid fa-plus"></i> Update Mileage Rate
                </a>  
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Client</th>
                            <th>Vehicle</th>
                            <th>Start</th>
                            <th>End</th>
                            <th>Total</th>
                            <th>Type</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for mile in mileage_list %}
                        <tr>
                            <td>{{ mile.date }}</td>
                            <td>{{ mile.client }}</td>
                            <td>{{ mile.vehicle }}</td>
                            <td>{{ mile.begin }}</td>
                            <td>{{ mile.end }}</td>
                            <td>{{ mile.total }}</td>
                            <td>{{ mile.mileage_type }}</td>
                            <td>
                                <a href="{% url 'mileage_update' mile.id %}">
                                    <i class="fa-solid fa-pen text-success"></i>
                                </a>&nbsp;
                                <a href="{% url 'mileage_delete' mile.id %}">
                                    <i class="fa-solid fa-trash text-warning"></i>
                                </a>
                            </td>
                        </tr>
                        {% empty %}
                        <tr><td colspan="8" class="text-center text-muted">No mileage entries.</td></tr>
                        {% endfor %}
                    </tbody>
                </table>
                <hr>
                <!-- Total Miles and Taxable Dollar Amount for Current Year -->
                <div class="mt-4 text-center">
                    <h3 class="section-heading">Yearly Mileage Summary</h3>
                    <div class="row">
                        <div class="col-md-6">
                            <p>Total Taxable Miles for {{ current_year }}:&nbsp;   <span class="strong fs-5 text-success"> {{ total_miles }}</span></p>
                        </div>
                        <div class="col-md-6">
                            <p>Total Taxable Mileage Amount ($ .{{ mileage_rate }} per mile): &nbsp; <span class="strong fs-5 text-warning">$ {{ taxable_dollars|floatformat:2|intcomma }}</span></p>
                        </div>
                    </div>
                </div>
            </div>  
        </div>
    </div>
    <!-- End of tab content -->
    <hr>
        <!-- Financial Settings -->
    <div class="container my-5">
        <div class="financial-settings">
            <h3 class="text-center pb-3">Financial Settings</h3>
            <div class="row justify-content-center">
                <div class="col-12 col-md-3 mb-3">
                    <a class="btn btn-primary btn-lg w-100" href="{% url 'category_list' %}">Categories</a>
                </div>
                <div class="col-12 col-md-3 mb-3">
                    <a class="btn btn-success btn-lg w-100" href="{% url 'sub_category_list' %}">Sub-Categories</a>
                </div>
                <div class="col-12 col-md-3">
                    <a class="btn btn-warning btn-lg w-100" href="{% url 'client_list' %}">Clients</a>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const table = document.querySelector('#mileage_tab table');
        const headers = table.querySelectorAll('th[data-sort]');
        let sortDirection = true;
    
        // Initially hide all arrows
        const arrows = document.querySelectorAll('.sort-arrow');
        arrows.forEach(arrow => arrow.style.display = 'none');
    
        headers.forEach((header, index) => {
            header.style.cursor = 'pointer';
    
            header.addEventListener('click', () => {
                const rowsArray = Array.from(table.querySelectorAll('tbody tr'));
                const key = index;
    
                // Hide all arrows and reset classes
                arrows.forEach(arrow => arrow.style.display = 'none');
                const upArrow = header.querySelector('.fa-arrow-up');
                const downArrow = header.querySelector('.fa-arrow-down');
    
                if (sortDirection) {
                    upArrow.style.display = 'inline';
                } else {
                    downArrow.style.display = 'inline';
                }
    
                // Sort rows based on column data
                rowsArray.sort((a, b) => {
                    let textA = a.children[key].innerText.trim();
                    let textB = b.children[key].innerText.trim();
    
                    // Try to parse as number, otherwise compare as string
                    let valA = isNaN(textA) ? textA : parseFloat(textA);
                    let valB = isNaN(textB) ? textB : parseFloat(textB);
    
                    return sortDirection
                        ? valA > valB ? 1 : -1
                        : valA < valB ? 1 : -1;
                });
    
                sortDirection = !sortDirection; // Flip the sorting direction
    
                // Reorder rows in the table
                const tbody = table.querySelector('tbody');
                rowsArray.forEach(row => tbody.appendChild(row));
            });
        });
    
        // CSV Export
        document.getElementById('downloadCSV').addEventListener('click', () => {
            const rows = table.querySelectorAll('tr');
            let csv = [];
            rows.forEach(row => {
                let cols = row.querySelectorAll('th, td');
                let rowData = Array.from(cols).map(col => `"${col.innerText.trim()}"`).join(',');
                csv.push(rowData);
            });
    
            const blob = new Blob([csv.join('\n')], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'mileage_log.csv';
            a.click();
            URL.revokeObjectURL(url);
        });
    });
    </script>
</body>
{% endblock %}