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

{% block title %}Batch Processing & Scheduling{% endblock %}

{% block extra_css %}
<style>
.batch-dashboard {
    padding: 20px;
}

.stats-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
}

.stats-card h3 {
    margin: 0;
    font-size: 2.5rem;
    font-weight: bold;
}

.stats-card p {
    margin: 5px 0 0 0;
    opacity: 0.9;
}

.job-status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: bold;
    text-transform: uppercase;
}

.status-pending { background-color: #ffc107; color: #000; }
.status-processing { background-color: #17a2b8; color: #fff; }
.status-completed { background-color: #28a745; color: #fff; }
.status-failed { background-color: #dc3545; color: #fff; }
.status-cancelled { background-color: #6c757d; color: #fff; }

.progress-container {
    background-color: #e9ecef;
    border-radius: 10px;
    height: 20px;
    overflow: hidden;
    margin: 10px 0;
}

.progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #28a745, #20c997);
    transition: width 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 0.75rem;
    font-weight: bold;
}

.schedule-frequency {
    display: inline-block;
    padding: 2px 6px;
    background-color: #e9ecef;
    border-radius: 4px;
    font-size: 0.75rem;
    color: #495057;
}

.action-buttons .btn {
    margin-right: 5px;
    margin-bottom: 5px;
}

.modal-body .form-group {
    margin-bottom: 15px;
}

.report-type-checkbox {
    margin-bottom: 8px;
}

.email-recipient {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
}

.email-recipient input {
    flex: 1;
    margin-right: 10px;
}

.real-time-updates {
    border-left: 4px solid #007bff;
    padding-left: 15px;
    background-color: #f8f9fa;
    border-radius: 0 4px 4px 0;
}

@media (max-width: 768px) {
    .batch-dashboard {
        padding: 10px;
    }
    
    .stats-card h3 {
        font-size: 2rem;
    }
    
    .action-buttons .btn {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="batch-dashboard">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>
            <i class="fas fa-tasks text-primary"></i>
            Batch Processing & Scheduling
        </h2>
        <div class="action-buttons">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createBatchJobModal">
                <span>+</span> New Batch Job
            </button>
            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createScheduleModal">
                <i class="fas fa-calendar-plus"></i> Schedule Report
            </button>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stats-card">
                <h3>{{ job_stats.total_jobs }}</h3>
                <p>Total Jobs</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <h3>{{ job_stats.completed_jobs }}</h3>
                <p>Completed Jobs</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <h3>{{ job_stats.failed_jobs }}</h3>
                <p>Failed Jobs</p>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <h3>{{ job_stats.active_schedules }}</h3>
                <p>Active Schedules</p>
            </div>
        </div>
    </div>

    <!-- Recent Jobs -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="fas fa-history"></i>
                Recent Jobs
            </h5>
            <button type="button" class="btn btn-sm btn-outline-primary" id="refreshJobs">
                <span>🔄</span> Refresh
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="recentJobsTable">
                    <thead>
                        <tr>
                            <th>Job ID</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Progress</th>
                            <th>Created</th>
                            <th>Duration</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for job in recent_jobs %}
                        <tr data-job-id="{{ job.id }}">
                            <td>
                                <code>{{ job.id|slice:":8" }}...</code>
                            </td>
                            <td>{{ job.job_type|title }}</td>
                            <td>
                                <span class="job-status-badge status-{{ job.status }}">
                                    {{ job.status }}
                                </span>
                            </td>
                            <td>
                                <div class="progress-container">
                                    <div class="progress-bar" style="width: {{ job.progress_percentage }}%">
                                        {{ job.progress_percentage|floatformat:1 }}%
                                    </div>
                                </div>
                                <small class="text-muted">
                                    {{ job.processed_items }}/{{ job.total_items }} items
                                </small>
                            </td>
                            <td>{{ job.created_at|date:"M d, Y H:i" }}</td>
                            <td>
                                {% if job.duration %}
                                    {{ job.duration }}
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-info view-job" 
                                            data-job-id="{{ job.id }}">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    {% if job.status == 'completed' %}
                                    <button type="button" class="btn btn-outline-success download-job" 
                                            data-job-id="{{ job.id }}">
                                        <span>⬇️</span>
                                    </button>
                                    {% endif %}
                                    {% if job.status in 'pending,processing' %}
                                    <button type="button" class="btn btn-outline-danger cancel-job" 
                                            data-job-id="{{ job.id }}">
                                        <span>✕</span>
                                    </button>
                                    {% endif %}
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="7" class="text-center text-muted">
                                No recent jobs found. Create your first batch job to get started.
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Scheduled Reports -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <span>📅</span>
                Scheduled Reports
            </h5>
            <button type="button" class="btn btn-sm btn-outline-primary" id="refreshSchedules">
                <span>🔄</span> Refresh
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="scheduledReportsTable">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Frequency</th>
                            <th>Next Run</th>
                            <th>Last Run</th>
                            <th>Run Count</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for report in scheduled_reports %}
                        <tr data-report-id="{{ report.id }}">
                            <td>
                                <strong>{{ report.name }}</strong>
                                {% if report.description %}
                                <br><small class="text-muted">{{ report.description }}</small>
                                {% endif %}
                            </td>
                            <td>
                                <span class="schedule-frequency">{{ report.frequency|title }}</span>
                                <br><small class="text-muted">{{ report.time_of_day }}</small>
                            </td>
                            <td>
                                {% if report.next_run %}
                                    {{ report.next_run|date:"M d, Y H:i" }}
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td>
                                {% if report.last_run %}
                                    {{ report.last_run|date:"M d, Y H:i" }}
                                {% else %}
                                    Never
                                {% endif %}
                            </td>
                            <td>{{ report.run_count }}</td>
                            <td>
                                {% if report.is_active %}
                                    <span class="badge bg-success">Active</span>
                                {% else %}
                                    <span class="badge bg-secondary">Inactive</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-info edit-schedule" 
                                            data-report-id="{{ report.id }}">
                                        <span>✏️</span>
                                    </button>
                                    <button type="button" class="btn btn-outline-warning run-now" 
                                            data-report-id="{{ report.id }}">
                                        <span>▶</span>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger delete-schedule" 
                                            data-report-id="{{ report.id }}">
                                        <span>🗑️</span>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="7" class="text-center text-muted">
                                No scheduled reports found. Create your first scheduled report to automate report generation.
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Batch Job Modal -->
<div class="modal fade" id="createBatchJobModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create Batch Job</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="batchJobForm">
                    <div class="form-group">
                        <label for="jobType" class="form-label">Job Type</label>
                        <select class="form-select" id="jobType" required>
                            <option value="batch_export">Batch Export</option>
                            <option value="bulk_processing">Bulk Processing</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Report Types</label>
                        <div id="reportTypesContainer">
                            {% for report_type in available_report_types %}
                            <div class="form-check report-type-checkbox">
                                <input class="form-check-input" type="checkbox" 
                                       value="{{ report_type }}" id="reportType_{{ report_type }}">
                                <label class="form-check-label" for="reportType_{{ report_type }}">
                                    {{ report_type|title|replace:"_":" " }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Export Formats</label>
                        <div id="exportFormatsContainer">
                            {% for format in export_formats %}
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" 
                                       value="{{ format }}" id="exportFormat_{{ format }}" checked>
                                <label class="form-check-label" for="exportFormat_{{ format }}">
                                    {{ format|upper }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="emailRecipients" class="form-label">Email Recipients (Optional)</label>
                        <div id="emailRecipientsContainer">
                            <div class="email-recipient">
                                <input type="email" class="form-control" placeholder="Enter email address">
                                <button type="button" class="btn btn-outline-danger remove-email">
                                    <span>−</span>
                                </button>
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="addEmailRecipient">
                            <span>+</span> Add Email
                        </button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="createBatchJob">Create Job</button>
            </div>
        </div>
    </div>
</div>

<!-- Create Schedule Modal -->
<div class="modal fade" id="createScheduleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Schedule Report</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="scheduleForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="scheduleName" class="form-label">Schedule Name</label>
                                <input type="text" class="form-control" id="scheduleName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="scheduleFrequency" class="form-label">Frequency</label>
                                <select class="form-select" id="scheduleFrequency" required>
                                    {% for value, label in frequency_choices %}
                                    <option value="{{ value }}">{{ label }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="scheduleDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="scheduleDescription" rows="2"></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="scheduleTime" class="form-label">Time</label>
                                <input type="time" class="form-control" id="scheduleTime" required>
                            </div>
                        </div>
                        <div class="col-md-4" id="dayOfWeekContainer" style="display: none;">
                            <div class="form-group">
                                <label for="scheduleDayOfWeek" class="form-label">Day of Week</label>
                                <select class="form-select" id="scheduleDayOfWeek">
                                    <option value="0">Monday</option>
                                    <option value="1">Tuesday</option>
                                    <option value="2">Wednesday</option>
                                    <option value="3">Thursday</option>
                                    <option value="4">Friday</option>
                                    <option value="5">Saturday</option>
                                    <option value="6">Sunday</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4" id="dayOfMonthContainer" style="display: none;">
                            <div class="form-group">
                                <label for="scheduleDayOfMonth" class="form-label">Day of Month</label>
                                <input type="number" class="form-control" id="scheduleDayOfMonth" 
                                       min="1" max="31" value="1">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Report Types</label>
                        <div id="scheduleReportTypesContainer">
                            {% for report_type in available_report_types %}
                            <div class="form-check report-type-checkbox">
                                <input class="form-check-input" type="checkbox" 
                                       value="{{ report_type }}" id="scheduleReportType_{{ report_type }}">
                                <label class="form-check-label" for="scheduleReportType_{{ report_type }}">
                                    {{ report_type|title|replace:"_":" " }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Export Formats</label>
                        <div id="scheduleExportFormatsContainer">
                            {% for format in export_formats %}
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" 
                                       value="{{ format }}" id="scheduleExportFormat_{{ format }}" checked>
                                <label class="form-check-label" for="scheduleExportFormat_{{ format }}">
                                    {{ format|upper }}
                                </label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="scheduleEmailRecipients" class="form-label">Email Recipients</label>
                        <div id="scheduleEmailRecipientsContainer">
                            <div class="email-recipient">
                                <input type="email" class="form-control" placeholder="Enter email address">
                                <button type="button" class="btn btn-outline-danger remove-email">
                                    <span>−</span>
                                </button>
                            </div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="addScheduleEmailRecipient">
                            <span>+</span> Add Email
                        </button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="createSchedule">Create Schedule</button>
            </div>
        </div>
    </div>
</div>

<!-- Job Progress Modal -->
<div class="modal fade" id="jobProgressModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Job Progress</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="real-time-updates" id="progressContent">
                    <!-- Progress content will be populated here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
class BatchProcessingDashboard {
    constructor() {
        this.init();
        this.setupEventListeners();
        this.startRealTimeUpdates();
    }
    
    init() {
        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
    
    setupEventListeners() {
        // Refresh buttons
        $('#refreshJobs').on('click', () => this.refreshJobs());
        $('#refreshSchedules').on('click', () => this.refreshSchedules());
        
        // Create batch job
        $('#createBatchJob').on('click', () => this.createBatchJob());
        $('#createSchedule').on('click', () => this.createSchedule());
        
        // Job actions
        $(document).on('click', '.view-job', (e) => this.viewJob(e));
        $(document).on('click', '.download-job', (e) => this.downloadJob(e));
        $(document).on('click', '.cancel-job', (e) => this.cancelJob(e));
        
        // Schedule actions
        $(document).on('click', '.edit-schedule', (e) => this.editSchedule(e));
        $(document).on('click', '.run-now', (e) => this.runScheduleNow(e));
        $(document).on('click', '.delete-schedule', (e) => this.deleteSchedule(e));
        
        // Email recipient management
        $('#addEmailRecipient').on('click', () => this.addEmailRecipient('#emailRecipientsContainer'));
        $('#addScheduleEmailRecipient').on('click', () => this.addEmailRecipient('#scheduleEmailRecipientsContainer'));
        $(document).on('click', '.remove-email', (e) => this.removeEmailRecipient(e));
        
        // Schedule frequency change
        $('#scheduleFrequency').on('change', () => this.updateScheduleFields());
    }
    
    startRealTimeUpdates() {
        // Update job progress every 5 seconds
        setInterval(() => {
            this.updateJobProgress();
        }, 5000);
    }
    
    async refreshJobs() {
        try {
            const response = await fetch('/api/batch-jobs/');
            const jobs = await response.json();
            
            this.updateJobsTable(jobs);
            
        } catch (error) {
            console.error('Error refreshing jobs:', error);
        }
    }
    
    async refreshSchedules() {
        try {
            const response = await fetch('/api/scheduled-reports/');
            const schedules = await response.json();
            
            this.updateSchedulesTable(schedules);
            
        } catch (error) {
            console.error('Error refreshing schedules:', error);
        }
    }
    
    async createBatchJob() {
        try {
            const reportTypes = Array.from(document.querySelectorAll('#reportTypesContainer input:checked'))
                .map(cb => cb.value);
            
            const exportFormats = Array.from(document.querySelectorAll('#exportFormatsContainer input:checked'))
                .map(cb => cb.value);
            
            const emailRecipients = Array.from(document.querySelectorAll('#emailRecipientsContainer input[type="email"]'))
                .map(input => input.value)
                .filter(email => email.trim() !== '');
            
            if (reportTypes.length === 0) {
                alert('Please select at least one report type.');
                return;
            }
            
            if (exportFormats.length === 0) {
                alert('Please select at least one export format.');
                return;
            }
            
            const jobData = {
                job_type: document.getElementById('jobType').value,
                report_types: reportTypes,
                export_formats: exportFormats,
                email_recipients: emailRecipients,
                filters: {} // Could be extended to include filters
            };
            
            const response = await fetch('/api/batch-jobs/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCsrfToken()
                },
                body: JSON.stringify(jobData)
            });
            
            if (response.ok) {
                const job = await response.json();
                $('#createBatchJobModal').modal('hide');
                this.refreshJobs();
                alert(`Batch job created successfully! Job ID: ${job.id}`);
            } else {
                const error = await response.json();
                alert(`Error creating batch job: ${error.error}`);
            }
            
        } catch (error) {
            console.error('Error creating batch job:', error);
            alert('Error creating batch job. Please try again.');
        }
    }
    
    async createSchedule() {
        try {
            const reportTypes = Array.from(document.querySelectorAll('#scheduleReportTypesContainer input:checked'))
                .map(cb => cb.value);
            
            const exportFormats = Array.from(document.querySelectorAll('#scheduleExportFormatsContainer input:checked'))
                .map(cb => cb.value);
            
            const emailRecipients = Array.from(document.querySelectorAll('#scheduleEmailRecipientsContainer input[type="email"]'))
                .map(input => input.value)
                .filter(email => email.trim() !== '');
            
            if (reportTypes.length === 0) {
                alert('Please select at least one report type.');
                return;
            }
            
            const frequency = document.getElementById('scheduleFrequency').value;
            const scheduleData = {
                name: document.getElementById('scheduleName').value,
                description: document.getElementById('scheduleDescription').value,
                frequency: frequency,
                time_of_day: document.getElementById('scheduleTime').value,
                report_types: reportTypes,
                export_formats: exportFormats,
                email_recipients: emailRecipients,
                filters: {}
            };
            
            // Add frequency-specific fields
            if (frequency === 'weekly') {
                scheduleData.day_of_week = parseInt(document.getElementById('scheduleDayOfWeek').value);
            } else if (frequency === 'monthly') {
                scheduleData.day_of_month = parseInt(document.getElementById('scheduleDayOfMonth').value);
            }
            
            const response = await fetch('/api/scheduled-reports/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCsrfToken()
                },
                body: JSON.stringify(scheduleData)
            });
            
            if (response.ok) {
                const schedule = await response.json();
                $('#createScheduleModal').modal('hide');
                this.refreshSchedules();
                alert(`Scheduled report created successfully! Next run: ${schedule.next_run}`);
            } else {
                const error = await response.json();
                alert(`Error creating scheduled report: ${error.error}`);
            }
            
        } catch (error) {
            console.error('Error creating scheduled report:', error);
            alert('Error creating scheduled report. Please try again.');
        }
    }
    
    async viewJob(event) {
        const jobId = event.target.closest('button').dataset.jobId;
        
        try {
            const response = await fetch(`/api/batch-jobs/${jobId}/progress/`);
            const progress = await response.json();
            
            this.showJobProgress(progress);
            
        } catch (error) {
            console.error('Error viewing job:', error);
        }
    }
    
    async downloadJob(event) {
        const jobId = event.target.closest('button').dataset.jobId;
        window.location.href = `/api/batch-jobs/${jobId}/download/`;
    }
    
    async cancelJob(event) {
        const jobId = event.target.closest('button').dataset.jobId;
        
        if (!confirm('Are you sure you want to cancel this job?')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/batch-jobs/${jobId}/`, {
                method: 'DELETE',
                headers: {
                    'X-CSRFToken': this.getCsrfToken()
                }
            });
            
            if (response.ok) {
                this.refreshJobs();
                alert('Job cancelled successfully.');
            } else {
                alert('Error cancelling job.');
            }
            
        } catch (error) {
            console.error('Error cancelling job:', error);
        }
    }
    
    showJobProgress(progress) {
        const content = `
            <div class="mb-3">
                <h6>Job ID: <code>${progress.id}</code></h6>
                <p><strong>Status:</strong> <span class="job-status-badge status-${progress.status}">${progress.status}</span></p>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Progress</label>
                <div class="progress-container">
                    <div class="progress-bar" style="width: ${progress.progress_percentage}%">
                        ${progress.progress_percentage.toFixed(1)}%
                    </div>
                </div>
                <small class="text-muted">${progress.processed_items}/${progress.total_items} items processed</small>
            </div>
            
            ${progress.estimated_time_remaining ? `
                <div class="mb-3">
                    <strong>Estimated Time Remaining:</strong> ${progress.estimated_time_remaining}
                </div>
            ` : ''}
            
            <div class="mb-3">
                <strong>Last Updated:</strong> ${new Date(progress.last_updated).toLocaleString()}
            </div>
        `;
        
        document.getElementById('progressContent').innerHTML = content;
        $('#jobProgressModal').modal('show');
    }
    
    updateScheduleFields() {
        const frequency = document.getElementById('scheduleFrequency').value;
        
        // Hide all frequency-specific fields
        document.getElementById('dayOfWeekContainer').style.display = 'none';
        document.getElementById('dayOfMonthContainer').style.display = 'none';
        
        // Show relevant fields
        if (frequency === 'weekly') {
            document.getElementById('dayOfWeekContainer').style.display = 'block';
        } else if (frequency === 'monthly') {
            document.getElementById('dayOfMonthContainer').style.display = 'block';
        }
    }
    
    addEmailRecipient(containerId) {
        const container = document.querySelector(containerId);
        const emailDiv = document.createElement('div');
        emailDiv.className = 'email-recipient';
        emailDiv.innerHTML = `
            <input type="email" class="form-control" placeholder="Enter email address">
            <button type="button" class="btn btn-outline-danger remove-email">
                <span>−</span>
            </button>
        `;
        container.appendChild(emailDiv);
    }
    
    removeEmailRecipient(event) {
        const emailDiv = event.target.closest('.email-recipient');
        emailDiv.remove();
    }
    
    async updateJobProgress() {
        // Update progress for processing jobs
        const processingRows = document.querySelectorAll('tr[data-job-id] .status-processing');
        
        for (const statusElement of processingRows) {
            const row = statusElement.closest('tr');
            const jobId = row.dataset.jobId;
            
            try {
                const response = await fetch(`/api/batch-jobs/${jobId}/progress/`);
                const progress = await response.json();
                
                // Update progress bar
                const progressBar = row.querySelector('.progress-bar');
                if (progressBar) {
                    progressBar.style.width = `${progress.progress_percentage}%`;
                    progressBar.textContent = `${progress.progress_percentage.toFixed(1)}%`;
                }
                
                // Update status if changed
                if (progress.status !== 'processing') {
                    this.refreshJobs();
                }
                
            } catch (error) {
                console.error(`Error updating progress for job ${jobId}:`, error);
            }
        }
    }
    
    updateJobsTable(jobs) {
        const tbody = document.querySelector('#recentJobsTable tbody');
        
        if (jobs.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-muted">
                        No recent jobs found. Create your first batch job to get started.
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = jobs.map(job => `
            <tr data-job-id="${job.id}">
                <td><code>${job.id.slice(0, 8)}...</code></td>
                <td>${job.job_type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}</td>
                <td><span class="job-status-badge status-${job.status}">${job.status}</span></td>
                <td>
                    <div class="progress-container">
                        <div class="progress-bar" style="width: ${job.progress_percentage}%">
                            ${job.progress_percentage.toFixed(1)}%
                        </div>
                    </div>
                    <small class="text-muted">${job.processed_items}/${job.total_items} items</small>
                </td>
                <td>${new Date(job.created_at).toLocaleDateString()} ${new Date(job.created_at).toLocaleTimeString()}</td>
                <td>${job.duration || '-'}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-info view-job" data-job-id="${job.id}">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${job.status === 'completed' ? `
                            <button type="button" class="btn btn-outline-success download-job" data-job-id="${job.id}">
                                <span>⬇️</span>
                            </button>
                        ` : ''}
                        ${['pending', 'processing'].includes(job.status) ? `
                            <button type="button" class="btn btn-outline-danger cancel-job" data-job-id="${job.id}">
                                <span>✕</span>
                            </button>
                        ` : ''}
                    </div>
                </td>
            </tr>
        `).join('');
    }
    
    updateSchedulesTable(schedules) {
        const tbody = document.querySelector('#scheduledReportsTable tbody');
        
        if (schedules.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-muted">
                        No scheduled reports found. Create your first scheduled report to automate report generation.
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = schedules.map(schedule => `
            <tr data-report-id="${schedule.id}">
                <td>
                    <strong>${schedule.name}</strong>
                    ${schedule.description ? `<br><small class="text-muted">${schedule.description}</small>` : ''}
                </td>
                <td>
                    <span class="schedule-frequency">${schedule.frequency.replace(/\b\w/g, l => l.toUpperCase())}</span>
                    <br><small class="text-muted">${schedule.time_of_day}</small>
                </td>
                <td>${schedule.next_run ? new Date(schedule.next_run).toLocaleDateString() + ' ' + new Date(schedule.next_run).toLocaleTimeString() : '-'}</td>
                <td>${schedule.last_run ? new Date(schedule.last_run).toLocaleDateString() + ' ' + new Date(schedule.last_run).toLocaleTimeString() : 'Never'}</td>
                <td>${schedule.run_count}</td>
                <td>
                    ${schedule.is_active ? 
                        '<span class="badge bg-success">Active</span>' : 
                        '<span class="badge bg-secondary">Inactive</span>'
                    }
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-info edit-schedule" data-report-id="${schedule.id}">
                            <span>✏️</span>
                        </button>
                        <button type="button" class="btn btn-outline-warning run-now" data-report-id="${schedule.id}">
                            <span>▶</span>
                        </button>
                        <button type="button" class="btn btn-outline-danger delete-schedule" data-report-id="${schedule.id}">
                            <span>🗑️</span>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }
    
    getCsrfToken() {
        return document.querySelector('[name=csrfmiddlewaretoken]').value;
    }
}

// Initialize when DOM is ready
$(document).ready(function() {
    window.batchDashboard = new BatchProcessingDashboard();
});
</script>
{% endblock %}