<?php echo $__env->make('admin.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="<?php echo e(route('admin.dashboard')); ?>">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="<?php echo e(route('admin.document-generator.index')); ?>">Document Generator</a></li>
                        <li class="breadcrumb-item active">Export Center</li>
                    </ol>
                </div>
                <h4 class="page-title">Export Center</h4>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Generated Documents -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Generated Documents</h5>
                    
                    <div class="table-responsive">
                        <table class="table table-centered table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>
                                        <input type="checkbox" id="selectAll">
                                    </th>
                                    <th>Document</th>
                                    <th>Order</th>
                                    <th>Type</th>
                                    <th>Generated By</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__empty_1 = true; $__currentLoopData = $documents; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $document): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td>
                                        <input type="checkbox" class="document-checkbox" value="<?php echo e($document->id); ?>">
                                    </td>
                                    <td>
                                        <i class="fas fa-file-pdf text-danger me-2"></i>
                                        <?php echo e($document->file_name); ?>

                                    </td>
                                    <td>
                                        <?php echo e($document->orderConfirmation->order_number ?? 'N/A'); ?>

                                    </td>
                                    <td>
                                        <span class="badge bg-info"><?php echo e(str_replace('_', ' ', ucfirst($document->document_type))); ?></span>
                                    </td>
                                    <td><?php echo e($document->generator->name ?? 'System'); ?></td>
                                    <td><?php echo e($document->created_at->format('M j, Y')); ?></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="<?php echo e(route('admin.document-generator.generated-documents.download', $document->id)); ?>" 
                                               class="btn btn-sm btn-outline-primary" title="Download">
                                                <i class="fas fa-download"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-outline-success email-btn" 
                                                    data-document-id="<?php echo e($document->id); ?>" 
                                                    data-document-name="<?php echo e($document->file_name); ?>"
                                                    title="Send Email">
                                                <i class="fas fa-envelope"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4">
                                        <div class="text-muted">
                                            <i class="fas fa-file-pdf fa-3x mb-3"></i>
                                            <h5>No documents generated yet</h5>
                                            <p>Generate documents first to see them here.</p>
                                            <a href="<?php echo e(route('admin.document-generator.index')); ?>" class="btn btn-primary">
                                                <i class="fas fa-file-pdf me-1"></i> Generate Documents
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if($documents->hasPages()): ?>
                    <div class="row mt-3">
                        <div class="col-12">
                            <?php echo e($documents->links()); ?>

                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row mt-3">
                        <div class="col-12">
                            <button type="button" class="btn btn-primary" id="bulkDownloadBtn" disabled>
                                <i class="fas fa-download me-1"></i> Download Selected
                            </button>
                            <button type="button" class="btn btn-outline-info" id="createReportBtn">
                                <i class="fas fa-file-excel me-1"></i> Create Excel Report
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Email Logs -->
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Recent Email Logs</h5>
                    <?php $__empty_1 = true; $__currentLoopData = $emailLogs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $log): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <div class="border-bottom pb-2 mb-2">
                        <div class="d-flex justify-content-between">
                            <strong><?php echo e($log->recipient_email); ?></strong>
                            <span class="badge bg-<?php echo e($log->status === 'sent' ? 'success' : 'warning'); ?>">
                                <?php echo e(ucfirst($log->status)); ?>

                            </span>
                        </div>
                        <small class="text-muted"><?php echo e($log->subject); ?></small>
                        <div class="text-muted small"><?php echo e($log->created_at->format('M j, Y H:i')); ?></div>
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-envelope fa-2x mb-2"></i>
                        <p>No email logs yet</p>
                    </div>
                    <?php endif; ?>
                    <div class="text-center mt-2">
                        <a href="<?php echo e(route('admin.email-logs.index')); ?>" class="btn btn-sm btn-outline-primary">
                            View All Logs
                        </a>
                    </div>
                </div>
            </div>

            <!-- Export Jobs -->
            <div class="card mt-3">
                <div class="card-body">
                    <h5 class="card-title">Recent Export Jobs</h5>
                    <?php $__empty_1 = true; $__currentLoopData = $exportJobs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $job): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <div class="border-bottom pb-2 mb-2">
                        <div class="d-flex justify-content-between">
                            <strong><?php echo e(ucfirst($job->type)); ?></strong>
                            <span class="badge bg-<?php echo e($job->status === 'completed' ? 'success' : ($job->status === 'failed' ? 'danger' : 'warning')); ?>">
                                <?php echo e(ucfirst($job->status)); ?>

                            </span>
                        </div>
                        <div class="progress mt-1" style="height: 5px;">
                            <div class="progress-bar" style="width: <?php echo e($job->progress_percentage); ?>%"></div>
                        </div>
                        <small class="text-muted">By: <?php echo e($job->user->name); ?></small>
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-tasks fa-2x mb-2"></i>
                        <p>No export jobs yet</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Email Modal - Fixed Version -->
<div id="emailModal" class="modal-overlay" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; align-items: center; justify-content: center;">
    <div class="modal-content" style="background: white; padding: 20px; border-radius: 8px; width: 500px; max-width: 90%; max-height: 90vh; overflow-y: auto;">
        <div class="modal-header" style="display: flex; justify-content: between; align-items: center; border-bottom: 1px solid #dee2e6; padding-bottom: 15px; margin-bottom: 15px;">
            <h5 class="modal-title" style="margin: 0;">Send Document via Email</h5>
            <button type="button" class="close-btn" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        <form id="emailForm">
            <?php echo csrf_field(); ?>
            <div class="modal-body">
                <input type="hidden" name="document_id" id="emailDocumentId">
                <div class="mb-3">
                    <label for="recipient_email" class="form-label">Recipient Email <span class="text-danger">*</span></label>
                    <input type="email" class="form-control" id="recipient_email" name="recipient_email" required>
                </div>
                <div class="mb-3">
                    <label for="recipient_name" class="form-label">Recipient Name</label>
                    <input type="text" class="form-control" id="recipient_name" name="recipient_name">
                </div>
                <div class="mb-3">
                    <label for="subject" class="form-label">Subject <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="subject" name="subject" required>
                </div>
                <div class="mb-3">
                    <label for="message" class="form-label">Message</label>
                    <textarea class="form-control" id="message" name="message" rows="4"></textarea>
                </div>
            </div>
            <div class="modal-footer" style="border-top: 1px solid #dee2e6; padding-top: 15px; margin-top: 15px; display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" class="btn btn-secondary" id="cancelEmail">Cancel</button>
                <button type="submit" class="btn btn-success">Send Email</button>
            </div>
        </form>
    </div>
</div>

<script>
// Select All Checkbox
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.document-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
    updateBulkDownloadBtn();
});

// Update Bulk Download Button
document.querySelectorAll('.document-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', updateBulkDownloadBtn);
});

function updateBulkDownloadBtn() {
    const checkedCount = document.querySelectorAll('.document-checkbox:checked').length;
    const bulkBtn = document.getElementById('bulkDownloadBtn');
    bulkBtn.disabled = checkedCount === 0;
    bulkBtn.textContent = `Download Selected (${checkedCount})`;
}

// Bulk Download
document.getElementById('bulkDownloadBtn').addEventListener('click', function() {
    const selectedIds = Array.from(document.querySelectorAll('.document-checkbox:checked'))
        .map(checkbox => checkbox.value);
    
    if (selectedIds.length === 0) return;

    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '<?php echo e(route("admin.export-center.bulk-download")); ?>';
    
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = '_token';
    csrfInput.value = '<?php echo e(csrf_token()); ?>';
    form.appendChild(csrfInput);

    selectedIds.forEach(id => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'document_ids[]';
        input.value = id;
        form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();
});

// Email Modal Functions
const emailModal = document.getElementById('emailModal');
const closeBtn = document.querySelector('.close-btn');
const cancelBtn = document.getElementById('cancelEmail');

// Open Modal
document.querySelectorAll('.email-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const documentId = this.getAttribute('data-document-id');
        const documentName = this.getAttribute('data-document-name');
        
        document.getElementById('emailDocumentId').value = documentId;
        document.getElementById('subject').value = `Document: ${documentName}`;
        document.getElementById('recipient_email').value = '';
        document.getElementById('recipient_name').value = '';
        document.getElementById('message').value = '';
        
        emailModal.style.display = 'flex';
    });
});

// Close Modal Functions
function closeModal() {
    emailModal.style.display = 'none';
}

closeBtn.addEventListener('click', closeModal);
cancelBtn.addEventListener('click', closeModal);

// Close modal when clicking outside
emailModal.addEventListener('click', function(e) {
    if (e.target === emailModal) {
        closeModal();
    }
});

// Email Form Submission
document.getElementById('emailForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Sending...';
    
    fetch('<?php echo e(route("admin.export-center.send-email")); ?>', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Email sent successfully!');
            closeModal();
            location.reload();
        } else {
            alert('Error sending email: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while sending email.');
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});

// Create Report Button
document.getElementById('createReportBtn').addEventListener('click', function() {
    alert('Excel report feature will be implemented soon!');
});
</script>

<style>
.modal-overlay {
    backdrop-filter: blur(5px);
}

.modal-content {
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.close-btn:hover {
    color: #ff0000;
}

.email-btn {
    cursor: pointer;
}

.email-btn:hover {
    background-color: #28a745;
    color: white;
}
</style>

<?php echo $__env->make('admin.footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH E:\xampp2\htdocs\texsia\resources\views/admin/document-generator/export-center/index.blade.php ENDPATH**/ ?>