<?php
include_once 'config/database.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bulk Student Upload - Gateway Polytechnic Saapade</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .navbar {
            background: linear-gradient(135deg, #1a237e, #283593);
        }
        .upload-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-top: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .step-card {
            border-left: 4px solid #007bff;
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        .template-download {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            cursor: pointer;
            transition: transform 0.3s;
        }
        .template-download:hover {
            transform: translateY(-2px);
            color: white;
            text-decoration: none;
        }
        .upload-area {
            border: 2px dashed #007bff;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            background: #f8f9ff;
            transition: all 0.3s;
            cursor: pointer;
        }
        .upload-area:hover {
            background: #e3f2fd;
            border-color: #0056b3;
        }
        .upload-area.dragover {
            background: #bbdefb;
            border-color: #1a237e;
        }
        .preview-table {
            max-height: 400px;
            overflow-y: auto;
        }
        .progress-container {
            display: none;
        }
        .result-alert {
            display: none;
        }
    </style>
</head>

<body>
    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <img src="assets/NewLogo.svg" alt="Logo" height="40" class="me-2" onerror="this.src='https://via.placeholder.com/40x40/ffffff/1a237e?text=GIPS'">
                Gateway ICT Polytechnic Saapade - Bulk Upload
            </a>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php" onclick="showSection('certificateSection')">
                            <i class="fas fa-certificate me-1"></i>Certificate
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="bulk_upload.php"><i class="fas fa-users me-1"></i>Add students</a>

                    </li>
                    
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('printManagementSection')">
                            <i class="fas fa-print me-1"></i>Print Management
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('reportsSection')">
                            <i class="fas fa-chart-bar me-1"></i>Reports
                        </a>
                    </li>
                </ul>
            </div>
            <!-- <div class="navbar-nav ms-auto">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-arrow-left me-1"></i>Back to Certificates
                </a>
            </div> -->
        </div>
        </div>
    </nav>

    <div class="container">
        <div class="upload-container">
            <h2 class="text-center mb-4"><i class="fas fa-users me-2"></i>Bulk Student Data Upload</h2>
            
            <!-- Steps Guide -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="step-card">
                        <h5><i class="fas fa-download text-primary me-2"></i>Step 1</h5>
                        <p class="mb-0">Download the Excel template</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="step-card">
                        <h5><i class="fas fa-edit text-warning me-2"></i>Step 2</h5>
                        <p class="mb-0">Fill in student data following the format</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="step-card">
                        <h5><i class="fas fa-upload text-success me-2"></i>Step 3</h5>
                        <p class="mb-0">Upload the filled Excel file</p>
                    </div>
                </div>
            </div>

            <!-- Template Download -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="template-download" onclick="downloadTemplate()">
                        <h4><i class="fas fa-file-excel me-2"></i>Download Excel Template</h4>
                        <p class="mb-0">Click here to download the formatted Excel template</p>
                    </div>
                </div>
            </div>

            <!-- Upload Section -->
            <div class="row">
                <div class="col-md-6">
                    <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()">
                        <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                        <h4>Upload Excel File</h4>
                        <p class="text-muted">Click or drag & drop your Excel file here</p>
                        <small class="text-muted">Supported formats: .xlsx, .xls, .csv</small>
                        <input type="file" id="fileInput" accept=".xlsx,.xls,.csv" style="display: none;" onchange="handleFileSelect(event)">
                    </div>
                    
                    <!-- File Info -->
                    <div id="fileInfo" class="mt-3" style="display: none;">
                        <div class="alert alert-info">
                            <i class="fas fa-file me-2"></i>
                            <span id="fileName"></span>
                            <button type="button" class="btn-close float-end" onclick="clearFile()"></button>
                        </div>
                    </div>

                    <!-- Upload Button -->
                    <div class="d-grid gap-2 mt-3">
                        <button class="btn btn-success btn-lg" id="uploadBtn" onclick="uploadFile()" disabled>
                            <i class="fas fa-upload me-2"></i>Upload & Process Data
                        </button>
                    </div>
                </div>

                <div class="col-md-6">
                    <!-- Data Preview -->
                    <div id="previewSection" style="display: none;">
                        <h5><i class="fas fa-eye me-2"></i>Data Preview</h5>
                        <div class="preview-table">
                            <table class="table table-sm table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>Student ID</th>
                                        <th>Full Name</th>
                                        <th>Program</th>
                                        <th>Grade</th>
                                    </tr>
                                </thead>
                                <tbody id="previewTableBody">
                                    <!-- Preview data will be inserted here -->
                                </tbody>
                            </table>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted" id="previewCount"></small>
                        </div>
                    </div>

                    <!-- Instructions -->
                    <div id="instructions">
                        <div class="alert alert-warning">
                            <h6><i class="fas fa-info-circle me-2"></i>Important Instructions:</h6>
                            <ul class="mb-0">
                                <li>Use the downloaded template format</li>
                                <li>Student ID must be unique for each student</li>
                                <li>Required fields: Student ID, Full Name, Program, Department, Grade, Graduation Date</li>
                                <li>Grade must be one of: Distinction, Upper Credit, Lower Credit, Pass</li>
                                <li>Graduation date format: YYYY-MM-DD (e.g., 2024-07-15)</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Progress Bar -->
            <div class="progress-container mt-4" id="progressContainer">
                <div class="d-flex justify-content-between mb-2">
                    <span>Processing...</span>
                    <span id="progressText">0%</span>
                </div>
                <div class="progress">
                    <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                         role="progressbar" style="width: 0%"></div>
                </div>
            </div>

            <!-- Results -->
            <div class="result-alert mt-4" id="resultAlert"></div>
        </div>

        <!-- Recent Uploads -->
        <div class="upload-container mt-4">
            <h4><i class="fas fa-history me-2"></i>Recent Uploads</h4>
            <div id="recentUploads">
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading upload history...</p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        let selectedFile = null;
        let previewData = [];

        // Download template
        function downloadTemplate() {
            const templateData = [
                ['student_id', 'full_name', 'program', 'department', 'grade', 'graduation_date', 'photo_path', 'certificate_id'],
                ['GPS/ND/24/001', 'John Chika Okafor', 'Computer Science', 'School of Computing', 'Upper Credit', '2024-07-15', 'uploads/photos/student1.jpg', ''],
                ['GPS/ND/24/002', 'Maryam Adekunle', 'Electrical Engineering', 'School of Engineering', 'Distinction', '2024-07-15', 'uploads/photos/student2.jpg', ''],
                ['GPS/ND/24/003', 'David Okon', 'Business Administration', 'School of Management', 'Lower Credit', '2024-07-15', 'uploads/photos/student3.jpg', '']
            ];

            const ws = XLSX.utils.aoa_to_sheet(templateData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Student Template');
            
            XLSX.writeFile(wb, 'student_upload_template.xlsx');
        }

        // Handle file selection
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (!file) return;

            // Validate file type
            const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];
            if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls|csv)$/)) {
                alert('Please select a valid Excel or CSV file.');
                return;
            }

            selectedFile = file;
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileInfo').style.display = 'block';
            document.getElementById('uploadBtn').disabled = false;

            // Preview file contents
            previewFile(file);
        }

        // Preview file contents
        function previewFile(file) {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(firstSheet);

                previewData = jsonData;
                displayPreview(jsonData);
            };

            reader.readAsArrayBuffer(file);
        }

        // Display preview data
        function displayPreview(data) {
            const previewBody = document.getElementById('previewTableBody');
            previewBody.innerHTML = '';

            // Show first 5 rows for preview
            const previewRows = data.slice(0, 5);
            
            previewRows.forEach(row => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${row.student_id || ''}</td>
                    <td>${row.full_name || ''}</td>
                    <td>${row.program || ''}</td>
                    <td>${row.grade || ''}</td>
                `;
                previewBody.appendChild(tr);
            });

            document.getElementById('previewCount').textContent = 
                `Showing ${previewRows.length} of ${data.length} records`;
            document.getElementById('previewSection').style.display = 'block';
            document.getElementById('instructions').style.display = 'none';
        }

        // Upload and process file
        function uploadFile() {
            if (!selectedFile) return;

            const formData = new FormData();
            formData.append('file', selectedFile);

            // Show progress
            document.getElementById('progressContainer').style.display = 'block';
            updateProgress(0);

            fetch('process_bulk_upload.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                updateProgress(100);
                
                const resultAlert = document.getElementById('resultAlert');
                resultAlert.style.display = 'block';

                if (data.success) {
                    resultAlert.className = 'alert alert-success';
                    resultAlert.innerHTML = `
                        <h4><i class="fas fa-check-circle me-2"></i>Upload Successful!</h4>
                        <p><strong>${data.inserted}</strong> records inserted successfully</p>
                        <p><strong>${data.updated}</strong> records updated</p>
                        <p><strong>${data.errors}</strong> errors encountered</p>
                        ${data.error_messages ? `<div class="mt-2"><strong>Errors:</strong><br>${data.error_messages.join('<br>')}</div>` : ''}
                    `;
                } else {
                    resultAlert.className = 'alert alert-danger';
                    resultAlert.innerHTML = `
                        <h4><i class="fas fa-exclamation-triangle me-2"></i>Upload Failed!</h4>
                        <p>${data.message}</p>
                    `;
                }

                // Refresh recent uploads
                loadRecentUploads();
            })
            .catch(error => {
                console.error('Error:', error);
                const resultAlert = document.getElementById('resultAlert');
                resultAlert.style.display = 'block';
                resultAlert.className = 'alert alert-danger';
                resultAlert.innerHTML = `
                    <h4><i class="fas fa-exclamation-triangle me-2"></i>Upload Error!</h4>
                    <p>An error occurred while processing the file.</p>
                `;
            });
        }

        // Update progress bar
        function updateProgress(percent) {
            document.getElementById('progressBar').style.width = percent + '%';
            document.getElementById('progressText').textContent = percent + '%';
        }

        // Clear selected file
        function clearFile() {
            selectedFile = null;
            document.getElementById('fileInput').value = '';
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('uploadBtn').disabled = true;
            document.getElementById('previewSection').style.display = 'none';
            document.getElementById('instructions').style.display = 'block';
        }

        // Load recent uploads
        function loadRecentUploads() {
            fetch('get_upload_history.php')
                .then(response => response.json())
                .then(data => {
                    const container = document.getElementById('recentUploads');
                    
                    if (data.uploads && data.uploads.length > 0) {
                        let html = '<div class="table-responsive"><table class="table table-striped"><thead><tr><th>Date</th><th>Filename</th><th>Records</th><th>Status</th></tr></thead><tbody>';
                        
                        data.uploads.forEach(upload => {
                            html += `
                                <tr>
                                    <td>${upload.upload_date}</td>
                                    <td>${upload.filename}</td>
                                    <td>${upload.records_processed}</td>
                                    <td><span class="badge bg-${upload.status === 'success' ? 'success' : 'danger'}">${upload.status}</span></td>
                                </tr>
                            `;
                        });
                        
                        html += '</tbody></table></div>';
                        container.innerHTML = html;
                    } else {
                        container.innerHTML = '<div class="alert alert-info">No recent uploads found.</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading upload history:', error);
                    document.getElementById('recentUploads').innerHTML = 
                        '<div class="alert alert-danger">Error loading upload history.</div>';
                });
        }

        // Drag and drop functionality
        const uploadArea = document.getElementById('uploadArea');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            uploadArea.classList.add('dragover');
        }

        function unhighlight() {
            uploadArea.classList.remove('dragover');
        }

        uploadArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length) {
                document.getElementById('fileInput').files = files;
                handleFileSelect({ target: { files: files } });
            }
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            loadRecentUploads();
        });
    </script>
</body>
</html>