{% extends "shared/frontend/base.html" %}

{% block title %}Worklog Godkendelse - BMC Hub{% endblock %}

{% block extra_css %}
    <style>
        .worklog-table {
            background: var(--bg-card);
        }

        .worklog-table th {
            font-weight: 600;
            color: var(--text-secondary);
            border-bottom: 2px solid var(--accent-light);
            padding: 1rem 0.75rem;
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .worklog-table td {
            padding: 1rem 0.75rem;
            vertical-align: middle;
            border-bottom: 1px solid var(--accent-light);
        }

        .worklog-row {
            transition: background-color 0.2s;
        }

        .worklog-row:hover {
            background-color: var(--accent-light);
        }

        .badge {
            padding: 0.4rem 0.8rem;
            font-weight: 500;
            border-radius: 6px;
            font-size: 0.75rem;
        }

        .badge-invoice {
            background-color: var(--accent-light);
            color: var(--accent);
        }

        .badge-prepaid {
            background-color: #d4edda;
            color: #155724;
        }

        .badge-support {
            background-color: #cce5ff;
            color: #004085;
        }

        .badge-development {
            background-color: #f8d7da;
            color: #721c24;
        }

        .btn-approve {
            background-color: var(--success);
            color: white;
            border: none;
            padding: 0.4rem 1rem;
            border-radius: 6px;
            font-size: 0.85rem;
            transition: all 0.2s;
        }

        .btn-approve:hover {
            background-color: #218838;
            transform: translateY(-1px);
        }

        .btn-reject {
            background-color: var(--danger);
            color: white;
            border: none;
            padding: 0.4rem 1rem;
            border-radius: 6px;
            font-size: 0.85rem;
            transition: all 0.2s;
        }

        .btn-reject:hover {
            background-color: #c82333;
            transform: translateY(-1px);
        }

        .filter-bar {
            background: var(--bg-card);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
        }

        .hours-display {
            font-weight: 700;
            color: var(--accent);
            font-size: 1.1rem;
        }

        .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }

        .ticket-number {
            font-family: 'Monaco', 'Courier New', monospace;
            background: var(--accent-light);
            padding: 0.2rem 0.5rem;
            border-radius: 4px;
            font-size: 0.85rem;
            color: var(--accent);
        }

        .customer-name {
            font-weight: 600;
            color: var(--text-primary);
        }

        .work-description {
            color: var(--text-secondary);
            font-size: 0.9rem;
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .btn-group-actions {
            white-space: nowrap;
        }
    </style>
{% endblock %}

{% block content %}
        <!-- Page Header -->
        <div class="row mb-4 align-items-center">
            <div class="col">
                <h1 class="mb-2">
                    <i class="bi bi-clock-history"></i> Worklog Godkendelse
                </h1>
                <p class="text-muted">Godkend eller afvis enkelt-entries fra draft worklog</p>
            </div>
            <div class="col-auto">
                 <a href="/timetracking/wizard2{% if selected_customer_id %}?hub_id={{ selected_customer_id }}{% endif %}" 
                    class="btn btn-primary btn-lg shadow-sm">
                    <i class="bi bi-magic me-2"></i> Åbn Billing Wizard
                 </a>
            </div>
        </div>

        <!-- Statistics Row -->
        <div class="row stats-row">
            <div class="col-md-4">
                <div class="card stat-card p-4">
                    <h3>{{ total_entries }}</h3>
                    <p>Entries til godkendelse</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card p-4">
                    <h3>{{ "%.2f"|format(total_hours) }}t</h3>
                    <p>Total timer</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card p-4">
                    <h3>{{ "%.2f"|format(total_billable_hours) }}t</h3>
                    <p>Fakturerbare timer</p>
                </div>
            </div>
        </div>

        <!-- Filter Bar -->
        <div class="filter-bar">
            <form method="get" action="/ticket/worklog/review" class="row g-3">
                <div class="col-md-4">
                    <label for="customer_id" class="form-label">Filtrer efter kunde:</label>
                    <select name="customer_id" id="customer_id" class="form-select" onchange="this.form.submit()">
                        <option value="">Alle kunder</option>
                        {% for customer in customers %}
                        <option value="{{ customer.id }}" {% if customer.id == selected_customer_id %}selected{% endif %}>
                            {{ customer.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="status" class="form-label">Status:</label>
                    <select name="status" id="status" class="form-select" onchange="this.form.submit()">
                        <option value="draft" {% if selected_status == 'draft' %}selected{% endif %}>Draft</option>
                        <option value="billable" {% if selected_status == 'billable' %}selected{% endif %}>Billable</option>
                        <option value="rejected" {% if selected_status == 'rejected' %}selected{% endif %}>Rejected</option>
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-funnel"></i> Filtrer
                    </button>
                    <a href="/ticket/worklog/review" class="btn btn-outline-secondary ms-2">
                        <i class="bi bi-x-circle"></i> Ryd filtre
                    </a>
                </div>
            </form>
        </div>

        <!-- Worklog Table -->
        {% if worklogs %}
        <div class="card">
            <div class="table-responsive">
                <table class="table worklog-table mb-0">
                    <thead>
                        <tr>
                            <th>Ticket</th>
                            <th>Kunde</th>
                            <th>Dato</th>
                            <th>Timer</th>
                            <th>Type</th>
                            <th>Fakturering</th>
                            <th>Beskrivelse</th>
                            <th>Medarbejder</th>
                            <th style="text-align: right;">Handlinger</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for worklog in worklogs %}
                        <tr class="worklog-row {% if worklog.billing_method == 'unknown' %}table-warning{% endif %}">
                            <td>
                                <span class="ticket-number">{{ worklog.ticket_number }}</span>
                                <br>
                                <small class="text-muted">{{ worklog.ticket_subject[:30] }}...</small>
                            </td>
                            <td>
                                {% if worklog.customer_name %}
                                <span class="customer-name">{{ worklog.customer_name }}</span>
                                {% else %}
                                <span class="text-muted">-</span>
                                {% endif %}
                            </td>
                            <td>
                                {{ worklog.work_date.strftime('%d-%m-%Y') if worklog.work_date else '-' }}
                            </td>
                            <td>
                                <span class="hours-display">{{ "%.2f"|format(worklog.hours) }}t</span>
                            </td>
                            <td>
                                {% if worklog.work_type == 'support' %}
                                <span class="badge badge-support">Support</span>
                                {% elif worklog.work_type == 'development' %}
                                <span class="badge badge-development">Udvikling</span>
                                {% else %}
                                <span class="badge">{{ worklog.work_type }}</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if worklog.billing_method == 'invoice' %}
                                <span class="badge badge-invoice">
                                    <i class="bi bi-file-earmark-text"></i> Faktura
                                </span>
                                {% elif worklog.billing_method == 'prepaid' %}
                                <span class="badge badge-prepaid">
                                    <i class="bi bi-credit-card"></i> Klippekort
                                </span>
                                {% if worklog.card_number %}
                                <br><small class="text-muted">{{ worklog.card_number }}</small>
                                {% endif %}
                                {% elif worklog.billing_method == 'unknown' %}
                                <span class="badge bg-warning text-dark">
                                    <i class="bi bi-question-circle"></i> Ved ikke
                                </span>
                                {% else %}
                                <span class="badge bg-secondary">{{ worklog.billing_method }}</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="work-description" title="{{ worklog.description or '-' }}">
                                    {{ worklog.description or '-' }}
                                </div>
                            </td>
                            <td>
                                {{ worklog.user_name or 'N/A' }}
                            </td>
                            <td>
                                {% if worklog.status == 'draft' %}
                                <div class="btn-group-actions">
                                    <form method="post" action="/ticket/worklog/{{ worklog.id }}/approve" style="display: inline;">
                                        <input type="hidden" name="redirect_to" value="{{ request.url }}">
                                        <button type="submit" class="btn btn-approve btn-sm" title="Godkend">
                                            <i class="bi bi-check-circle"></i>
                                        </button>
                                    </form>
                                    <button 
                                        type="button" 
                                        class="btn btn-outline-primary btn-sm ms-1"
                                        title="Rediger"
                                        data-id="{{ worklog.id }}"
                                        data-customer-id="{{ worklog.customer_id }}"
                                        data-hours="{{ worklog.hours }}"
                                        data-type="{{ worklog.work_type }}"
                                        data-billing="{{ worklog.billing_method }}"
                                        data-prepaid-card-id="{{ worklog.prepaid_card_id or '' }}"
                                        data-desc="{{ worklog.description }}"
                                        data-internal="{{ 'true' if worklog.is_internal else 'false' }}"
                                        onclick="openEditModal(this)">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button 
                                        type="button" 
                                        class="btn btn-reject btn-sm ms-1" 
                                        title="Afvis"
                                        onclick="rejectWorklog({{ worklog.id }}, '{{ request.url }}')">
                                        <i class="bi bi-x-circle"></i>
                                    </button>
                                </div>
                                {% else %}
                                <span class="badge">{{ worklog.status }}</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        {% else %}
        <div class="card">
            <div class="empty-state">
                <i class="bi bi-inbox"></i>
                <h3>Ingen worklog entries</h3>
                <p>Der er ingen entries med status "{{ selected_status }}" {% if selected_customer_id %}for denne kunde{% endif %}.</p>
            </div>
        </div>
        {% endif %}

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content" style="background: var(--bg-card); color: var(--text-primary);">
                <div class="modal-header" style="border-bottom: 1px solid var(--accent-light);">
                    <h5 class="modal-title">Rediger Worklog Entry</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="editId">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label">Tid brugt *</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="editHours" min="0" placeholder="tt" step="1" 
                                       style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);">
                                <span class="input-group-text" style="background: var(--accent-light); border-color: var(--accent-light); color: var(--text-primary);">:</span>
                                <input type="number" class="form-control" id="editMinutes" min="0" max="59" placeholder="mm" step="1" 
                                       style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);">
                            </div>
                            <div class="form-text text-end" id="editTotalCalc">Total: 0.00 timer</div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Type</label>
                            <select class="form-select" id="editType" style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);">
                                <option value="support">Support</option>
                                <option value="troubleshooting">Fejlsøgning</option>
                                <option value="development">Udvikling</option>
                                <option value="on_site">Kørsel / On-site</option>
                                <option value="meeting">Møde</option>
                                <option value="other">Andet</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Afregning</label>
                            <select class="form-select" id="editBilling" style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);" onchange="handleBillingMethodChange()">
                                <option value="invoice">Faktura</option>
                                <option value="prepaid_card">Klippekort</option>
                                <option value="internal">Internt / Ingen faktura</option>
                                <option value="warranty">Garanti / Reklamation</option>
                                <option value="unknown">❓ Ved ikke</option>
                            </select>
                        </div>
                        <div class="col-12" id="prepaidCardSelectContainer" style="display: none;">
                            <label class="form-label">Vælg Klippekort *</label>
                            <select class="form-select" id="editPrepaidCard" style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);">
                                <option value="">-- Henter klippekort --</option>
                            </select>
                            <div class="form-text">Vælg hvilket klippekort der skal bruges</div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Beskrivelse</label>
                            <textarea class="form-control" id="editDesc" rows="3" 
                                      style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);"></textarea>
                        </div>
                        <div class="col-12">
                             <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="editInternal">
                                <label class="form-check-label" for="editInternal">Skjul for kunde (Intern registrering)</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer" style="border-top: 1px solid var(--accent-light);">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuller</button>
                    <button type="button" class="btn btn-primary" onclick="saveWorklog()">Gem Ændringer</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content" style="background: var(--bg-card); color: var(--text-primary);">
                <div class="modal-header" style="border-bottom: 1px solid var(--accent-light);">
                    <h5 class="modal-title">Afvis Worklog Entry</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="rejectForm" method="post">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="rejectReason" class="form-label">Årsag til afvisning (valgfrit):</label>
                            <textarea 
                                class="form-control" 
                                id="rejectReason" 
                                name="reason" 
                                rows="3"
                                placeholder="Forklar hvorfor denne entry afvises..."
                                style="background: var(--bg-body); color: var(--text-primary); border-color: var(--accent-light);"></textarea>
                        </div>
                        <input type="hidden" name="redirect_to" id="rejectRedirectTo">
                    </div>
                    <div class="modal-footer" style="border-top: 1px solid var(--accent-light);">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuller</button>
                        <button type="submit" class="btn btn-reject">
                            <i class="bi bi-x-circle"></i> Afvis Entry
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_js %}
    <script>
        // Reject worklog with modal
        function rejectWorklog(worklogId, redirectUrl) {
            const form = document.getElementById('rejectForm');
            form.action = `/ticket/worklog/${worklogId}/reject`;
            document.getElementById('rejectRedirectTo').value = redirectUrl;
            
            const modal = new bootstrap.Modal(document.getElementById('rejectModal'));
            modal.show();
        }

        // Auto-refresh indicator (optional)
        let lastRefresh = Date.now();
        setInterval(() => {
            const elapsed = Math.floor((Date.now() - lastRefresh) / 1000);
            if (elapsed > 300) { // 5 minutes
                const badge = document.createElement('span');
                badge.className = 'badge bg-warning position-fixed';
                badge.style.bottom = '20px';
                badge.style.right = '20px';
                badge.style.cursor = 'pointer';
                badge.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Opdater siden';
                badge.onclick = () => location.reload();
                document.body.appendChild(badge);
            }
        }, 60000);

        // ==========================================
        // EDIT FUNCTIONALITY
        // ==========================================
        async function openEditModal(btn) {
            const id = btn.getAttribute('data-id');
            const customerId = btn.getAttribute('data-customer-id');
            const hoursDec = parseFloat(btn.getAttribute('data-hours'));
            const type = btn.getAttribute('data-type');
            const billing = btn.getAttribute('data-billing');
            const prepaidCardId = btn.getAttribute('data-prepaid-card-id');
            const desc = btn.getAttribute('data-desc');
            const isInternal = btn.getAttribute('data-internal') === 'true';

            document.getElementById('editId').value = id;
            // Store customer_id for later use
            window._editCustomerId = customerId;
            window._editPrepaidCardId = prepaidCardId;
            
            // Decimal to HH:MM logic
            const h = Math.floor(hoursDec);
            const m = Math.round((hoursDec - h) * 60);
            
            document.getElementById('editHours').value = h;
            document.getElementById('editMinutes').value = m;
            document.getElementById('editTotalCalc').innerText = `Total: ${hoursDec.toFixed(2)} timer`;
            
            document.getElementById('editType').value = type;
            document.getElementById('editBilling').value = billing;
            document.getElementById('editDesc').value = desc;
            
            // Handle billing method if it was unknown/invalid before, default to invoice
            if(!['invoice','prepaid_card','internal','warranty','unknown'].includes(billing)) {
                 document.getElementById('editBilling').value = 'invoice'; 
            } else {
                 document.getElementById('editBilling').value = billing;
            }
            
            document.getElementById('editInternal').checked = isInternal;

            // Load prepaid cards if billing method is prepaid_card
            if(billing === 'prepaid_card') {
                await loadPrepaidCardsForEdit(customerId, prepaidCardId);
            } else {
                document.getElementById('prepaidCardSelectContainer').style.display = 'none';
            }

            new bootstrap.Modal(document.getElementById('editModal')).show();
        }
        
        async function handleBillingMethodChange() {
            const billing = document.getElementById('editBilling').value;
            const customerId = window._editCustomerId;
            
            if(billing === 'prepaid_card' && customerId) {
                await loadPrepaidCardsForEdit(customerId, null);
            } else {
                document.getElementById('prepaidCardSelectContainer').style.display = 'none';
            }
        }
        
        async function loadPrepaidCardsForEdit(customerId, selectedCardId) {
            const container = document.getElementById('prepaidCardSelectContainer');
            const select = document.getElementById('editPrepaidCard');
            
            try {
                const response = await fetch(`/api/v1/prepaid/prepaid-cards?status=active&customer_id=${customerId}`);
                if(response.ok) {
                    const cards = await response.json();
                    
                    if(cards && cards.length > 0) {
                        const options = cards.map(c => {
                            const remaining = parseFloat(c.remaining_hours).toFixed(2);
                            const expiryText = c.expires_at ? ` • Udløber ${new Date(c.expires_at).toLocaleDateString('da-DK')}` : '';
                            const selected = (selectedCardId && c.id == selectedCardId) ? 'selected' : '';
                            return `<option value="${c.id}" ${selected}>💳 Klippekort #${c.id} (${remaining}t tilbage${expiryText})</option>`;
                        }).join('');
                        
                        select.innerHTML = options;
                        container.style.display = 'block';
                    } else {
                        select.innerHTML = '<option value="">Ingen aktive klippekort fundet</option>';
                        container.style.display = 'block';
                    }
                } else {
                    select.innerHTML = '<option value="">Fejl ved hentning af klippekort</option>';
                    container.style.display = 'block';
                }
            } catch(e) {
                console.error('Failed to load prepaid cards', e);
                select.innerHTML = '<option value="">Fejl ved hentning af klippekort</option>';
                container.style.display = 'block';
            }
        }
        
        const calcEdit = () => {
             const h = parseInt(document.getElementById('editHours').value) || 0;
             const m = parseInt(document.getElementById('editMinutes').value) || 0;
             const total = h + (m / 60);
             document.getElementById('editTotalCalc').innerText = `Total: ${total.toFixed(2)} timer`;
        };
        document.getElementById('editHours').addEventListener('input', calcEdit);
        document.getElementById('editMinutes').addEventListener('input', calcEdit);


        async function saveWorklog() {
            const id = document.getElementById('editId').value;
            const h = parseInt(document.getElementById('editHours').value) || 0;
            const m = parseInt(document.getElementById('editMinutes').value) || 0;
            const totalHours = h + (m / 60);
            const billingMethod = document.getElementById('editBilling').value;
            
            const payload = {
                hours: totalHours,
                work_type: document.getElementById('editType').value,
                billing_method: billingMethod,
                description: document.getElementById('editDesc').value,
                is_internal: document.getElementById('editInternal').checked
            };
            
            // Include prepaid_card_id if billing method is prepaid_card
            if(billingMethod === 'prepaid_card') {
                const prepaidCardId = document.getElementById('editPrepaidCard').value;
                if(prepaidCardId) {
                    payload.prepaid_card_id = parseInt(prepaidCardId);
                } else {
                    alert('⚠️ Vælg venligst et klippekort');
                    return;
                }
            }

            try {
                const response = await fetch(`/api/v1/ticket/worklog/${id}`, {
                    method: 'PATCH',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(payload)
                });
                
                if(!response.ok) {
                    const err = await response.json();
                    throw new Error(err.detail || 'Failed to update');
                }
                
                location.reload();
            } catch(e) {
                alert("Fejl ved opdatering: " + e.message);
            }
        }
    </script>
{% endblock %}
