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

{% block title %}Log Daily Attendance | LabourFlow{% endblock %}

{% block content %}
<div class="dashboard-header">
    <div class="container">
        <h1 class="display-5 mb-2">Log Daily Attendance</h1>
        <p class="lead opacity-75">Record work for projects and labourers.</p>
    </div>
</div>

<div class="container mb-5 mt-n4">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="card p-4 shadow-sm">
                <form method="post" id="workLogForm">
                    {% csrf_token %}
                    
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Start Date</label>
                            {{ form.date }}
                            {% if form.date.errors %}
                                <div class="text-danger mt-1 small">{{ form.date.errors }}</div>
                            {% endif %}
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">End Date (Optional)</label>
                            {{ form.end_date }}
                            <div class="mt-2">
                                <div class="form-check form-check-inline">
                                    {{ form.include_saturday }}
                                    <label class="form-check-label small" for="{{ form.include_saturday.id_for_label }}">Sat</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    {{ form.include_sunday }}
                                    <label class="form-check-label small" for="{{ form.include_sunday.id_for_label }}">Sun</label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold">Project</label>
                            {{ form.project }}
                            {% if form.project.errors %}
                                <div class="text-danger mt-1 small">{{ form.project.errors }}</div>
                            {% endif %}
                        </div>
                         <div class="col-md-3">
                            <label class="form-label fw-bold">Team (Optional)</label>
                            {{ form.team }}
                            {% if form.team.errors %}
                                <div class="text-danger mt-1 small">{{ form.team.errors }}</div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <label class="form-label fw-bold mb-0">Select Labourers</label>
                            <a href="{% url 'manage_resources' %}" class="small text-decoration-none text-primary">Manage Resources</a>
                        </div>
                        <div class="row">
                            {% for checkbox in form.workers %}
                                <div class="col-md-6 col-lg-4 mb-2">
                                    <div class="form-check p-3 border rounded-3 hover-shadow transition-all">
                                        {{ checkbox.tag }}
                                        <label class="form-check-label ms-2" for="{{ checkbox.id_for_label }}">
                                            {{ checkbox.choice_label }}
                                        </label>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                        {% if form.workers.errors %}
                            <div class="text-danger mt-1 small">{{ form.workers.errors }}</div>
                        {% endif %}
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">Notes / Comments</label>
                        {{ form.notes }}
                        {% if form.notes.errors %}
                            <div class="text-danger mt-1 small">{{ form.notes.errors }}</div>
                        {% endif %}
                    </div>

                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <a href="{% url 'home' %}" class="btn btn-light px-4">Cancel</a>
                        <button type="submit" class="btn btn-primary px-5">Save Work Log</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% if is_conflict %}
<!-- Conflict Resolution Modal -->
<div class="modal fade" id="conflictModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="conflictModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-warning text-dark">
        <h5 class="modal-title fw-bold" id="conflictModalLabel">
            Duplicate Logs Detected
        </h5>
      </div>
      <div class="modal-body">
        <p class="fw-bold">The following duplicate entries were found:</p>
        <div class="card bg-light mb-3" style="max-height: 200px; overflow-y: auto;">
            <ul class="list-group list-group-flush">
                {% for conflict in conflicting_workers %}
                    <li class="list-group-item bg-transparent">{{ conflict.name }}</li>
                {% endfor %}
            </ul>
        </div>
        <p>How would you like to proceed?</p>
        <div class="alert alert-info small mb-0">
            <strong>Skip:</strong> Log only the new entries. Existing logs remain unchanged.<br>
            <strong>Overwrite:</strong> Update existing logs for these dates with the new project/team selection.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" onclick="submitConflict('skip')">Skip Duplicates</button>
        <button type="button" class="btn btn-primary" onclick="submitConflict('overwrite')">Overwrite Existing</button>
      </div>
    </div>
  </div>
</div>
{% endif %}

<style>
    .hover-shadow:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        border-color: #0d6efd !important;
    }
    .transition-all {
        transition: all 0.2s ease-in-out;
    }
    .mt-n4 {
        margin-top: -3rem !important;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const teamSelect = document.getElementById('{{ form.team.id_for_label }}');
        const teamWorkersMap = {{ team_workers_json|safe }};
        
        if (teamSelect) {
            teamSelect.addEventListener('change', function() {
                const teamId = this.value;
                if (teamId && teamWorkersMap[teamId]) {
                    const workerIds = teamWorkersMap[teamId];
                    // Uncheck all first? No, maybe append. Let's append as per common expectations unless explicit clear needed.
                    // Actually, if I change team, I probably expect to select THAT team's workers.
                    // Let's clear and select.
                    // But maybe I want to mix teams.
                    // User didn't specify. Previous logic was: select workers belonging to team.
                    // Let's stick to "select", don't uncheck others.
                    
                    workerIds.forEach(function(id) {
                         const checkbox = document.querySelector(`input[name="workers"][value="${id}"]`);
                         if (checkbox) {
                             checkbox.checked = true;
                         }
                    });
                }
            });
        }

        // Show conflict modal if it exists
        const conflictModalEl = document.getElementById('conflictModal');
        if (conflictModalEl) {
            var myModal = new bootstrap.Modal(conflictModalEl);
            myModal.show();
        }
    });

    function submitConflict(action) {
        const form = document.getElementById('workLogForm');
        // Check if input already exists
        let input = form.querySelector('input[name="conflict_action"]');
        if (!input) {
            input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'conflict_action';
            form.appendChild(input);
        }
        input.value = action;
        form.submit();
    }
</script>
{% endblock %}