<?php
// $currentWeek, $pageTitle, $currentPage come from the controller
$week = htmlspecialchars($currentWeek, ENT_QUOTES, 'UTF-8');
?>

<style>
    /* Scoped weekly report styles (mobile-first) */
    .weekly-report-page {
        max-width: 1100px;
        margin: 1.5rem auto;
        padding: 1.5rem;
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
    }

    .weekly-report-page h1,
    .weekly-report-page h2,
    .weekly-report-page h3 {
        margin: 0;
    }

    .weekly-report-page p {
        margin: 0.25rem 0;
    }

    .weekly-report-page .page-header {
        margin-bottom: 1.5rem;
    }

    .weekly-report-page .page-title {
        font-size: 1.6rem;
        font-weight: 600;
        margin-bottom: 0.25rem;
    }

    .weekly-report-page .page-description {
        color: #4b5563;
        font-size: 0.95rem;
    }

    .weekly-report-page .page-actions {
        margin-top: 0.75rem;
    }

    .weekly-report-page .badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.6rem;
        border-radius: 999px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .weekly-report-page .badge-soft-sky {
        background-color: rgba(56, 189, 248, 0.12);
        color: #0369a1;
        border: 1px solid rgba(56, 189, 248, 0.4);
    }

    .weekly-report-page .layout-grid {
        display: grid;
        grid-template-columns: minmax(0, 1fr);
        gap: 1.25rem;
    }

    @media (min-width: 900px) {
        .weekly-report-page .layout-grid.layout-grid-2 {
            grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr);
        }
    }

    .weekly-report-page .card {
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
        border: 1px solid rgba(148, 163, 184, 0.35);
        overflow: hidden;
    }

    .weekly-report-page .card-soft {
        background: rgba(255, 255, 255, 0.7);
        border-style: dashed;
    }

    .weekly-report-page .card-header {
        padding: 0.85rem 1.1rem 0.35rem;
        border-bottom: 1px solid rgba(226, 232, 240, 0.8);
    }

    .weekly-report-page .card-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin-bottom: 0.1rem;
    }

    .weekly-report-page .card-subtitle {
        font-size: 0.85rem;
        color: #6b7280;
    }

    .weekly-report-page .card-body {
        padding: 1rem 1.1rem 1.1rem;
        font-size: 0.9rem;
    }

    .weekly-report-page .card-footer {
        padding: 0.75rem 1.1rem;
        border-top: 1px solid rgba(226, 232, 240, 0.8);
        font-size: 0.8rem;
    }

    .weekly-report-page .form-group {
        margin-bottom: 0.85rem;
    }

    .weekly-report-page .form-label {
        display: block;
        font-size: 0.85rem;
        font-weight: 500;
        margin-bottom: 0.25rem;
    }

    .weekly-report-page .form-control,
    .weekly-report-page select,
    .weekly-report-page textarea {
        width: 100%;
        border-radius: 10px;
        border: 1px solid #cbd5f5;
        padding: 0.45rem 0.6rem;
        font-size: 0.9rem;
        outline: none;
        box-sizing: border-box;
    }

    .weekly-report-page .form-control:focus,
    .weekly-report-page select:focus,
    .weekly-report-page textarea:focus {
        border-color: #6366f1;
        box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.18);
    }

    .weekly-report-page textarea {
        min-height: 170px;
        resize: vertical;
    }

    .weekly-report-page .form-hint {
        font-size: 0.78rem;
        color: #6b7280;
        margin-top: 0.15rem;
    }

    .weekly-report-page .form-footer {
        margin-top: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .weekly-report-page .btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 999px;
        padding: 0.4rem 0.9rem;
        font-size: 0.85rem;
        font-weight: 500;
        border: none;
        cursor: pointer;
    }

    .weekly-report-page .btn-primary {
        background: linear-gradient(135deg, #6366f1, #4f46e5);
        color: #ffffff;
        box-shadow: 0 8px 18px rgba(79, 70, 229, 0.35);
    }

    .weekly-report-page .btn-link {
        background: transparent;
        color: #4f46e5;
        padding: 0;
        box-shadow: none;
    }

    .weekly-report-page .btn-xs {
        font-size: 0.8rem;
    }

    .weekly-report-page .text-muted {
        color: #6b7280;
    }

    .weekly-report-page .history-list {
        font-size: 0.85rem;
    }

    .weekly-report-page .task-list {
        border-radius: 10px;
        border: 1px solid rgba(203, 213, 225, 0.7);
        padding: 0.5rem 0.5rem 0.4rem;
        max-height: 260px;
        overflow-y: auto;
    }

    .weekly-report-page .stack {
        display: flex;
        flex-direction: column;
    }

    .weekly-report-page .stack.stack-sm > * + * {
        margin-top: 0.35rem;
    }

    .weekly-report-page .task-list-item {
        display: flex;
        align-items: flex-start;
        padding: 0.45rem 0.4rem;
        border-radius: 8px;
        cursor: pointer;
        gap: 0.45rem;
    }

    .weekly-report-page .task-list-item:hover {
        background-color: rgba(226, 232, 240, 0.5);
    }

    .weekly-report-page .task-checkbox {
        margin-top: 0.2rem;
    }

    .weekly-report-page .task-list-body {
        flex: 1;
    }

    .weekly-report-page .task-list-title {
        font-size: 0.9rem;
        font-weight: 500;
    }

    .weekly-report-page .task-list-meta {
        margin-top: 0.1rem;
        font-size: 0.78rem;
        color: #6b7280;
        display: flex;
        flex-wrap: wrap;
        gap: 0.35rem;
    }

    .weekly-report-page .badge-pill {
        border-radius: 999px;
        padding: 0.1rem 0.5rem;
        font-size: 0.75rem;
    }

    .weekly-report-page .badge-soft-high {
        background-color: rgba(248, 113, 113, 0.1);
        color: #b91c1c;
    }

    .weekly-report-page .badge-soft-medium {
        background-color: rgba(251, 191, 36, 0.12);
        color: #92400e;
    }

    .weekly-report-page .badge-soft-low {
        background-color: rgba(34, 197, 94, 0.12);
        color: #166534;
    }

    .weekly-report-page .table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 0.4rem;
        font-size: 0.84rem;
    }

    .weekly-report-page .table th,
    .weekly-report-page .table td {
        padding: 0.4rem 0.45rem;
        border-bottom: 1px solid rgba(226, 232, 240, 0.8);
    }

    .weekly-report-page .table th {
        text-align: left;
        font-size: 0.78rem;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        color: #6b7280;
        background: rgba(248, 250, 252, 0.95);
    }

    .weekly-report-page .skeleton-line {
        height: 0.75rem;
        border-radius: 999px;
        background: linear-gradient(
            90deg,
            rgba(148, 163, 184, 0.3),
            rgba(148, 163, 184, 0.1),
            rgba(148, 163, 184, 0.3)
        );
        background-size: 200% 100%;
        animation: weekly-skeleton 1.4s ease-in-out infinite;
        margin-bottom: 0.4rem;
    }

    .weekly-report-page .skeleton-line-lg {
        height: 1.1rem;
    }

    .weekly-report-page .skeleton-line-sm {
        height: 0.55rem;
        width: 60%;
    }

    @keyframes weekly-skeleton {
        0% { background-position: 200% 0; }
        100% { background-position: -200% 0; }
    }

    .weekly-report-page .mt-6 {
        margin-top: 1.75rem;
    }

    .weekly-report-page .flex-row {
        display: flex;
        align-items: center;
    }

    .weekly-report-page .flex-between {
        justify-content: space-between;
    }
</style>

<div class="weekly-report-page">
    <div class="page-header">
        <div>
            <h1 class="page-title">Weekly Report</h1>
            <p class="page-description">
                Capture what you worked on this week and optionally link it to tasks.
            </p>
        </div>
        <div class="page-actions">
            <span class="badge badge-soft-sky">
                Week: <?= $week ?>
            </span>
        </div>
    </div>

    <div class="layout-grid layout-grid-2">
        <!-- Left: Report form -->
        <section class="card">
            <div class="card-header">
                <h2 class="card-title">This Week's Accomplishments</h2>
                <p class="card-subtitle">
                    Summarize your key work for <strong><?= $week ?></strong>.
                </p>
            </div>

            <div class="card-body">
                <form id="weekly-report-form">
                    <input type="hidden" name="week" value="<?= $week ?>">

                    <div class="form-group">
                        <label for="status" class="form-label">Status</label>
                        <select name="status" id="status" class="form-control">
                            <option value="draft">Draft</option>
                            <option value="submitted">Submitted</option>
                        </select>
                        <p class="form-hint">
                            Save as <strong>Draft</strong> to continue editing, or mark as
                            <strong>Submitted</strong> when you're done.
                        </p>
                    </div>

                    <div class="form-group">
                        <label for="accomplishments" class="form-label">
                            What did you work on?
                        </label>
                        <textarea
                            id="accomplishments"
                            name="accomplishments"
                            rows="10"
                            class="form-control"
                            placeholder="Example:
- Wrapped up onboarding for 3 new leads
- Followed up on open tasks for ACME Corp
- Prepared outline for next week's campaign..."></textarea>
                    </div>

                    <div class="form-footer">
                        <button type="submit" class="btn btn-primary" id="save-report-btn">
                            Save Weekly Report
                        </button>
                        <span id="weekly-report-status" class="text-muted" style="margin-left: 0.75rem;"></span>
                    </div>
                </form>
            </div>
        </section>

        <!-- Right: Tasks + stats -->
        <section class="card">
            <div class="card-header">
                <h2 class="card-title">Link Tasks</h2>
                <p class="card-subtitle">
                    Optionally link tasks you worked on this week.
                </p>
            </div>

            <div class="card-body">
                <div class="card card-soft mb-4">
                    <div class="card-body small">
                        <div id="weekly-report-stats">
                            <div class="skeleton-line skeleton-line-lg"></div>
                        </div>
                    </div>
                </div>

                <div class="form-group mb-2">
                    <div class="flex-row flex-between">
                        <label class="form-label">Tasks for <?= $week ?></label>
                        <button type="button" class="btn btn-link btn-xs" id="reload-tasks-btn">
                            Reload
                        </button>
                    </div>
                    <p class="form-hint">
                        Check the tasks that this report relates to. This is optional.
                    </p>
                </div>

                <div id="tasks-container" class="task-list">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line skeleton-line-sm"></div>
                </div>

                <div class="card-footer text-muted">
                    Linked tasks are stored in <code>report_task_links</code> and can be used later
                    for manager dashboards or analytics.
                </div>
            </div>
        </section>
    </div>

    <!-- History -->
    <section class="card mt-6">
        <div class="card-header">
            <h2 class="card-title">Recent Weekly Reports</h2>
            <p class="card-subtitle">
                Quick overview of your last few weeks.
            </p>
        </div>
        <div class="card-body">
            <div id="weekly-report-history" class="history-list">
                <div class="skeleton-line"></div>
                <div class="skeleton-line"></div>
                <div class="skeleton-line skeleton-line-sm"></div>
            </div>
        </div>
    </section>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const week = <?= json_encode($week) ?>;
        const baseUrl = '/lead-management/public/app/weekly-reports';

        const form = document.getElementById('weekly-report-form');
        const statusSpan = document.getElementById('weekly-report-status');
        const accomplishmentsEl = document.getElementById('accomplishments');
        const statusEl = document.getElementById('status');
        const tasksContainer = document.getElementById('tasks-container');
        const reloadTasksBtn = document.getElementById('reload-tasks-btn');
        const statsContainer = document.getElementById('weekly-report-stats');
        const historyContainer = document.getElementById('weekly-report-history');

        function setStatus(message, type = 'muted') {
            statusSpan.textContent = message || '';
            statusSpan.className = '';
            if (message) {
                statusSpan.classList.add(type === 'error' ? 'text-danger' : 'text-muted');
            }
        }

        // Load existing report for this week
        function loadCurrentReport() {
            fetch(`${baseUrl}/report?week=${encodeURIComponent(week)}`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success || !data.data) {
                        return;
                    }
                    const report = data.data;
                    accomplishmentsEl.value = report.accomplishments || '';
                    if (report.status) {
                        statusEl.value = report.status;
                    }
                    if (Array.isArray(report.linked_task_ids) && report.linked_task_ids.length > 0) {
                        const ids = new Set(report.linked_task_ids.map(String));
                        document
                            .querySelectorAll('#tasks-container input[type="checkbox"][name="linked_tasks[]"]')
                            .forEach(cb => {
                                cb.checked = ids.has(cb.value);
                            });
                    }
                })
                .catch(err => {
                    console.error('Error loading weekly report:', err);
                });
        }

        // Load tasks for this week
        function loadTasks() {
            tasksContainer.innerHTML = '<div class="skeleton-line"></div><div class="skeleton-line"></div>';
            fetch(`${baseUrl}/tasks?week=${encodeURIComponent(week)}`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        tasksContainer.innerHTML = '<p class="text-muted">Unable to load tasks.</p>';
                        return;
                    }

                    const tasks = data.data || [];
                    if (tasks.length === 0) {
                        tasksContainer.innerHTML = '<p class="text-muted">No tasks found for this week.</p>';
                        return;
                    }

                    const list = document.createElement('div');
                    list.className = 'stack stack-sm';

                    tasks.forEach(task => {
                        const item = document.createElement('label');
                        item.className = 'task-list-item';

                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.name = 'linked_tasks[]';
                        checkbox.value = task.task_id;
                        checkbox.className = 'task-checkbox';

                        const body = document.createElement('div');
                        body.className = 'task-list-body';

                        const title = document.createElement('div');
                        title.className = 'task-list-title';
                        title.textContent = task.title || 'Untitled task';

                        const meta = document.createElement('div');
                        meta.className = 'task-list-meta';

                        if (task.priority) {
                            const priority = document.createElement('span');
                            priority.className = `badge badge-pill badge-soft-${task.priority}`;
                            priority.textContent = task.priority.charAt(0).toUpperCase() + task.priority.slice(1);
                            meta.appendChild(priority);
                        }

                        if (task.due_date) {
                            const due = document.createElement('span');
                            due.className = 'text-muted';
                            due.style.marginLeft = '0.5rem';
                            due.textContent = 'Due ' + task.due_date;
                            meta.appendChild(due);
                        }

                        body.appendChild(title);
                        body.appendChild(meta);

                        item.appendChild(checkbox);
                        item.appendChild(body);
                        list.appendChild(item);
                    });

                    tasksContainer.innerHTML = '';
                    tasksContainer.appendChild(list);

                    // After tasks load, re-apply linked checkboxes if report already loaded
                    loadCurrentReport();
                })
                .catch(err => {
                    console.error('Error loading tasks:', err);
                    tasksContainer.innerHTML = '<p class="text-muted">Unable to load tasks.</p>';
                });
        }

        // Load stats (right-side card)
        function loadStats() {
            statsContainer.innerHTML = '<div class="skeleton-line skeleton-line-lg"></div>';
            fetch(`${baseUrl}/stats`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        statsContainer.innerHTML = '<p class="text-muted">Unable to load stats.</p>';
                        return;
                    }
                    const s = data.data || {};
                    const r = s.reports || {};

                    statsContainer.innerHTML = `
                    <div class="flex-row flex-between">
                        <div>
                            <div class="text-xs text-muted">Total reports</div>
                            <div class="text-lg font-semibold">${r.total || 0}</div>
                        </div>
                        <div>
                            <div class="text-xs text-muted">Submitted</div>
                            <div class="text-lg font-semibold">${r.submitted || 0}</div>
                        </div>
                        <div>
                            <div class="text-xs text-muted">Approved</div>
                            <div class="text-lg font-semibold">${r.approved || 0}</div>
                        </div>
                    </div>
                    <div class="mt-3 text-xs text-muted">
                        This week: <strong>${s.current_week || week}</strong>
                        — status: <strong>${(r.current_week_status || 'not_started').replace('_', ' ')}</strong>
                    </div>
                `;
                })
                .catch(err => {
                    console.error('Error loading stats:', err);
                    statsContainer.innerHTML = '<p class="text-muted">Unable to load stats.</p>';
                });
        }

        // Load history table
        function loadHistory() {
            historyContainer.innerHTML = '<div class="skeleton-line"></div><div class="skeleton-line"></div>';
            fetch(`${baseUrl}/history?limit=8`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        historyContainer.innerHTML = '<p class="text-muted">Unable to load history.</p>';
                        return;
                    }
                    const items = data.data || [];
                    if (items.length === 0) {
                        historyContainer.innerHTML = '<p class="text-muted">No previous weekly reports yet.</p>';
                        return;
                    }

                    const table = document.createElement('table');
                    table.className = 'table table-sm';

                    table.innerHTML = `
                    <thead>
                        <tr>
                            <th>Week</th>
                            <th>Status</th>
                            <th>Linked Tasks</th>
                            <th>Length</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${items.map(row => `
                            <tr>
                                <td>${row.week}</td>
                                <td>${row.status}</td>
                                <td>${row.linked_tasks_count}</td>
                                <td>${row.content_length}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                `;

                    historyContainer.innerHTML = '';
                    historyContainer.appendChild(table);
                })
                .catch(err => {
                    console.error('Error loading history:', err);
                    historyContainer.innerHTML = '<p class="text-muted">Unable to load history.</p>';
                });
        }

        // Handle form submit via AJAX
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            setStatus('Saving...');

            const formData = new FormData(form);

            fetch(`${baseUrl}/submit`, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(r => r.json())
                .then(data => {
                    if (!data.success) {
                        setStatus(data.message || 'Failed to save report', 'error');
                        return;
                    }
                    setStatus(data.message || 'Saved');
                    loadStats();
                    loadHistory();
                })
                .catch(err => {
                    console.error('Error saving weekly report:', err);
                    setStatus('Failed to save weekly report', 'error');
                });
        });

        reloadTasksBtn.addEventListener('click', function() {
            loadTasks();
        });

        // Initial load
        loadTasks();
        loadStats();
        loadHistory();
        loadCurrentReport();
    });
</script>
