Path : /home/vishqocm/pcib.in/enroll/
File Upload :
Current File : //home/vishqocm/pcib.in/enroll/upload_documents.php

<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session
session_start();

// Include database configuration
require_once '../admin/database/db_config.php';

// If user is not logged in, redirect to login page
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Get application ID from URL parameter
$application_id = isset($_GET['application_id']) ? intval($_GET['application_id']) : 0;

// If application ID is not provided, redirect to courses page
if ($application_id <= 0) {
    header('Location: courses.php');
    exit;
}

// Get user ID
$user_id = $_SESSION['user_id'];

// Check if the application belongs to the current user
$application_query = "SELECT ea.*, c.title as course_title, c.image as course_image 
                      FROM enrollment_applications ea 
                      JOIN courses c ON ea.course_id = c.id 
                      WHERE ea.id = ? AND ea.user_id = ?";
$stmt = $conn->prepare($application_query);
$stmt->bind_param("ii", $application_id, $user_id);
$stmt->execute();
$application_result = $stmt->get_result();
$application = $application_result->fetch_assoc();

// If application not found or doesn't belong to the user, redirect
if (!$application) {
    header('Location: courses.php');
    exit;
}

// If application is already in payment_pending or completed status, redirect to payment page
if ($application['status'] === 'payment_pending' || $application['status'] === 'completed') {
    header("Location: payment.php?application_id=$application_id");
    exit;
}

// Get already uploaded documents for this application
$documents_query = "SELECT * FROM student_documents WHERE user_id = ? ORDER BY upload_date DESC";
$stmt = $conn->prepare($documents_query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$documents_result = $stmt->get_result();

// Count uploaded documents by type
$uploaded_documents = array();
while ($doc = $documents_result->fetch_assoc()) {
    $uploaded_documents[$doc['document_type']] = $doc;
}

// Calculate document completion percentage
$required_document_types = ['id_proof', 'educational_certificate', 'photograph'];
$total_required = count($required_document_types);
$uploaded_required = 0;

foreach ($required_document_types as $type) {
    if (isset($uploaded_documents[$type])) {
        $uploaded_required++;
    }
}

$completion_percentage = ($total_required > 0) ? round(($uploaded_required / $total_required) * 100) : 0;
$all_documents_uploaded = ($uploaded_required == $total_required);

// Reset result pointer for the document list display
$documents_result->data_seek(0);

// Define required document types
$document_types = [
    'id_proof' => 'ID Proof (Aadhaar/PAN/Passport)',
    'educational_certificate' => 'Educational Certificate',
    'photograph' => 'Recent Passport Size Photograph',
    'other' => 'Other Supporting Documents (Optional)'
];

// Process document upload
$error_message = '';
$success_message = '';

// Check for success parameter in URL
if (isset($_GET['success']) && $_GET['success'] == '1') {
    $success_message = "Document uploaded successfully.";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_document'])) {
    // Get form data
    $document_type = trim($_POST['document_type']);
    
    // Validate document type
    if (!array_key_exists($document_type, $document_types)) {
        $error_message = "Invalid document type selected.";
    } else {
        // Check if file was uploaded
        if (!isset($_FILES['document_file']) || $_FILES['document_file']['error'] === UPLOAD_ERR_NO_FILE) {
            $error_message = "Please select a file to upload.";
        } else {
            // Check for upload errors
            if ($_FILES['document_file']['error'] !== UPLOAD_ERR_OK) {
                $error_message = "Upload failed. Please try again.";
            } else {
                // Validate file size (max 5MB)
                if ($_FILES['document_file']['size'] > 5 * 1024 * 1024) {
                    $error_message = "File size exceeds 5MB limit.";
                } else {
                    // Validate file type (PDF, JPG, PNG)
                    $allowed_types = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'];
                    $file_info = finfo_open(FILEINFO_MIME_TYPE);
                    $mime_type = finfo_file($file_info, $_FILES['document_file']['tmp_name']);
                    finfo_close($file_info);
                    
                    if (!in_array($mime_type, $allowed_types)) {
                        $error_message = "Invalid file type. Only PDF, JPG, and PNG files are allowed.";
                    } else {
                        // Create directory if it doesn't exist
                        $upload_dir = '../uploads/student_documents/' . $user_id . '/';
                        if (!file_exists($upload_dir)) {
                            mkdir($upload_dir, 0777, true);
                        }
                        
                        // Generate unique filename
                        $file_extension = pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION);
                        $new_filename = $document_type . '_' . time() . '.' . $file_extension;
                        $target_file = $upload_dir . $new_filename;
                        
                        // Move uploaded file
                        if (move_uploaded_file($_FILES['document_file']['tmp_name'], $target_file)) {
                            // Insert into database
                            $document_query = "INSERT INTO student_documents (user_id, document_type, document_path, upload_date, status) VALUES (?, ?, ?, NOW(), 'pending')";
                            $stmt = $conn->prepare($document_query);
                            
                            // Ensure document_type is properly formatted
                            if (!array_key_exists($document_type, $document_types)) {
                                error_log("Invalid document type: $document_type");
                                $document_type = 'other'; // Fallback to 'other' if not recognized
                            }
                            
                            error_log("Inserting document: User ID: $user_id, Type: $document_type, Path: $target_file");
                            $stmt->bind_param("iss", $user_id, $document_type, $target_file);
                            
                            if ($stmt->execute()) {
                                $success_message = "Document uploaded successfully.";
                                
                                // Check if all required documents are uploaded
                                $required_docs = ['id_proof', 'educational_certificate', 'photograph'];
                                $all_required_uploaded = true;
                                
                                foreach ($required_docs as $req_doc) {
                                    $check_query = "SELECT COUNT(*) as count FROM student_documents WHERE user_id = ? AND document_type = ?";
                                    $stmt = $conn->prepare($check_query);
                                    $stmt->bind_param("is", $user_id, $req_doc);
                                    $stmt->execute();
                                    $check_result = $stmt->get_result()->fetch_assoc();
                                    
                                    if ($check_result['count'] == 0) {
                                        $all_required_uploaded = false;
                                        break;
                                    }
                                }
                                
                                // If all required documents are uploaded, update application status
                                if ($all_required_uploaded) {
                                    $update_query = "UPDATE enrollment_applications SET status = 'payment_pending' WHERE id = ?";
                                    $stmt = $conn->prepare($update_query);
                                    $stmt->bind_param("i", $application_id);
                                    $stmt->execute();
                                    
                                    // Redirect to payment page
                                    header("Location: payment.php?application_id=$application_id");
                                    exit;
                                }
                                
                                // Reload the page to refresh the document list
                                header("Location: upload_documents.php?application_id=$application_id&success=1");
                                exit;
                            } else {
                                $error_message = "Failed to save document information.";
                            }
                        } else {
                            $error_message = "Failed to upload document. Please try again.";
                        }
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Upload - <?php echo htmlspecialchars($application['course_title']); ?></title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Modern UI CSS -->
    <link rel="stylesheet" href="css/modern-ui.css">
    
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f8f9fa;
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        .logo-container {
            text-align: center;
            margin: 20px 0;
        }
        
        .logo-container img {
            max-height: 60px;
        }
        
        .logo-container h2 {
            color: white;
            margin: 10px 0;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        
        .return-link {
            position: absolute;
            top: 20px;
            left: 20px;
            color: white;
            text-decoration: none;
            z-index: 100;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            padding: 8px 15px;
            border-radius: 50px;
            font-weight: 500;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .return-link:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
            color: white;
        }
        
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 1;
            margin: 0 20px;
        }
        
        .step-number {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-bottom: 8px;
            color: white;
            border: 2px solid rgba(255, 255, 255, 0.3);
        }
        
        .step.active .step-number {
            background: #4e73df;
            border-color: white;
        }
        
        .step.completed .step-number {
            background: #1cc88a;
            border-color: white;
        }
        
        .step-title {
            font-size: 0.8rem;
            color: white;
            text-align: center;
        }
        
        .step-connector {
            position: absolute;
            top: 18px;
            height: 2px;
            background: rgba(255, 255, 255, 0.2);
            width: 100px;
            left: -60px;
            z-index: -1;
        }
        
        .step:first-child .step-connector {
            display: none;
        }

        .progress {
            height: 10px;
            border-radius: 5px;
            margin-bottom: 1rem;
        }

        .document-status {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 10px;
            background-color: #f8f9fa;
            box-shadow: 0 0 10px rgba(0,0,0,0.05);
        }

        .document-status .progress-info {
            flex-grow: 1;
        }

        .document-status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.85rem;
        }

        .document-status-badge.complete {
            background-color: #d1e7dd;
            color: #0f5132;
        }

        .document-status-badge.incomplete {
            background-color: #f8d7da;
            color: #842029;
        }

        .document-status-badge.partial {
            background-color: #fff3cd;
            color: #664d03;
        }

        .btn-proceed {
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        .btn-proceed:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0,0,0,0.15);
        }
    </style>
</head>
<body>

<!-- Return to Enrollment Link -->
<a href="enroll.php?course_id=<?php echo $application['course_id']; ?>" class="return-link">
    <i class="fas fa-arrow-left me-2"></i> Back to Enrollment
</a>

<!-- Logo Container -->
<div class="logo-container">
    <?php 
    // Get school settings from site_settings table
    $school_name = 'Popular Computer Institute';
    $school_logo = '../assets/img/logo.png';
    
    $site_settings_query = "SELECT setting_key, setting_value FROM site_settings WHERE setting_key IN ('site_name', 'site_logo')";
    try {
        $site_settings_result = $conn->query($site_settings_query);
        if ($site_settings_result && $site_settings_result->num_rows > 0) {
            while ($row = $site_settings_result->fetch_assoc()) {
                if ($row['setting_key'] == 'site_name') {
                    $school_name = $row['setting_value'];
                } else if ($row['setting_key'] == 'site_logo') {
                    $school_logo = $row['setting_value'];
                    // Add path prefix if not already present
                    if ($school_logo && substr($school_logo, 0, 1) !== '/' && substr($school_logo, 0, 4) !== 'http') {
                        $school_logo = '../' . $school_logo;
                    }
                }
            }
        }
    } catch (Exception $e) {
        // Silently handle the error - use default values
    }
    ?>
    <img src="<?php echo $school_logo; ?>" alt="<?php echo htmlspecialchars($school_name); ?>" class="logo" onerror="this.src='../assets/img/logo.png'; this.onerror='';">
    <h2><?php echo htmlspecialchars($school_name); ?></h2>
</div>

<!-- Step Indicator -->
<div class="step-indicator container">
    <div class="step completed">
        <div class="step-number"><i class="fas fa-check"></i></div>
        <div class="step-title">Application</div>
    </div>
    <div class="step active">
        <div class="step-connector"></div>
        <div class="step-number">2</div>
        <div class="step-title">Documents</div>
    </div>
    <div class="step">
        <div class="step-connector"></div>
        <div class="step-number">3</div>
        <div class="step-title">Payment</div>
    </div>
    <div class="step">
        <div class="step-connector"></div>
        <div class="step-number">4</div>
        <div class="step-title">Confirmation</div>
    </div>
</div>

<!-- Animated Background -->
<div class="animated-bg">
    <div class="animated-shape shape-1"></div>
    <div class="animated-shape shape-2"></div>
    <div class="animated-shape shape-3"></div>
    <div class="animated-shape shape-4"></div>
</div>

<!-- Begin Page Content -->
<div class="container mt-5 mb-5">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            <div class="glass-card shadow fade-in">
                <div class="modern-card-header">
                    <div class="glow-effect glow-1"></div>
                    <div class="glow-effect glow-2"></div>
                    <div class="modern-card-header-content">
                        <i class="fas fa-file-upload"></i>
                    <h4 class="mb-0">Document Upload</h4>
                    </div>
                    <span class="floating-label">Step 2</span>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-8">
                            <h5 class="text-white">Course: <?php echo htmlspecialchars($application['course_title']); ?></h5>
                            <p class="text-white-50">Application Status: 
                                <span class="badge animated-badge" style="background-color: <?php echo ($application['status'] === 'pending') ? '#ffc107' : '#28a745'; ?>; color: #fff;">
                                <?php echo ucfirst($application['status']); ?>
                                </span>
                            </p>
                            <p class="mb-0 text-white-50">Please upload the required documents to proceed with your enrollment.</p>
                        </div>
                        <div class="col-md-4 text-center">
                            <img src="<?php echo $application['course_image'] ? '../' . $application['course_image'] : '../assets/img/course-placeholder.jpg'; ?>" 
                                 class="img-fluid rounded bounce-in" alt="<?php echo htmlspecialchars($application['course_title']); ?>"
                                 style="max-height: 120px; border: 3px solid rgba(255,255,255,0.2);">
                        </div>
                    </div>
                    
                    <!-- Document Status -->
                    <div class="container">
                        <div class="document-status">
                            <div class="progress-info">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h5 class="mb-0">Document Completion</h5>
                                    <span class="document-status-badge <?php echo $all_documents_uploaded ? 'complete' : ($uploaded_required > 0 ? 'partial' : 'incomplete'); ?>">
                                        <?php 
                                        if ($all_documents_uploaded) {
                                            echo '<i class="fas fa-check-circle me-1"></i> Complete';
                                        } elseif ($uploaded_required > 0) {
                                            echo '<i class="fas fa-hourglass-half me-1"></i> Partially Complete';
                                        } else {
                                            echo '<i class="fas fa-times-circle me-1"></i> Incomplete';
                                        }
                                        ?>
                                    </span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $completion_percentage; ?>%" 
                                         aria-valuenow="<?php echo $completion_percentage; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                                <div class="text-muted small">
                                    <?php echo $uploaded_required; ?> of <?php echo $total_required; ?> required documents uploaded
                                </div>
                            </div>
                            <?php if ($all_documents_uploaded): ?>
                            <div class="ms-3">
                                <a href="payment.php?application_id=<?php echo $application_id; ?>" class="btn btn-primary btn-proceed">
                                    <i class="fas fa-credit-card me-2"></i> Proceed to Payment
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <?php if ($error_message): ?>
                        <div class="alert alert-danger"><?php echo $error_message; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($success_message): ?>
                        <div class="alert alert-success"><?php echo $success_message; ?></div>
                    <?php endif; ?>
                    
                    <!-- Document Upload Form -->
                    <form method="post" enctype="multipart/form-data" class="mb-4 fade-in" id="documentUploadForm">
                        <input type="hidden" name="application_id" value="<?php echo $application_id; ?>">
                        <div class="p-4 mb-4 rounded" style="background: rgba(255, 255, 255, 0.1);">
                            <h5 class="text-white mb-4"><i class="fas fa-upload me-2"></i>Upload New Document</h5>
                            
                            <div class="row mb-3">
                            <div class="col-md-6">
                                    <label for="document_type" class="form-label text-white">Document Type <span class="text-danger">*</span></label>
                                    <select class="form-select" id="document_type" name="document_type" required>
                                        <option value="">Select Document Type</option>
                                        <?php foreach($document_types as $value => $label): ?>
                                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                            </div>
                            <div class="col-md-6">
                                    <label for="document_file" class="form-label text-white">Document File <span class="text-danger">*</span></label>
                                    <input type="file" class="form-control" id="document_file" name="document_file" required>
                                    <div class="form-text text-white-50">Accepted formats: PDF, JPG, PNG (Max size: 5MB)</div>
                                </div>
                            </div>
                            
                            <!-- Upload Progress Bar (initially hidden) -->
                            <div id="uploadProgressContainer" class="mb-3" style="display: none;">
                                <div class="progress" style="height: 25px; background: rgba(0,0,0,0.2);">
                                    <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                                         role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" 
                                         style="width: 0%">0%</div>
                                </div>
                                <div id="uploadStatusText" class="mt-2 text-center text-white"></div>
                        </div>
                        
                        <div class="text-end">
                                <button type="submit" name="upload_document" id="uploadButton" class="btn btn-3d btn-primary-3d">
                                    <i class="fas fa-cloud-upload-alt me-2"></i>Upload Document
                            </button>
                            </div>
                        </div>
                    </form>
                    
                    <!-- Uploaded Documents -->
                    <div class="p-4 rounded" style="background: rgba(255, 255, 255, 0.1);">
                        <h5 class="text-white mb-4"><i class="fas fa-file-alt me-2"></i>Uploaded Documents</h5>
                        
                        <div id="documentListContainer">
                        <?php if ($documents_result && $documents_result->num_rows > 0): ?>
                    <div class="table-responsive">
                                <table class="table table-hover" style="color: white; border-color: rgba(255,255,255,0.1);">
                                    <thead>
                                <tr>
                                    <th>Document Type</th>
                                    <th>Upload Date</th>
                                    <th>Status</th>
                                            <th>File</th>
                                </tr>
                            </thead>
                            <tbody>
                                        <?php while ($document = $documents_result->fetch_assoc()): ?>
                                    <tr>
                                                    <td><?php echo $document_types[$document['document_type']] ?? ucfirst(str_replace('_', ' ', $document['document_type'])); ?></td>
                                        <td><?php echo date('M d, Y h:i A', strtotime($document['upload_date'])); ?></td>
                                        <td>
                                                    <span class="badge <?php echo ($document['status'] === 'verified') ? 'bg-success' : (($document['status'] === 'rejected') ? 'bg-danger' : 'bg-warning'); ?>">
                                                <?php echo ucfirst($document['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                                    <a href="<?php echo $document['document_path']; ?>" target="_blank" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-eye me-1"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                        <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                        <?php else: ?>
                            <div class="alert" style="background: rgba(255, 255, 255, 0.1); color: white;">
                                <i class="fas fa-info-circle me-2"></i>
                                No documents uploaded yet. Please upload the required documents above.
                    </div>
                        <?php endif; ?>
                        </div>
                        
                        <div class="text-center mt-4">
                            <a href="../course-details.php?id=<?php echo $application['course_id']; ?>" class="btn btn-3d btn-outline-3d">
                                <i class="fas fa-arrow-left me-2"></i>Back to Course Details
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Add 3D hover effect to buttons
    const buttons = document.querySelectorAll('.btn-3d');
    
    buttons.forEach(button => {
        button.addEventListener('mousemove', function(e) {
            const rect = this.getBoundingClientRect();
            const x = (e.clientX - rect.left) / this.offsetWidth;
            const y = (e.clientY - rect.top) / this.offsetHeight;
            
            const rotateY = 5 * (0.5 - x);
            const rotateX = 5 * (y - 0.5);
            
            this.style.transform = `perspective(500px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.05, 1.05, 1.05)`;
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = '';
        });
    });
    
    // Set up document type field to highlight based on required vs optional
    const documentTypeSelect = document.getElementById('document_type');
    if (documentTypeSelect) {
        documentTypeSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const isOptional = selectedOption.value === 'other';
            
            if (isOptional) {
                this.classList.add('is-optional');
                this.classList.remove('is-required');
            } else {
                this.classList.add('is-required');
                this.classList.remove('is-optional');
            }
        });
    }
    
    // File input preview and validation
    const fileInput = document.getElementById('document_file');
    if (fileInput) {
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                const fileSize = this.files[0].size / 1024 / 1024; // in MB
                if (fileSize > 5) {
                    alert('File size exceeds 5MB. Please select a smaller file.');
                    this.value = ''; // Clear the input
                    return;
                }
                
                // Show file name in upload button
                const fileName = this.files[0].name;
                const uploadBtn = document.getElementById('uploadButton');
                if (uploadBtn) {
                    uploadBtn.innerHTML = `<i class="fas fa-cloud-upload-alt me-2"></i>Upload ${fileName}`;
                }
            }
        });
    }
    
    // Real-time document upload with progress indicator
    const documentForm = document.getElementById('documentUploadForm');
    if (documentForm) {
        documentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Validate form
            if (!documentForm.checkValidity()) {
                documentForm.reportValidity();
                return;
            }
            
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            
            // Get UI elements
            const uploadButton = document.getElementById('uploadButton');
            const progressContainer = document.getElementById('uploadProgressContainer');
            const progressBar = document.getElementById('uploadProgressBar');
            const statusText = document.getElementById('uploadStatusText');
            
            // Show progress bar and disable button
            progressContainer.style.display = 'block';
            uploadButton.disabled = true;
            uploadButton.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Preparing Upload...';
            
            // Set up XHR
            xhr.open('POST', 'ajax/upload_document.php', true);
            
            // Upload progress event
            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percentComplete + '%';
                    progressBar.textContent = percentComplete + '%';
                    progressBar.setAttribute('aria-valuenow', percentComplete);
                    
                    if (percentComplete < 100) {
                        statusText.textContent = 'Uploading document...';
                    } else {
                        statusText.textContent = 'Processing document...';
                    }
                }
            };
            
            // Upload complete
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        
                        if (response.success) {
                            // Update UI for success
                            progressBar.classList.remove('progress-bar-animated');
                            progressBar.classList.add('bg-success');
                            statusText.textContent = 'Document uploaded successfully!';
                            
                            // Show success message
                            addNotification('success', 'Document uploaded successfully.');
                            
                            // Update document list and completion status
                            refreshDocumentList();
                            
                            // If all documents are uploaded and payment is ready, offer redirect
                            if (response.all_documents_uploaded && response.redirect_to_payment) {
                            setTimeout(() => {
                                    const shouldRedirect = confirm('All required documents have been uploaded. Would you like to proceed to payment?');
                                    if (shouldRedirect) {
                                        window.location.href = response.payment_url;
                                    } else {
                                        // Reset form after confirmation
                                        resetUploadForm();
                                    }
                                }, 1000);
                            } else {
                                // Reset form after short delay
                                setTimeout(resetUploadForm, 1500);
                            }
                        } else {
                            // Update UI for error
                            progressBar.classList.remove('progress-bar-animated');
                            progressBar.classList.add('bg-danger');
                            statusText.textContent = 'Error: ' + response.message;
                            
                            // Show error message
                            addNotification('danger', 'Error: ' + response.message);
                            
                            // Re-enable button after short delay
                            setTimeout(() => {
                                progressContainer.style.display = 'none';
                                uploadButton.disabled = false;
                                uploadButton.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Try Again';
                                progressBar.classList.remove('bg-danger');
                                progressBar.classList.add('progress-bar-animated');
                                progressBar.style.width = '0%';
                                progressBar.textContent = '0%';
                                progressBar.setAttribute('aria-valuenow', 0);
                            }, 2000);
                        }
                    } catch (e) {
                        console.error('Error parsing response:', e);
                        console.error('Raw response:', xhr.responseText);
                        statusText.textContent = 'Error: Invalid server response';
                        
                        // Show error message
                        addNotification('danger', 'Error: Invalid server response');
                        
                        // Re-enable button
                        uploadButton.disabled = false;
                        uploadButton.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Try Again';
                    }
                } else {
                    // Handle HTTP errors
                    progressBar.classList.remove('progress-bar-animated');
                    progressBar.classList.add('bg-danger');
                    statusText.textContent = 'Error: Server returned status ' + xhr.status;
                    
                    // Show error message
                    addNotification('danger', 'Error: Server returned status ' + xhr.status);
                    
                    // Re-enable button
                    uploadButton.disabled = false;
                    uploadButton.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Try Again';
                }
            };
            
            // Handle network errors
            xhr.onerror = function() {
                progressBar.classList.remove('progress-bar-animated');
                progressBar.classList.add('bg-danger');
                statusText.textContent = 'Network error occurred. Please try again.';
                
                // Show error message
                addNotification('danger', 'Network error occurred. Please try again.');
                
                // Re-enable button
                uploadButton.disabled = false;
                uploadButton.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Try Again';
            };
            
            // Send the form data
            xhr.send(formData);
        });
    }
    
    // Function to reset the upload form
    function resetUploadForm() {
        const uploadButton = document.getElementById('uploadButton');
        const progressContainer = document.getElementById('uploadProgressContainer');
        const progressBar = document.getElementById('uploadProgressBar');
        const documentForm = document.getElementById('documentUploadForm');
        
        documentForm.reset();
        progressContainer.style.display = 'none';
        uploadButton.disabled = false;
        uploadButton.innerHTML = '<i class="fas fa-cloud-upload-alt me-2"></i>Upload Document';
        progressBar.classList.remove('bg-success', 'bg-danger');
        progressBar.classList.add('progress-bar-animated');
        progressBar.style.width = '0%';
        progressBar.textContent = '0%';
        progressBar.setAttribute('aria-valuenow', 0);
    }
    
    // Function to add a notification message
    function addNotification(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        
        // Find where to insert the notification
        const formElement = document.getElementById('documentUploadForm');
        formElement.parentNode.insertBefore(alertDiv, formElement);
        
        // Auto dismiss after 5 seconds
            setTimeout(() => {
            alertDiv.classList.remove('show');
            setTimeout(() => alertDiv.remove(), 150);
        }, 5000);
    }
    
    // Function to refresh document list
    function refreshDocumentList() {
        const documentListContainer = document.getElementById('documentListContainer');
        const documentProgressBar = document.querySelector('.progress-bar[role="progressbar"]');
        const documentCountElements = document.querySelectorAll('.document-status .text-muted small');
        
        fetch(`ajax/check_document_status.php?application_id=<?php echo $application_id; ?>`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update document list
                    if (documentListContainer) {
                        documentListContainer.innerHTML = data.document_html;
                    }
                    
                    // Update progress bar
                    if (documentProgressBar) {
                        documentProgressBar.style.width = data.completion_percentage + '%';
                        documentProgressBar.setAttribute('aria-valuenow', data.completion_percentage);
                    }
                    
                    // Update document count
                    if (documentCountElements.length > 0) {
                        documentCountElements[0].textContent = `${data.uploaded_required} of ${data.total_required} required documents uploaded`;
                    }
                    
                    // If all required documents are uploaded, update UI
                    if (data.all_documents_uploaded) {
                        const statusBadge = document.querySelector('.document-status-badge');
                        if (statusBadge) {
                            statusBadge.className = 'document-status-badge complete';
                            statusBadge.innerHTML = '<i class="fas fa-check-circle me-1"></i> Complete';
                        }
                        
                        // Add proceed to payment button if not already there
                        const proceedButtonContainer = document.querySelector('.document-status .ms-3');
                        if (!proceedButtonContainer) {
                            const statusContainer = document.querySelector('.document-status');
                            if (statusContainer) {
                                const buttonDiv = document.createElement('div');
                                buttonDiv.className = 'ms-3';
                                buttonDiv.innerHTML = `
                                    <a href="payment.php?application_id=<?php echo $application_id; ?>" class="btn btn-primary btn-proceed">
                                        <i class="fas fa-credit-card me-2"></i> Proceed to Payment
                                    </a>
                                `;
                                statusContainer.appendChild(buttonDiv);
                                
                                // Add animation effect
                                buttonDiv.classList.add('animate__animated', 'animate__bounceIn');
                            }
                        }
                    }
                }
            })
            .catch(error => console.error('Error refreshing document list:', error));
    }
    
    // Set up periodic refresh of document status
    const statusRefreshInterval = setInterval(refreshDocumentList, 30000); // Every 30 seconds
    
    // Add animation library
    const animateCSSLink = document.createElement('link');
    animateCSSLink.rel = 'stylesheet';
    animateCSSLink.href = 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css';
    document.head.appendChild(animateCSSLink);
});
</script>

<!-- Bootstrap JS Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>