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

{% block title %}Work Log History | Fox Fitt{% endblock %}

{% block head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
{% endblock %}

{% block content %}
<div class="dashboard-header pb-5">
    <div class="container">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
            <div>
                <h1 class="display-5 mb-2">Work Log History</h1>
                <p class="lead opacity-75 mb-0">Filter and review historical daily work logs and adjustments.</p>
            </div>
            <div class="d-flex flex-wrap gap-2 align-items-center">
                <!-- View Switcher -->
                <div class="btn-group me-2 shadow-sm" role="group">
                  <a href="?view=list&worker={{ selected_worker|default:'' }}&team={{ selected_team|default:'' }}&project={{ selected_project|default:'' }}&payment_status={{ selected_payment_status|default:'' }}" class="btn btn-outline-secondary bg-white {% if view_mode != 'calendar' %}active fw-bold{% endif %}">
                      <i class="fas fa-list"></i> List
                  </a>
                  <a href="?view=calendar&worker={{ selected_worker|default:'' }}&team={{ selected_team|default:'' }}&project={{ selected_project|default:'' }}&payment_status={{ selected_payment_status|default:'' }}" class="btn btn-outline-secondary bg-white {% if view_mode == 'calendar' %}active fw-bold{% endif %}">
                      <i class="fas fa-calendar-alt"></i> Calendar
                  </a>
                </div>

                <a href="{% url 'export_work_log_csv' %}?{{ request.GET.urlencode }}" class="btn btn-outline-secondary shadow-sm border-0 bg-white text-dark">
                    <i class="fas fa-download me-1"></i> Export CSV
                </a>
                <a href="{% url 'log_attendance' %}" class="btn btn-accent shadow-sm">
                    + New Entry
                </a>
            </div>
        </div>

        <!-- Filter Card -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-4">
                <form method="get" class="row g-3">
                    <input type="hidden" name="view" value="{{ view_mode }}">
                    {% if view_mode == 'calendar' %}
                        <input type="hidden" name="month" value="{{ curr_month }}">
                        <input type="hidden" name="year" value="{{ curr_year }}">
                    {% endif %}
                    
                    <div class="col-md-3">
                        <label class="form-label small text-muted text-uppercase fw-bold">Worker</label>
                        <select name="worker" class="form-select">
                            <option value="">All Workers</option>
                            {% for w in workers %}
                            <option value="{{ w.id }}" {% if selected_worker == w.id %}selected{% endif %}>{{ w.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted text-uppercase fw-bold">Team</label>
                        <select name="team" class="form-select">
                            <option value="">All Teams</option>
                            {% for t in teams %}
                            <option value="{{ t.id }}" {% if selected_team == t.id %}selected{% endif %}>{{ t.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small text-muted text-uppercase fw-bold">Project</label>
                        <select name="project" class="form-select">
                            <option value="">All Projects</option>
                            {% for p in projects %}
                            <option value="{{ p.id }}" {% if selected_project == p.id %}selected{% endif %}>{{ p.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    {% if is_admin_user %}
                    <div class="col-md-2">
                        <label class="form-label small text-muted text-uppercase fw-bold">Payment</label>
                        <select name="payment_status" class="form-select">
                            <option value="all" {% if selected_payment_status == 'all' %}selected{% endif %}>All Status</option>
                            <option value="paid" {% if selected_payment_status == 'paid' %}selected{% endif %}>Paid</option>
                            <option value="unpaid" {% if selected_payment_status == 'unpaid' %}selected{% endif %}>Unpaid</option>
                        </select>
                    </div>
                    {% endif %}
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">Filter</button>
                    </div>
                </form>
                
                <hr class="my-4 opacity-10">

                <div class="d-flex justify-content-between align-items-end">
                    <div>
                        {% if selected_worker or selected_team or selected_project or selected_payment_status and selected_payment_status != 'all' %}
                        <a href="{% url 'work_log_list' %}?view={{ view_mode }}" class="btn btn-sm btn-link text-decoration-none text-muted p-0">
                            <i class="fas fa-times-circle"></i> Clear all filters
                        </a>
                        {% else %}
                        <small class="text-muted">Showing all records</small>
                        {% endif %}
                    </div>
                    {% if is_admin_user %}
                    <div class="text-end">
                        <small class="text-uppercase text-muted fw-bold ls-1 d-block mb-1">Total Value</small>
                        <span class="h2 fw-bold text-primary mb-0">R {{ total_amount|floatformat:2 }}</span>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <!-- Overtime Chart (Admin Only) -->
        {% if is_admin_user %}
        <div class="card border-0 shadow-sm mb-4" id="otChartContainer" style="display: none;">
            <div class="card-header bg-white fw-bold small text-uppercase text-muted">Overtime History (Monthly)</div>
            <div class="card-body">
                <div style="height: 200px;">
                    <canvas id="otHistoryChart"></canvas>
                </div>
                <p class="text-muted small mt-2 mb-0 fst-italic text-center">
                    Showing overtime costs for the current filters.
                </p>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<div class="container mb-5 mt-n4">
    {% if view_mode == 'calendar' %}
    <!-- CALENDAR VIEW -->
    <div class="card shadow-sm border-0">
        <div class="card-header bg-white py-3 border-bottom">
            <div class="d-flex justify-content-between align-items-center">
                <h3 class="mb-0 fw-bold text-dark">{{ month_name }} {{ curr_year }}</h3>
                <div class="btn-group shadow-sm">
                    <a href="?view=calendar&month={{ prev_month }}&year={{ prev_year }}&worker={{ selected_worker|default:'' }}&team={{ selected_team|default:'' }}&project={{ selected_project|default:'' }}&payment_status={{ selected_payment_status|default:'' }}" class="btn btn-light border bg-white">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <a href="?view=calendar&month={{ next_month }}&year={{ next_year }}&worker={{ selected_worker|default:'' }}&team={{ selected_team|default:'' }}&project={{ selected_project|default:'' }}&payment_status={{ selected_payment_status|default:'' }}" class="btn btn-light border bg-white">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered mb-0 calendar-table" style="table-layout: fixed;">
                    <thead class="table-light text-center text-uppercase text-muted small">
                        <tr>
                            <th style="width: 14.28%">Mon</th>
                            <th style="width: 14.28%">Tue</th>
                            <th style="width: 14.28%">Wed</th>
                            <th style="width: 14.28%">Thu</th>
                            <th style="width: 14.28%">Fri</th>
                            <th style="width: 14.28%">Sat</th>
                            <th style="width: 14.28%">Sun</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for week in calendar_weeks %}
                        <tr>
                            {% for day_info in week %}
                                <td class="cal-day {% if day_info.records %}cal-day--has-logs{% endif %} {% if not day_info.is_current_month %}bg-light text-muted bg-opacity-10{% endif %}"
                                    data-date="{{ day_info.date|date:'Y-m-d' }}"
                                    style="height: 140px; vertical-align: top; padding: 10px;">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <span class="fw-bold {% if day_info.date == current_time.date %}text-primary bg-primary bg-opacity-10 px-2 rounded-circle{% endif %}">{{ day_info.day }}</span>
                                        {% if day_info.records %}
                                            <span class="badge bg-secondary opacity-50">{{ day_info.records|length }}</span>
                                        {% endif %}
                                    </div>
                                    <div class="calendar-events" style="max-height: 100px; overflow-y: auto;">
                                        {% for record in day_info.records %}
                                            <div class="mb-1 p-1 rounded border small bg-white shadow-sm" style="font-size: 0.75rem; line-height: 1.2; border-left: 3px solid {% if record.type == 'ADJ' %}#dc3545{% else %}var(--bs-primary){% endif %} !important;">
                                                <div class="fw-bold text-truncate">{{ record.project_name }}</div>
                                                {% if record.type == 'WORK' and record.team_name %}
                                                    <div class="text-muted small text-truncate" style="font-size: 0.7rem;">
                                                        <i class="fas fa-users me-1"></i>{{ record.team_name }}
                                                    </div>
                                                {% endif %}
                                                <div class="text-muted text-truncate">
                                                    {% if selected_worker %}
                                                        {{ record.workers.0.name }}
                                                    {% elif record.workers|length == 1 %}
                                                         {{ record.workers.0.name }}
                                                    {% else %}
                                                        {{ record.workers|length }} workers
                                                    {% endif %}
                                                </div>
                                            </div>
                                        {% endfor %}
                                    </div>
                                </td>
                            {% endfor %}
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Day Detail Panel (shown on click) -->
    <div id="dayDetailPanel" class="card shadow-sm border-0 mt-3" style="display: none;">
        <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
            <h5 class="mb-0 fw-bold text-dark" id="dayDetailTitle">-</h5>
            <button type="button" class="btn-close" id="dayDetailClose" aria-label="Close"></button>
        </div>
        <div class="card-body p-0" id="dayDetailBody">
        </div>
    </div>
    
    {% else %}
    <!-- LIST VIEW -->
    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            {% if records %}
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4">Date</th>
                            <th>Description / Project</th>
                            <th>Worker(s)</th>
                            {% if is_admin_user %}<th>Amount</th>{% endif %}
                            {% if is_admin_user %}<th>Status / Payslip</th>{% endif %}
                            <th>Supervisor</th>
                            <th class="pe-4 text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for record in records %}
                        <tr>
                            <td class="ps-4">
                                <span class="fw-bold">{{ record.date|date:"D, d M Y" }}</span>
                            </td>
                            <td>
                                {% if record.type == 'WORK' %}
                                    <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25 px-2 py-1">
                                        {{ record.project_name }}
                                    </span>
                                    {% if record.team_name %}
                                        <small class="text-muted ms-1"><i class="fas fa-users"></i> {{ record.team_name }}</small>
                                    {% endif %}
                                {% else %}
                                    <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 px-2 py-1">
                                        {{ record.project_name }}
                                    </span>
                                {% endif %}
                            </td>
                            <td>
                                {% if selected_worker %}
                                    <span class="text-primary fw-medium">
                                        {% for w in record.workers %}
                                            {% if w.id == selected_worker %}
                                                {{ w.name }}
                                            {% endif %}
                                        {% endfor %}
                                    </span>
                                    {% if record.workers|length > 1 %}
                                        <small class="text-muted">(+{{ record.workers|length|add:"-1" }} others)</small>
                                    {% endif %}
                                {% else %}
                                    <div class="d-flex flex-wrap gap-1">
                                        {% for w in record.workers|slice:":3" %}
                                            <span class="small bg-light px-2 py-1 rounded border">{{ w.name|truncatechars:12 }}</span>
                                        {% endfor %}
                                        {% if record.workers|length > 3 %}
                                            <span class="small text-muted align-self-center ms-1">+{{ record.workers|length|add:"-3" }}</span>
                                        {% endif %}
                                    </div>
                                {% endif %}
                            </td>
                            {% if is_admin_user %}
                            <td>
                                <span class="fw-bold font-monospace {% if record.amount < 0 %}text-danger{% else %}text-dark{% endif %}">
                                    R {{ record.amount|floatformat:2 }}
                                </span>
                            </td>
                            <td>
                                {% if record.paid_record %}
                                    <a href="{% url 'payslip_detail' record.paid_record.id %}" class="text-decoration-none">
                                        <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25">
                                            <i class="fas fa-check-circle"></i> Paid (Slip #{{ record.paid_record.id }})
                                        </span>
                                    </a>
                                {% else %}
                                    <span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25">
                                        Pending
                                    </span>
                                {% endif %}
                            </td>
                            {% endif %}
                            <td>
                                <small class="text-muted">{{ record.supervisor }}</small>
                            </td>
                            <td class="pe-4 text-end">
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-light text-dark border-0" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-ellipsis-v"></i>
                                    </button>
                                    <ul class="dropdown-content dropdown-menu dropdown-menu-end">
                                        {% if record.type == 'WORK' %}
                                            <li><a class="dropdown-item" href="/admin/core/worklog/{{ record.obj.id }}/change/">Edit Entry</a></li>
                                        {% else %}
                                            <li><a class="dropdown-item" href="/admin/core/payrolladjustment/{{ record.obj.id }}/change/">Edit Adjustment</a></li>
                                        {% endif %}
                                        
                                        {% if record.notes %}
                                        <li><hr class="dropdown-divider"></li>
                                        <li class="px-3 py-1"><small class="text-muted">Note: {{ record.notes }}</small></li>
                                        {% endif %}
                                    </ul>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                    {% if is_admin_user %}
                    <tfoot class="table-light border-top-2">
                        <tr>
                            <td colspan="3" class="text-end fw-bold ps-4">Total:</td>
                            <td class="fw-bold font-monospace text-dark bg-warning bg-opacity-10">R {{ total_amount|floatformat:2 }}</td>
                            <td colspan="3"></td>
                        </tr>
                    </tfoot>
                    {% endif %}
                </table>
            </div>
            {% else %}
            <div class="text-center py-5">
                <i class="fas fa-search display-1 text-muted opacity-25 mb-3 d-block"></i>
                <h4 class="text-muted">No records found matching filters.</h4>
                <p class="text-muted mb-4">Try adjusting your filters or record a new entry.</p>
                <a href="{% url 'log_attendance' %}" class="btn btn-primary">Log Attendance</a>
            </div>
            {% endif %}
        </div>
    </div>
    {% endif %}
</div>

<style>
    .mt-n4 { margin-top: -0.75rem !important; }
    @media (min-width: 768px) {
        .mt-n4 { margin-top: -1.5rem !important; }
    }
    .bg-accent { background-color: var(--bs-accent); }
    .btn-accent { background-color: #ffde59; color: #000; border: none; font-weight: 600; }
    .btn-accent:hover { background-color: #e6c850; }

    /* Calendar Scrollbar custom */
    .calendar-events::-webkit-scrollbar {
        width: 4px;
    }
    .calendar-events::-webkit-scrollbar-thumb {
        background-color: #ccc;
        border-radius: 4px;
    }

    /* Clickable calendar cells */
    .cal-day--has-logs { cursor: pointer; transition: background-color 0.15s; }
    .cal-day--has-logs:hover { background-color: rgba(13, 110, 253, 0.04) !important; }
    .cal-day--selected { background-color: rgba(13, 110, 253, 0.08) !important; box-shadow: inset 0 0 0 2px var(--bs-primary); }

    /* Calendar mobile: compact cells */
    @media (max-width: 767.98px) {
        .calendar-table td { height: 80px !important; padding: 4px !important; }
        .calendar-table .calendar-events { max-height: 50px !important; }
        .calendar-table .calendar-events .mb-1 { font-size: 0.65rem !important; padding: 2px !important; }
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    {% if is_admin_user %}
    const otLabels = {{ ot_chart_labels|safe|default:"[]" }};
    const otData = {{ ot_chart_data|safe|default:"[]" }};
    const chartContainer = document.getElementById('otChartContainer');
    
    // Only show chart if we have data and more than 0 entries
    if (otData.length > 0 && otData.some(val => val > 0)) {
        chartContainer.style.display = 'block';
        
        const ctx = document.getElementById('otHistoryChart');
        if (ctx) {
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: otLabels,
                    datasets: [{
                        label: 'Overtime Paid (R)',
                        data: otData,
                        backgroundColor: '#f59e0b',
                        borderRadius: 4,
                        barThickness: 40
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { callback: v => 'R ' + v.toLocaleString() }
                        },
                        x: {
                            grid: { display: false }
                        }
                    }
                }
            });
        }
    }
    {% endif %}

    {% if view_mode == 'calendar' %}
    const detailData = {{ calendar_detail_json|safe }};
    const panel = document.getElementById('dayDetailPanel');
    const panelTitle = document.getElementById('dayDetailTitle');
    const panelBody = document.getElementById('dayDetailBody');
    const panelClose = document.getElementById('dayDetailClose');

    let selectedDates = new Set();
    const dateOpts = { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' };

    function renderPanel() {
        // Sort selected dates chronologically
        const sorted = Array.from(selectedDates).sort();
        if (!sorted.length) {
            panel.style.display = 'none';
            return;
        }

        // Build title
        if (sorted.length === 1) {
            const d = new Date(sorted[0] + 'T00:00:00');
            const longOpts = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
            panelTitle.textContent = d.toLocaleDateString('en-ZA', longOpts);
        } else {
            panelTitle.textContent = sorted.length + ' dates selected';
        }

        // Build detail HTML with date grouping for multi-select
        let html = '<div class="table-responsive"><table class="table table-hover align-middle mb-0">';
        html += '<thead class="table-light"><tr>';
        if (sorted.length > 1) html += '<th class="ps-4">Date</th>';
        html += '<th class="' + (sorted.length === 1 ? 'ps-4' : '') + '">Description / Project</th><th>Workers</th><th>Amount</th><th>Supervisor</th><th>Notes</th></tr></thead><tbody>';

        sorted.forEach(function(dateStr) {
            const records = detailData[dateStr] || [];
            const d = new Date(dateStr + 'T00:00:00');
            const dateLabel = d.toLocaleDateString('en-ZA', dateOpts);

            records.forEach(function(rec, idx) {
                const teams = rec.teams.length ? rec.teams.join(', ') : '';
                
                let desc = rec.project;
                if(rec.type === 'ADJ') {
                    desc = '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25">' + rec.project + '</span>';
                } else {
                    desc = '<span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25">' + rec.project + '</span>';
                    if (teams) desc += ' <small class="text-muted ms-1">' + teams + '</small>';
                }

                const workers = rec.workers.map(function(w) {
                    return '<span class="small bg-light px-2 py-1 rounded border d-inline-block mb-1">' + w + '</span>';
                }).join(' ');
                
                const notes = rec.notes ? '<small class="text-muted">' + rec.notes + '</small>' : '<span class="text-muted">-</span>';
                const amount = rec.amount ? 'R ' + rec.amount.toFixed(2) : '-';

                html += '<tr>';
                if (sorted.length > 1) {
                    if (idx === 0) {
                        html += '<td class="ps-4 fw-bold" rowspan="' + records.length + '">' + dateLabel + '</td>';
                    }
                }
                html += '<td class="' + (sorted.length === 1 ? 'ps-4 ' : '') + '">' + desc + '</td>';
                html += '<td>' + workers + '</td>';
                html += '<td class="font-monospace fw-bold">' + amount + '</td>';
                html += '<td><small class="text-muted">' + rec.supervisor + '</small></td>';
                html += '<td>' + notes + '</td>';
                html += '</tr>';
            });
        });

        html += '</tbody></table></div>';
        panelBody.innerHTML = html;
        panel.style.display = 'block';
        panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    document.querySelectorAll('.cal-day--has-logs').forEach(function(cell) {
        cell.addEventListener('click', function(e) {
            const dateStr = this.dataset.date;
            const records = detailData[dateStr];
            if (!records || !records.length) return;

            if (e.shiftKey) {
                // Shift+click: toggle this date in multi-selection
                if (selectedDates.has(dateStr)) {
                    selectedDates.delete(dateStr);
                    this.classList.remove('cal-day--selected');
                } else {
                    selectedDates.add(dateStr);
                    this.classList.add('cal-day--selected');
                }
            } else {
                // Normal click: single-select (clear others)
                selectedDates.clear();
                document.querySelectorAll('.cal-day--selected').forEach(function(el) {
                    el.classList.remove('cal-day--selected');
                });
                selectedDates.add(dateStr);
                this.classList.add('cal-day--selected');
            }

            renderPanel();
        });
    });

    panelClose.addEventListener('click', function() {
        selectedDates.clear();
        panel.style.display = 'none';
        document.querySelectorAll('.cal-day--selected').forEach(function(el) {
            el.classList.remove('cal-day--selected');
        });
    });
    {% endif %}
});
</script>
{% endblock %}