<?php
session_start();
require_once('../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'student') {
    header("Location: login.php");
    exit();
}

include('../header/header.php');

$student_id = $_SESSION['user_id'];
$assignment_id = $_GET['id'] ?? null;

if (!$assignment_id) {
    header("Location: assignments.php");
    exit();
}

// Fetch assignment details
$stmt = $pdo->prepare("
    SELECT a.*, c.course_name 
    FROM assignments a 
    JOIN courses c ON a.course_id = c.id 
    JOIN enrollments e ON c.id = e.course_id
    WHERE a.id = ? AND e.student_id = ? AND e.status = 'enrolled'
");
$stmt->execute([$assignment_id, $student_id]);
$assignment = $stmt->fetch();

if (!$assignment) {
    header("Location: assignments.php");
    exit();
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['submission_file'])) {
    $file = $_FILES['submission_file'];
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];
    
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $allowed = ['pdf', 'doc', 'docx', 'txt', 'zip', 'zip', 'rar'];

    if (in_array($file_ext, $allowed)) {
        if ($file_error === 0) {
            if ($file_size <= 10000000) { // 10MB limit
                $new_file_name = "submission_" . $assignment_id . "_" . $student_id . "_" . uniqid() . "." . $file_ext;
                $file_destination = '../uploads/submissions/' . $new_file_name;

                // Create submissions directory if it doesn't exist
                if (!is_dir('../uploads/submissions')) {
                    mkdir('../uploads/submissions', 0777, true);
                }

                if (move_uploaded_file($file_tmp, $file_destination)) {
                    // Check if record exists
                    $stmt = $pdo->prepare("SELECT id FROM submissions WHERE assignment_id = ? AND student_id = ?");
                    $stmt->execute([$assignment_id, $student_id]);
                    $existing = $stmt->fetch();

                    if ($existing) {
                        $stmt = $pdo->prepare("UPDATE submissions SET file_path = ?, status = 'submitted', submitted_at = CURRENT_TIMESTAMP WHERE id = ?");
                        $stmt->execute([$new_file_name, $existing['id']]);
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO submissions (assignment_id, student_id, file_path, status, submitted_at) VALUES (?, ?, ?, 'submitted', CURRENT_TIMESTAMP)");
                        $stmt->execute([$assignment_id, $student_id, $new_file_name]);
                    }
                    $success = "Your assignment has been submitted successfully!";
                } else {
                    $error = "Failed to move uploaded file.";
                }
            } else {
                $error = "File is too large (max 10MB).";
            }
        } else {
            $error = "Error uploading file.";
        }
    } else {
        $error = "Invalid file type. Allowed: PDF, DOC, DOCX, TXT, ZIP, RAR.";
    }
}
?>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-sm border-0">
                <div class="card-body p-5">
                    <div class="mb-4">
                        <a href="assignments.php" class="text-decoration-none small"><i class="fas fa-arrow-left me-1"></i> Back to Assignments</a>
                    </div>
                    <h2 class="fw-bold mb-2">Submit Assignment</h2>
                    <p class="text-primary fw-bold mb-4"><?php echo htmlspecialchars($assignment['course_name']); ?>: <?php echo htmlspecialchars($assignment['title']); ?></p>
                    
                    <div class="bg-light p-4 rounded mb-4">
                        <h6 class="fw-bold"><i class="fas fa-info-circle me-2"></i>Instructions:</h6>
                        <p class="text-muted small mb-0"><?php echo nl2br(htmlspecialchars($assignment['description'])); ?></p>
                        <hr>
                        <p class="text-danger small mb-0 fw-bold">Due Date: <?php echo date('M d, Y H:i', strtotime($assignment['due_date'])); ?></p>
                    </div>

                    <?php if($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>

                    <?php if($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            <div class="mt-3">
                                <a href="assignments.php" class="btn btn-primary btn-sm">Return to Assignments</a>
                            </div>
                        </div>
                    <?php else: ?>
                        <form action="submit_assignment.php?id=<?php echo $assignment_id; ?>" method="POST" enctype="multipart/form-data">
                            <div class="mb-4">
                                <label class="form-label fw-bold">Upload Your Work</label>
                                <div class="upload-zone p-5 border-2 border-dashed rounded text-center bg-white" style="border: 2px dashed #dee2e6;">
                                    <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                    <input type="file" name="submission_file" class="form-control" required>
                                    <p class="text-muted small mt-2">Accepted formats: PDF, Word, TXT, ZIP (Max 10MB)</p>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 py-3 fw-bold shadow-sm">Submit Assignment</button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('../footer/footer.php'); ?>
