<?php
/**
 * ===================================================================================
 * Submit Work Page (for Students) - with Progress Bar
 * ===================================================================================
 *
 * File: submit_work.php
 * Location: /homework_portal/student/submit_work.php
 *
 * Purpose:
 * 1. Provides a functional and interactive page for students to upload assignments.
 * 2. Features a real-time progress bar for a better user experience on mobile.
 * 3. Handles server-side file validation and database recording.
 */

require_once '../config.php';

// --- Security Check & Initial Setup ---
if (!isset($_SESSION['student_id'])) {
    header('Location: ../login.php');
    exit();
}

$student_id = $_SESSION['student_id'];
$assignment_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$errors = [];
$success_message = '';

if ($assignment_id <= 0) {
    header('Location: dashboard.php');
    exit();
}

// --- Fetch Assignment Details for display ---
try {
    $stmt = $pdo->prepare("SELECT title, subject_id FROM assignments WHERE id = ?");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch();
    if (!$assignment) {
        header('Location: dashboard.php?error=Assignment not found.');
        exit();
    }
} catch (PDOException $e) {
    die("Database error fetching assignment details.");
}

// --- This part handles the AJAX file upload from the JavaScript ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['submission_file'])) {
    header('Content-Type: application/json');
    
    if ($_FILES['submission_file']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/submissions/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        
        $file_name = "sub_{$assignment_id}_student_{$student_id}_" . basename($_FILES['submission_file']['name']);
        $target_file = $upload_dir . $file_name;
        $db_path = 'uploads/submissions/' . $file_name;

        if (move_uploaded_file($_FILES['submission_file']['tmp_name'], $target_file)) {
            try {
                $check_stmt = $pdo->prepare("SELECT id FROM submissions WHERE assignment_id = ? AND student_id = ?");
                $check_stmt->execute([$assignment_id, $student_id]);
                if ($check_stmt->fetch()) {
                    $sql = "UPDATE submissions SET file_path = ?, submitted_at = NOW() WHERE assignment_id = ? AND student_id = ?";
                    $pdo->prepare($sql)->execute([$db_path, $assignment_id, $student_id]);
                } else {
                    $sql = "INSERT INTO submissions (assignment_id, student_id, file_path) VALUES (?, ?, ?)";
                    $pdo->prepare($sql)->execute([$assignment_id, $student_id, $db_path]);
                }
                echo json_encode(['success' => true, 'message' => 'File uploaded successfully!']);
            } catch (PDOException $e) {
                echo json_encode(['success' => false, 'message' => 'Database error.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Error moving uploaded file.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'File upload error.']);
    }
    exit(); // Stop script execution for AJAX requests
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Work - School Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f4f8; }
        .font-brand { font-family: 'Baloo 2', cursive; }
        .progress-bar-container { background-color: #e0e0e0; border-radius: 9999px; overflow: hidden; }
        .progress-bar { background-color: #26a69a; /* teal-500 */ height: 100%; width: 0%; border-radius: 9999px; transition: width 0.4s ease; }
    </style>
</head>
<body class="min-h-screen">
    <main class="max-w-2xl mx-auto py-8 px-4">
        <div class="bg-white p-8 rounded-2xl shadow-lg">
            <div class="text-center mb-6">
                 <h1 class="text-3xl font-bold font-brand text-gray-800">Submit Your Work</h1>
                 <p class="text-gray-500">For Assignment: <strong class="text-gray-700"><?php echo e($assignment['title']); ?></strong></p>
            </div>
            
            <div id="feedback-message" class="hidden p-4 my-4 text-sm rounded-lg"></div>

            <form id="upload-form" action="submit_work.php?id=<?php echo $assignment_id; ?>" method="POST" enctype="multipart/form-data" class="space-y-6">
                <div>
                    <label for="submission_file_input" class="block text-lg font-medium text-center text-gray-700">Choose your file</label>
                    <p class="text-center text-sm text-gray-500 mb-4">You can upload a photo, a scan, a PDF, or a Word document.</p>
                    <div id="drop-zone" class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                        <div class="space-y-1 text-center">
                            <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true"><path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /></svg>
                            <div class="flex text-sm text-gray-600">
                                <label for="submission_file_input" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500">
                                    <span>Upload a file</span>
                                    <input id="submission_file_input" name="submission_file" type="file" class="sr-only" required>
                                </label>
                                <p class="pl-1">or drag and drop</p>
                            </div>
                             <p id="file-name-display" class="text-sm text-gray-900 font-semibold"></p>
                        </div>
                    </div>
                </div>
                
                <!-- Progress Bar -->
                <div id="progress-container" class="hidden w-full progress-bar-container h-4">
                    <div id="progress-bar" class="progress-bar"></div>
                </div>

                <div class="text-center">
                    <button type="submit" id="submit-btn" class="w-full py-3 px-6 bg-teal-600 text-white font-bold text-lg rounded-xl shadow-lg hover:bg-teal-700 transition-transform hover:scale-105">Submit My Work</button>
                </div>
            </form>
             <div class="mt-4 text-center">
                <a href="view_subject.php?id=<?php echo e($assignment['subject_id']); ?>" id="back-link" class="text-sm text-cyan-700 hover:underline">Back to Subject</a>
            </div>
        </div>
    </main>

    <script>
        const uploadForm = document.getElementById('upload-form');
        const inputFile = document.getElementById('submission_file_input');
        const dropZone = document.getElementById('drop-zone');
        const progressBarContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const feedbackMessage = document.getElementById('feedback-message');
        const submitBtn = document.getElementById('submit-btn');
        const fileNameDisplay = document.getElementById('file-name-display');

        // Handle file selection
        inputFile.addEventListener('change', () => {
            if (inputFile.files.length > 0) {
                fileNameDisplay.textContent = inputFile.files[0].name;
            }
        });

        // Handle form submission with AJAX
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (inputFile.files.length === 0) {
                showFeedback('Please select a file first!', 'error');
                return;
            }

            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();

            xhr.open('POST', this.action, true);

            // Progress event
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressBarContainer.classList.remove('hidden');
                    progressBar.style.width = percentComplete + '%';
                }
            });

            // On successful upload
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        showFeedback('Great job! Your work has been submitted.', 'success');
                        submitBtn.disabled = true;
                        submitBtn.textContent = 'Submitted!';
                        submitBtn.classList.remove('bg-teal-600', 'hover:bg-teal-700');
                        submitBtn.classList.add('bg-green-500', 'cursor-not-allowed');
                    } else {
                        showFeedback(response.message || 'An unknown error occurred.', 'error');
                    }
                } else {
                    showFeedback('Upload failed. Please try again.', 'error');
                }
            };

            // On error
            xhr.onerror = function() {
                showFeedback('An error occurred during the transfer.', 'error');
            };

            submitBtn.textContent = 'Uploading...';
            submitBtn.disabled = true;
            xhr.send(formData);
        });

        function showFeedback(message, type) {
            feedbackMessage.textContent = message;
            feedbackMessage.classList.remove('hidden', 'bg-green-100', 'text-green-800', 'bg-red-100', 'text-red-800');
            if (type === 'success') {
                feedbackMessage.classList.add('bg-green-100', 'text-green-800');
            } else {
                feedbackMessage.classList.add('bg-red-100', 'text-red-800');
            }
        }
    </script>
</body>
</html>
