{% extends 'base.html' %}
{% load static humanize %}

{% block title %}Dashboard | Fox Fitt{% endblock %}

{% block content %}
<style>
    .resource-hidden { display: none !important; }
    .quick-action-btn { display: flex; align-items: center; gap: 0.5rem; padding: 0.6rem 1rem; border-radius: 0.5rem; font-weight: 500; font-size: 0.875rem; transition: all 0.15s; text-decoration: none; }
    .quick-action-btn:hover { transform: translateX(3px); }
    @media (max-width: 767.98px) {
        .dashboard-header .display-5 { font-size: 1.75rem; }
    }
</style>
<div class="dashboard-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="display-5 mb-2">Welcome Back, {% if user.is_authenticated %}{{ user.username }}{% else %}Admin{% endif %}</h1>
                <p class="lead opacity-75">Track your projects, workers, and payroll in one place.</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="{% url 'log_attendance' %}" class="btn btn-accent shadow-sm">
                    + Log Daily Work
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container mb-5">
    <!-- Stats Row -->
    <div class="row g-4 mb-4">
        {% if is_admin_user %}
        <!-- Admin: Outstanding Payments -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card p-4 border-start border-4 border-warning h-100">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Outstanding Payments</p>
                        <h2 class="mb-0">R {{ outstanding_total|floatformat:2|intcomma }}</h2>
                    </div>
                    <div class="p-3 bg-warning bg-opacity-10 rounded-circle text-warning">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
                    </div>
                </div>
                <a href="{% url 'payroll_dashboard' %}" class="small text-muted mt-2 d-block stretched-link">View details &rarr;</a>
            </div>
        </div>
        <!-- Admin: Paid This Month -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card p-4 border-start border-4 border-success h-100">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Paid This Month</p>
                        <h2 class="mb-0">R {{ recent_payments_total|floatformat:2|intcomma }}</h2>
                    </div>
                    <div class="p-3 bg-success bg-opacity-10 rounded-circle text-success">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                    </div>
                </div>
            </div>
        </div>
        <!-- Admin: Active Loans -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card p-4 border-start border-4 border-danger h-100">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Active Loans</p>
                        <h2 class="mb-0">R {{ active_loans_total|floatformat:2|intcomma }}</h2>
                        <small class="text-muted">{{ active_loans_count }} loan{{ active_loans_count|pluralize }}</small>
                    </div>
                    <div class="p-3 bg-danger bg-opacity-10 rounded-circle text-danger">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
                    </div>
                </div>
                <a href="{% url 'payroll_dashboard' %}?status=loans" class="small text-muted mt-1 d-block stretched-link">View loans &rarr;</a>
            </div>
        </div>
        <!-- Admin: Outstanding Project Costs (New) -->
        <div class="col-xl-3 col-md-6">
            <div class="card stat-card border-start border-4 border-info h-100">
                <div class="card-body p-4 pb-0">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                         <p class="text-uppercase small fw-bold mb-0 opacity-75">Outstanding by Project</p>
                         <div class="p-2 bg-info bg-opacity-10 rounded-circle text-info">
                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3"/></svg>
                        </div>
                    </div>
                    <div class="overflow-auto" style="max-height: 100px;">
                        {% if outstanding_project_costs %}
                            <ul class="list-unstyled mb-0 small">
                            {% for p in outstanding_project_costs %}
                                <li class="d-flex justify-content-between py-1 border-bottom border-light">
                                    <span class="text-truncate me-2" style="max-width: 120px;" title="{{ p.name }}">{{ p.name }}</span>
                                    <span class="fw-bold">R {{ p.cost|intcomma }}</span>
                                </li>
                            {% endfor %}
                            </ul>
                        {% else %}
                            <p class="text-muted small">No outstanding costs.</p>
                        {% endif %}
                    </div>
                </div>
                 <div class="card-footer bg-transparent border-0 pt-0 pb-3">
                     <a href="{% url 'payroll_dashboard' %}" class="small text-muted stretched-link">View payroll &rarr;</a>
                 </div>
            </div>
        </div>
        {% else %}
        <!-- Non-admin: Active Projects -->
        <div class="col-md-4">
            <div class="card stat-card p-4 border-start border-4 border-info">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Active Projects</p>
                        <h2 class="mb-0">{{ projects_count }}</h2>
                    </div>
                    <div class="p-3 bg-info bg-opacity-10 rounded-circle text-info">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>
                    </div>
                </div>
            </div>
        </div>
        <!-- Non-admin: Active Teams -->
        <div class="col-md-4">
            <div class="card stat-card p-4 border-start border-4 border-secondary">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Active Teams</p>
                        <h2 class="mb-0">{{ teams_count }}</h2>
                    </div>
                    <div class="p-3 bg-secondary bg-opacity-10 rounded-circle text-secondary">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                    </div>
                </div>
            </div>
        </div>
        <!-- Non-admin: Active Workers -->
        <div class="col-md-4">
             <div class="card stat-card p-4">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-uppercase small fw-bold mb-1 opacity-75">Active Workers</p>
                        <h2 class="mb-0">{{ workers_count }}</h2>
                    </div>
                    <div class="p-3 bg-primary bg-opacity-10 rounded-circle text-primary">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <div class="row g-4">
        <!-- Left Column -->
        <div class="col-lg-8">
            <!-- This Week Summary -->
            <div class="card p-4 mb-4">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-calendar-week me-2"></i>This Week</h5>
                    <a href="{% url 'work_log_list' %}?view=calendar" class="btn btn-sm btn-link text-decoration-none">View Calendar &rarr;</a>
                </div>
                <div class="d-flex flex-wrap gap-4 mt-3">
                    <div class="text-center">
                        <div class="fs-3 fw-bold text-primary">{{ week_worker_days }}</div>
                        <div class="text-muted small">Worker-Days</div>
                    </div>
                    <div class="text-center">
                        <div class="fs-3 fw-bold text-primary">{{ week_projects }}</div>
                        <div class="text-muted small">Projects</div>
                    </div>
                    <div class="text-center">
                        <div class="fs-3 fw-bold text-primary">{{ workers_count }}</div>
                        <div class="text-muted small">Active Workers</div>
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="card p-4 mb-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Recent Activity</h5>
                    <a href="{% url 'work_log_list' %}" class="btn btn-sm btn-link text-decoration-none">View All &rarr;</a>
                </div>
                {% if recent_logs %}
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th>
                                <th>Project</th>
                                <th>Team</th>
                                <th>Workers</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for log in recent_logs %}
                            <tr>
                                <td class="text-muted small">{{ log.date|date:"D, d M" }}</td>
                                <td><strong class="small">{{ log.project.name }}</strong></td>
                                <td class="small">{% if log.team %}{{ log.team.name }}{% else %}<span class="text-muted">-</span>{% endif %}</td>
                                <td class="small">{{ log.workers.count }} labourer{{ log.workers.count|pluralize }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-4">
                    <p class="text-muted mb-2">No recent work logs found.</p>
                    <a href="{% url 'log_attendance' %}" class="btn btn-sm btn-outline-primary">Create First Log</a>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- Right Column -->
        <div class="col-lg-4">
            {% if is_admin_user %}
            <!-- Quick Actions -->
            <div class="card p-4 mb-4">
                <h5 class="mb-3">Quick Actions</h5>
                <div class="d-grid gap-2">
                    <a href="{% url 'log_attendance' %}" class="quick-action-btn btn btn-outline-primary">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="12" y1="18" x2="12" y2="12"></line><line x1="9" y1="15" x2="15" y2="15"></line></svg>
                        Log Daily Work
                    </a>
                    <a href="{% url 'payroll_dashboard' %}" class="quick-action-btn btn btn-outline-success">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
                        Run Payroll
                    </a>
                    <a href="{% url 'work_log_list' %}" class="quick-action-btn btn btn-outline-secondary">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
                        View History
                    </a>
                </div>
            </div>
            {% endif %}

            {% if user.is_staff or user.is_superuser %}
            <!-- Manage Resources -->
            <div class="card p-4">
                <h5 class="mb-2">Manage Resources</h5>
                <p class="text-muted small mb-3">Toggle active status. Inactive items are hidden from forms.</p>

                <!-- Feedback Toast -->
                <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
                  <div id="liveToast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
                    <div class="d-flex">
                      <div class="toast-body" id="toastMessage">Status updated.</div>
                      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                    </div>
                  </div>
                </div>

                <ul class="nav nav-tabs nav-fill mb-3" id="manageTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active py-1 px-2 small" id="m-workers-tab" data-bs-toggle="tab" data-bs-target="#m-workers" type="button" role="tab">Workers</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link py-1 px-2 small" id="m-projects-tab" data-bs-toggle="tab" data-bs-target="#m-projects" type="button" role="tab">Projects</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link py-1 px-2 small" id="m-teams-tab" data-bs-toggle="tab" data-bs-target="#m-teams" type="button" role="tab">Teams</button>
                    </li>
                </ul>

                <!-- Filter: Active / Inactive / All -->
                <div class="btn-group btn-group-sm w-100 mb-3" id="resourceFilter" role="group">
                    <button type="button" class="btn btn-outline-secondary active" data-filter="active">Active</button>
                    <button type="button" class="btn btn-outline-secondary" data-filter="inactive">Inactive</button>
                    <button type="button" class="btn btn-outline-secondary" data-filter="all">All</button>
                </div>

                <div class="tab-content" style="max-height: 350px; overflow-y: auto;">
                    <!-- Workers -->
                    <div class="tab-pane fade show active" id="m-workers" role="tabpanel">
                        {% for worker in all_workers %}
                        <div class="resource-row d-flex justify-content-between align-items-center py-2 border-bottom {% if not worker.is_active %}resource-hidden{% endif %}" data-active="{% if worker.is_active %}true{% else %}false{% endif %}">
                            <div>
                                <strong class="small">{{ worker.name }}</strong>
                                <div class="text-muted" style="font-size: 0.7rem;">{{ worker.id_no }}</div>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input resource-toggle" type="checkbox" role="switch"
                                       data-model="worker" data-id="{{ worker.id }}"
                                       {% if worker.is_active %}checked{% endif %}>
                            </div>
                        </div>
                        {% empty %}
                        <p class="text-muted small">No workers found.</p>
                        {% endfor %}
                        <p class="text-muted small text-center mt-2 resource-empty" style="display:none;">No matching items.</p>
                    </div>

                    <!-- Projects -->
                    <div class="tab-pane fade" id="m-projects" role="tabpanel">
                        {% for project in all_projects %}
                        <div class="resource-row d-flex justify-content-between align-items-center py-2 border-bottom {% if not project.is_active %}resource-hidden{% endif %}" data-active="{% if project.is_active %}true{% else %}false{% endif %}">
                            <strong class="small">{{ project.name }}</strong>
                            <div class="form-check form-switch">
                                <input class="form-check-input resource-toggle" type="checkbox" role="switch"
                                       data-model="project" data-id="{{ project.id }}"
                                       {% if project.is_active %}checked{% endif %}>
                            </div>
                        </div>
                        {% empty %}
                        <p class="text-muted small">No projects found.</p>
                        {% endfor %}
                        <p class="text-muted small text-center mt-2 resource-empty" style="display:none;">No matching items.</p>
                    </div>

                    <!-- Teams -->
                    <div class="tab-pane fade" id="m-teams" role="tabpanel">
                        {% for team in all_teams %}
                        <div class="resource-row d-flex justify-content-between align-items-center py-2 border-bottom {% if not team.is_active %}resource-hidden{% endif %}" data-active="{% if team.is_active %}true{% else %}false{% endif %}">
                            <div>
                                <strong class="small">{{ team.name }}</strong>
                                <div class="text-muted" style="font-size: 0.7rem;">{{ team.workers.count }} workers</div>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input resource-toggle" type="checkbox" role="switch"
                                       data-model="team" data-id="{{ team.id }}"
                                       {% if team.is_active %}checked{% endif %}>
                            </div>
                        </div>
                        {% empty %}
                        <p class="text-muted small">No teams found.</p>
                        {% endfor %}
                        <p class="text-muted small text-center mt-2 resource-empty" style="display:none;">No matching items.</p>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

{% if user.is_staff or user.is_superuser %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const toggles = document.querySelectorAll('.resource-toggle');
    const toastEl = document.getElementById('liveToast');
    const toast = new bootstrap.Toast(toastEl);
    const toastMessage = document.getElementById('toastMessage');

    // --- Resource Filter (Active / Inactive / All) ---
    let currentFilter = 'active';
    const filterBtns = document.querySelectorAll('#resourceFilter button');

    function applyFilter() {
        document.querySelectorAll('.resource-row').forEach(row => {
            const isActive = row.dataset.active === 'true';
            let show = false;
            if (currentFilter === 'all') show = true;
            else if (currentFilter === 'active') show = isActive;
            else if (currentFilter === 'inactive') show = !isActive;
            if (show) {
                row.classList.remove('resource-hidden');
            } else {
                row.classList.add('resource-hidden');
            }
        });
        document.querySelectorAll('.tab-pane').forEach(pane => {
            const rows = pane.querySelectorAll('.resource-row');
            const visibleRows = Array.from(rows).filter(r => !r.classList.contains('resource-hidden'));
            const emptyMsg = pane.querySelector('.resource-empty');
            if (emptyMsg) {
                emptyMsg.style.display = (rows.length > 0 && visibleRows.length === 0) ? '' : 'none';
            }
        });
    }

    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            currentFilter = this.dataset.filter;
            applyFilter();
        });
    });

    applyFilter();

    // --- Toggle handler ---
    toggles.forEach(toggle => {
        toggle.addEventListener('change', function() {
            const model = this.dataset.model;
            const id = this.dataset.id;
            const isChecked = this.checked;
            const row = this.closest('.resource-row');
            const url = `/manage-resources/toggle/${model}/${id}/`;

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (response.ok) return response.json();
                throw new Error('Network error');
            })
            .then(data => {
                if (data.success) {
                    row.dataset.active = isChecked ? 'true' : 'false';
                    toastMessage.textContent = data.message;
                    toastEl.classList.remove('bg-danger');
                    toastEl.classList.add('bg-success');
                    toast.show();
                    applyFilter();
                } else {
                    this.checked = !isChecked;
                }
            })
            .catch(error => {
                this.checked = !isChecked;
                toastMessage.textContent = "Error updating status.";
                toastEl.classList.remove('bg-success');
                toastEl.classList.add('bg-danger');
                toast.show();
            });
        });
    });
});
</script>
{% endif %}
{% endblock %}