<?php include 'header.php'; ?>

<!-- Normal Sub Header -->
<?php include 'template-parts/sub-header-trainer.php'; ?>

<div class="uk-container">
    <div class="uk-grid uk-grid-medium" uk-grid>

        <!-- Sidebar Area -->
        <div class="uk-width-2-6@m uk-visible@m">
            <div class="sidebar-sticky" uk-sticky="offset: 20; bottom: true">
                <?php include 'trainer-sidebar.php'; ?>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="uk-width-expand@m">

            <div class="profile-container">

                <div class="profile-header">
                    <h2 class="uk-heading-divider">Certificates & Qualifications</h2>
                    <p class="uk-margin-small-top">Upload your professional certificates, training certifications, and relevant qualifications.</p>
                </div>

                <!-- Certificate Upload Section -->
                <div class="upload-container">
                    <label class="form-label" for="certificateInput">Profile Picture</label>
                    <div class="upload-area certificate-upload" id="certificateUpload">
                        <div class="upload-icon">
                            <span uk-icon="icon: upload; ratio: 1.6" class="uk-icon" aria-hidden="true"></span>
                        </div>
                        <div class="upload-text uk-margin-small-top">Upload New Certificates</div>
                        <div class="upload-subtext uk-text-muted">PDF, JPG, PNG files up to 5MB each (multiple files allowed)</div>
                    </div>
                    <input type="file" id="certificateInput" class="hidden" accept=".pdf,.jpg,.jpeg,.png" multiple>
                </div>

                <!-- Certificates Display - Initially Hidden -->
                <div class="certificates-grid uk-margin-medium hidden" id="certificatesContainer">
                    <!-- Certificates will be dynamically added here when uploaded -->
                </div>

                <!-- Certificate Requirements -->
                <div class="requirements-section uk-margin-medium">

                    <div class="profile-sub-header">
                        <h3>Certificate Requirements</h3>
                    </div>

                    <div class="requirements-content uk-padding-small uk-alret uk-alert-primary br-8">
                        <ul class="uk-margin-remove uk-list uk-list-decimal" role="list">
                            <li>All certificates must be clearly visible and readable</li>
                            <li>Include professional certifications, training certificates, and relevant qualifications</li>
                            <li>Certificates help build trust with potential clients</li>
                            <li>Admin approval required for new certificates</li>
                        </ul>
                    </div>
                </div>

                <!-- Update Pricing Button -->
                <div class="uk-margin-medium-top">
                    <button type="button" id="saveCertificatesBtn" class="uk-button uk-button-primary">
                        Save Changes
                    </button>
                </div>

            </div>

        </div>

    </div><!-- .uk-grid -->
</div><!-- .uk-container -->

<script>
    // Certificate upload functionality
    function setupCertificateUpload() {
        const uploadArea = document.getElementById('certificateUpload');
        const input = document.getElementById('certificateInput');

        uploadArea.addEventListener('click', () => input.click());

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleMultipleCertificateUpload(files);
            }
        });

        input.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleMultipleCertificateUpload(e.target.files);
            }
        });
    }

    function handleMultipleCertificateUpload(files) {
        let successCount = 0;
        let errorCount = 0;

        Array.from(files).forEach(file => {
            if (handleCertificateUpload(file)) {
                successCount++;
            } else {
                errorCount++;
            }
        });

        document.getElementById('certificateInput').value = '';

        if (files.length > 1) {
            let message = '';
            if (successCount > 0) {
                message += `${successCount} certificate(s) uploaded successfully.`;
            }
            if (errorCount > 0) {
                message += ` ${errorCount} file(s) failed to upload.`;
            }
            if (message) {
                UIkit.notification({
                    message: message,
                    status: successCount > 0 ? 'success' : 'warning',
                    pos: 'top-center',
                    timeout: 4000
                });
            }
        }
    }

    function handleCertificateUpload(file) {
        const allowedTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
        if (!allowedTypes.includes(file.type)) {
            UIkit.notification({
                message: `File "${file.name}" is not a valid format. Please upload only PDF, JPG, or PNG files.`,
                status: 'warning',
                pos: 'top-center',
                timeout: 4000
            });
            return false;
        }

        if (file.size > 5 * 1024 * 1024) {
            UIkit.notification({
                message: `File "${file.name}" is too large. File size must be less than 5MB.`,
                status: 'warning',
                pos: 'top-center',
                timeout: 4000
            });
            return false;
        }

        addCertificateToGrid(file.name, 'Just uploaded');
        return true;
    }

    function addCertificateToGrid(certificateName, uploadDate) {
        const container = document.getElementById('certificatesContainer');
        const certificateId = 'cert_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        const displayName = certificateName.replace(/\.[^/.]+$/, "");

        const certificateCard = document.createElement('div');
        certificateCard.className = 'certificate-card';
        certificateCard.setAttribute('data-certificate-id', certificateId);

        certificateCard.innerHTML = `
            <div class="certificate-content">
                <h4 class="certificate-title uk-card-title">${displayName}</h4>
                <p class="certificate-date uk-text-muted">${uploadDate}</p>
            </div>
            <div class="actions-btns">
                <button type="button" class="action-btn view-btn" title="View Certificate" onclick="viewCertificate('${certificateId}')">
                    <span uk-icon="icon: search; ratio: 0.8" class="uk-icon"></span>
                </button>
                <button type="button" class="action-btn delete-btn" title="Delete Certificate" onclick="deleteCertificate('${certificateId}')">
                    <span uk-icon="icon: trash; ratio: 0.8" class="uk-icon"></span>
                </button>
            </div>
        `;

        container.appendChild(certificateCard);
        container.classList.remove('hidden');
    }

    function viewCertificate(certificateId) {
        console.log('Viewing certificate:', certificateId);
    }

    function deleteCertificate(certificateId) {
        UIkit.notification({
            message: 'Certificate deleted successfully!',
            status: 'warning',
            pos: 'top-center',
            timeout: 3000
        });

        const certificateCard = document.querySelector(`[data-certificate-id="${certificateId}"]`);
        if (certificateCard) {
            certificateCard.remove();
            const container = document.getElementById('certificatesContainer');
            if (container.children.length === 0) {
                container.classList.add('hidden');
            }
        }
    }

    // Initialize on page load and add save button handler
    document.addEventListener('DOMContentLoaded', function() {
        setupCertificateUpload();

        // FIXED: Target the save button by its specific ID
        const saveButton = document.getElementById('saveCertificatesBtn');
        if (saveButton) {
            saveButton.addEventListener('click', function() {
                console.log('Save button clicked!'); // Debug line

                UIkit.notification({
                    message: 'Saving your certificates...',
                    status: 'primary',
                    pos: 'top-center',
                    timeout: 2000
                });

                setTimeout(() => {
                    UIkit.notification({
                        message: 'Certificates updated successfully!',
                        status: 'success',
                        pos: 'top-center',
                        timeout: 4000
                    });
                }, 1500);
            });
        } else {
            console.error('Save button not found!'); // Debug line
        }
    });
</script>

<?php include 'footer.php'; ?>