<main class="main-content" id="mainContent">
    <header class="main-header">
        <h1>PORTFOLIO MANAGEMENT</h1>
        <p class="welcome-text">Manage your portfolio items with advanced PDF processing</p>
    </header>

    <div class="content-area">
        <h2>Advanced Portfolio Management</h2>
        
        <!-- System Status -->
        <?php 
        $system_status = $this->pdf_service->get_system_stats();
        $python_service_available = $this->pdf_service->is_service_healthy();
        ?>
        
        <div class="system-status" style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
            <h3>System Status</h3>
            <?php if (!$python_service_available): ?>
            <div class="alert alert-warning">
                <strong>Warning:</strong> PDF processing service is currently unavailable. 
                Please ensure the Python service is running on port 5000.
            </div>
            <?php else: ?>
            <div class="alert alert-success">
                <strong>Success:</strong> PDF processing service is running and ready.
            </div>
            <?php if ($system_status): ?>
            <div class="status-details" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-top: 10px;">
                <div><strong>Active Workers:</strong> <?php echo $system_status['max_workers']; ?></div>
                <div><strong>Upload Limit:</strong> <?php echo $system_status['upload_limit']; ?></div>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Display Batch Processing Results -->
        <?php if ($this->session->flashdata('batch_processing_result')): 
            $batch_result = $this->session->flashdata('batch_processing_result');
        ?>
        <div class="batch-results" style="margin: 20px 0; padding: 20px; background: #e8f4fd; border-radius: 8px;">
            <h3>PDF Processing Results</h3>
            
            <div class="batch-summary" style="margin-bottom: 20px;">
                <h4>Summary</h4>
                <p><strong>Total Files:</strong> <?php echo $batch_result['total']; ?></p>
                <p><strong>Successful:</strong> <?php echo $batch_result['success']; ?></p>
                <p><strong>Failed:</strong> <?php echo $batch_result['failed']; ?></p>
                <p><strong>Processing Time:</strong> <?php echo date('Y-m-d H:i:s', strtotime($batch_result['processing_time'])); ?></p>
            </div>

            <?php if (!empty($batch_result['upload_errors'])): ?>
            <div class="upload-errors" style="margin-bottom: 20px;">
                <h4>Upload Errors</h4>
                <?php foreach ($batch_result['upload_errors'] as $error): ?>
                <div class="error-item" style="padding: 10px; margin: 5px 0; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px;">
                    <span style="color: #856404;"><?php echo $error; ?></span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if (!empty($batch_result['results'])): ?>
            <div class="batch-results-list">
                <h4>Processed Files (<?php echo count($batch_result['results']); ?>)</h4>
                <div class="results-grid" style="display: grid; gap: 15px; max-height: 600px; overflow-y: auto;">
                    <?php foreach ($batch_result['results'] as $result): ?>
                    <div class="result-item" style="padding: 15px; background: white; border-radius: 4px; border: 1px solid #dee2e6;">
                        <h5><?php echo htmlspecialchars($result['file_name']); ?></h5>
                        
                        <!-- Model Information -->
                        <?php if (!empty($result['model_info'])): ?>
                        <div class="model-info" style="margin: 10px 0; padding: 10px; background: #f0f8ff; border-radius: 4px;">
                            <h6>Extracted Model Information</h6>
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px;">
                                <?php if (!empty($result['model_info']['name'])): ?>
                                <div><strong>Name:</strong> <?php echo htmlspecialchars($result['model_info']['name']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['height'])): ?>
                                <div><strong>Height:</strong> <?php echo htmlspecialchars($result['model_info']['height']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['weight'])): ?>
                                <div><strong>Weight:</strong> <?php echo htmlspecialchars($result['model_info']['weight']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['waist'])): ?>
                                <div><strong>Waist:</strong> <?php echo htmlspecialchars($result['model_info']['waist']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['instagram'])): ?>
                                <div><strong>Instagram:</strong> <?php echo htmlspecialchars($result['model_info']['instagram']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['contact'])): ?>
                                <div><strong>Contact:</strong> <?php echo htmlspecialchars($result['model_info']['contact']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($result['model_info']['specialties'])): ?>
                                <div><strong>Specialties:</strong> <?php echo htmlspecialchars(implode(', ', $result['model_info']['specialties'])); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Document Stats -->
                        <div class="doc-stats" style="font-size: 14px; color: #666;">
                            <strong>Pages:</strong> <?php echo $result['metadata']['pages']; ?> | 
                            <strong>Images:</strong> <?php echo count($result['images']); ?> | 
                            <strong>Size:</strong> <?php echo round($result['metadata']['file_size'] / 1024, 2); ?> KB
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <button onclick="cleanupProcessing('<?php echo $batch_result['session_id']; ?>')" 
                    class="btn btn-secondary" style="margin-top: 20px; padding: 10px 20px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">
                Cleanup Temporary Files
            </button>
        </div>
        <?php endif; ?>

        <!-- Batch Upload -->
       <!-- In the batch upload form -->
<div style="padding: 20px; background: #f0f8ff; border-radius: 8px; margin: 20px 0;">
    <h3>Upload Portfolio PDFs in Batch</h3>
    <form action="<?php echo site_url('admin/upload_batch_pdfs'); ?>" method="post" enctype="multipart/form-data" id="batchForm">
        <div style="margin: 10px 0;">
            <!-- FIXED: Added array brackets [] -->
            <input type="file" name="pdf_files[]" multiple accept=".pdf" required 
                   style="padding: 8px; border: 2px dashed #007bff; border-radius: 4px; width: 100%;"
                   onchange="updateFileCount(this)">
            <div id="fileCount" style="font-size: 14px; color: #666; margin-top: 5px;"></div>
        </div>
        <button type="submit" class="btn btn-primary" 
                style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;"
                id="batchSubmit"
                <?php echo !$python_service_available ? 'disabled' : ''; ?>>
            Process Batch PDFs
        </button>
    </form>
    
    <div style="margin-top: 15px; font-size: 14px; color: #666;">
        <strong>Features:</strong> 
        <ul style="margin: 5px 0; padding-left: 20px;">
            <li>Upload multiple PDFs at once</li>
            <li>Auto-extract model information (name, height, weight, waist, Instagram)</li>
            <li>Extract images and convert to WebP format</li>
            <li>Parallel processing for faster results</li>
            <li>No file size or quantity limits</li>
        </ul>
    </div>
</div>
        <!-- Single File Upload -->
        <div style="padding: 20px; background: #f8f9fa; border-radius: 8px; margin: 20px 0;">
            <h3>Upload Single Portfolio PDF</h3>
            <form action="<?php echo site_url('admin/upload_portfolio_pdf'); ?>" method="post" enctype="multipart/form-data">
                <div style="margin: 10px 0;">
                    <input type="file" name="file" accept=".pdf" required 
                           style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <button type="submit" class="btn btn-primary" 
                        style="padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;"
                        <?php echo !$python_service_available ? 'disabled' : ''; ?>>
                    Process Single PDF
                </button>
            </form>
        </div>

        <!-- Flash Messages -->
        <?php if ($this->session->flashdata('success')): ?>
            <div class="alert alert-success" style="margin-top: 15px; padding: 10px; background: #d4edda; color: #155724; border-radius: 4px;">
                <?php echo $this->session->flashdata('success'); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($this->session->flashdata('error')): ?>
            <div class="alert alert-danger" style="margin-top: 15px; padding: 10px; background: #f8d7da; color: #721c24; border-radius: 4px;">
                <?php echo $this->session->flashdata('error'); ?>
            </div>
        <?php endif; ?>
    </div>
</main>

<script>
function updateFileCount(input) {
    const fileCount = input.files.length;
    const fileCountElement = document.getElementById('fileCount');
    
    if (fileCount > 0) {
        fileCountElement.innerHTML = `<strong>${fileCount} files selected</strong> - Ready to process!`;
        fileCountElement.style.color = '#28a745';
    } else {
        fileCountElement.textContent = '';
    }
}

function cleanupProcessing(sessionId) {
    if (confirm('Are you sure you want to cleanup temporary files? This will remove all extracted images.')) {
        fetch('<?php echo site_url('admin/cleanup_processing'); ?>/' + sessionId, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Temporary files cleaned up successfully!');
                document.querySelector('.batch-results').style.display = 'none';
            } else {
                alert('Cleanup failed: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Cleanup error: ' + error);
        });
    }
}

// Prevent form resubmission
document.getElementById('batchForm')?.addEventListener('submit', function(e) {
    const submitBtn = document.getElementById('batchSubmit');
    if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.textContent = 'Processing... Please wait';
    }
});
</script>