{% extends 'core/base.html' %}
{% load currency_filters %}
{% load static %}

{% block title %}Branch: {{ branch.name }} - SwiftPOS{% endblock %}

{% block topbar_title %}
Branch Detail
{% endblock %}

{% block content %}
<div class="container-fluid px-0">

    <!-- Toast Messages -->
    <div class="swiftpos-toast-container">
        {% if messages %}
            {% for message in messages %}
                <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}">
                    <div class="toast-icon">
                        {% if message.tags == 'success' %}
                            <i class="fas fa-check-circle"></i>
                        {% elif message.tags == 'error' or message.tags == 'danger' %}
                            <i class="fas fa-exclamation-circle"></i>
                        {% elif message.tags == 'warning' %}
                            <i class="fas fa-exclamation-triangle"></i>
                        {% else %}
                            <i class="fas fa-info-circle"></i>
                        {% endif %}
                    </div>
                    <div class="toast-text">
                        {{ message }}
                    </div>
                </div>
            {% endfor %}
        {% endif %}
    </div>

    <!-- Header -->
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
        <div>
            <h5 class="mb-0">
                {{ branch.name }}
                {% if not branch.is_active %}
                    <span class="badge bg-danger-subtle text-danger">Inactive</span>
                {% endif %}
            </h5>
            <div class="text-muted small">
                {{ branch.address|default:"No address provided" }}
                {% if branch.phone %}
                    · {{ branch.phone }}
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Metrics -->
    <div class="row g-3 mb-3">
        <div class="col-12 col-sm-6 col-xl-3">
            <div class="metric-card sp-animate-card">
                <div class="metric-card-title">Today Sales</div>
                <div class="metric-card-value">{% money today_sales %}</div>
                <div class="metric-card-sub">
                    {{ total_orders_today }} order{{ total_orders_today|pluralize }}
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="metric-card sp-animate-card">
                <div class="metric-card-title">This Month Sales</div>
                <div class="metric-card-value">{% money month_sales %}</div>
                <div class="metric-card-sub">
                    {{ total_orders_month }} order{{ total_orders_month|pluralize }}
                </div>
            </div>
        </div>

        <div class="col-12 col-sm-6 col-xl-3">
            <div class="metric-card sp-animate-card">
                <div class="metric-card-title">Users in Branch</div>
                <div class="metric-card-value">{{ users|length }}</div>
                <div class="metric-card-sub">
                    Admins, managers & cashiers
                </div>
            </div>
        </div>
    </div>

    <!-- Two-column layout: Users + Today Orders -->
    <div class="row g-3">
        <!-- Users table -->
        <div class="col-lg-5">
            <div class="card sp-animate-card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-users"></i> Branch Users
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div class="sp-table-container">
                        <table class="table align-middle mb-0 table-hover">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Role</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% if users %}
                                    {% for u in users %}
                                        <tr>
                                            <td>
                                                <div class="fw-semibold small">
                                                    {{ u.get_full_name|default:u.username }}
                                                </div>
                                                <div class="small text-muted">
                                                    {{ u.email|default:"" }}
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge bg-info-subtle">
                                                    {{ u.role|title }}
                                                </span>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                {% else %}
                                    <tr>
                                        <td colspan="2" class="text-center text-muted small py-3">
                                            No users assigned to this branch yet.
                                        </td>
                                    </tr>
                                {% endif %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Today orders -->
        <div class="col-lg-7">
            <div class="card sp-animate-card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-list"></i> Today Orders
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div class="sp-table-container">
                        <table class="table align-middle mb-0 table-hover">
                            <thead>
                                <tr>
                                    <th>Order</th>
                                    <th>Customer</th>
                                    <th>Amount</th>
                                    <th>Cashier</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% if orders_today %}
                                    {% for order in orders_today %}
                                        <tr>
                                            <td>
                                                <div class="fw-semibold small">
                                                    <a href="{% url 'sales:print_receipt' order.id %}"
                                                       class="text-decoration-none text-primary">
                                                        {{ order.order_number }}
                                                    </a>
                                                </div>
                                                <div class="text-muted small">
                                                    {{ order.created_at|date:"Y-m-d H:i" }}
                                                </div>
                                            </td>
                                            <td>
                                                {{ order.customer_name|default:"Walk-in" }}
                                            </td>
                                            <td class="text-end">
                                                {% money order.final_amount %}
                                            </td>
                                            <td>
                                                {{ order.cashier }}
                                            </td>
                                        </tr>
                                    {% endfor %}
                                {% else %}
                                    <tr>
                                        <td colspan="4" class="text-center text-muted small py-3">
                                            No orders recorded today for this branch.
                                        </td>
                                    </tr>
                                {% endif %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <!-- Inventory Allocations -->
    <div class="row g-3 mt-1">
        <div class="col-12">
            <div class="card sp-animate-card h-100">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-boxes"></i> Inventory Allocations
                    </h6>
                    <div class="d-flex align-items-center gap-2">
                        <input type="text" id="branchStockSearch" class="form-control form-control-sm shadow-none" placeholder="Search product or SKU..." autocomplete="off" style="width: 220px; border-radius: 8px;">
                        <select id="branchStockCategory" class="form-select form-select-sm shadow-none" style="width: 150px; border-radius: 8px;">
                            <option value="">All Categories</option>
                        </select>
                        <a href="{% url 'inventory:product_list' %}" class="btn btn-sm btn-outline-primary ms-2">Manage Stock</a>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="sp-table-container">
                        <table class="table align-middle mb-0 table-hover" id="branchStockTable">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Category</th>
                                    <th>Branch Quantity</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% if branch_stocks %}
                                    {% for bs in branch_stocks %}
                                        <tr>
                                            <td>
                                                <div class="fw-semibold small">
                                                    {{ bs.product.name }}
                                                </div>
                                                <div class="small text-muted">
                                                    SKU: {{ bs.product.sku }}
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge" style="background-color: {{ bs.product.category.color_code }}20; color: {{ bs.product.category.color_code }};">
                                                    {{ bs.product.category.name }}
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge {% if bs.quantity > 0 %}bg-success-subtle text-success{% else %}bg-danger-subtle text-danger{% endif %} border-0 px-2 py-1">
                                                    {{ bs.quantity }} units assigned
                                                </span>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                {% else %}
                                    <tr>
                                        <td colspan="3" class="text-center text-muted small py-4">
                                            <i class="fas fa-box-open fs-4 text-muted mx-auto d-block mb-2"></i>
                                            Branch inventory is completely empty. Transfer stock to this branch to begin selling.
                                        </td>
                                    </tr>
                                {% endif %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('branchStockSearch');
    const categorySelect = document.getElementById('branchStockCategory');
    const table = document.getElementById('branchStockTable');
    
    if(!table || !searchInput || !categorySelect) return;
    
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    // Extract unique categories from the table to populate the dropdown
    const categories = new Set();
    rows.forEach(row => {
        if(row.children.length >= 2) {
            const catBadge = row.children[1].querySelector('.badge');
            if(catBadge) categories.add(catBadge.textContent.trim());
        }
    });
    
    categories.forEach(cat => {
        const opt = document.createElement('option');
        opt.value = cat.toLowerCase();
        opt.textContent = cat;
        categorySelect.appendChild(opt);
    });

    // Filter Logic
    function filterTable() {
        const searchTerm = searchInput.value.toLowerCase();
        const categoryTerm = categorySelect.value.toLowerCase();
        
        let visibleCount = 0;

        rows.forEach(row => {
            // Skip the "empty" message row if present
            if(row.children.length === 1) return;

            const productColText = row.children[0].textContent.toLowerCase();
            const categoryColText = row.children[1].textContent.toLowerCase().trim();
            
            const matchesSearch = productColText.includes(searchTerm);
            const matchesCategory = categoryTerm === "" || categoryColText === categoryTerm;
            
            if(matchesSearch && matchesCategory) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        });

        // Handle completely empty search results
        let noResultsRow = tbody.querySelector('.no-results-row');
        if (visibleCount === 0 && rows.length > 0 && rows[0].children.length > 1) {
            if(!noResultsRow) {
                noResultsRow = document.createElement('tr');
                noResultsRow.className = 'no-results-row';
                noResultsRow.innerHTML = '<td colspan="3" class="text-center text-muted py-4"><i class="fas fa-search mb-2 fs-4 text-muted"></i><br>No matching products found.</td>';
                tbody.appendChild(noResultsRow);
            }
            noResultsRow.style.display = '';
        } else if(noResultsRow) {
            noResultsRow.style.display = 'none';
        }
    }

    searchInput.addEventListener('input', filterTable);
    categorySelect.addEventListener('change', filterTable);
});
</script>
{% endblock %}
