<?php //error_reporting(0); ?>
<?php    session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php include '../admin/includes/styles.php'; ?>
    <style>

        .assignment-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .info-box {
            padding: 15px;
            background: #f8f9fa;
            border-left: 4px solid #007bff;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .alert-overdue {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .submission-area {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        .file-upload-area {
            border: 2px dashed #007bff;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            background: #fff;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-upload-area:hover {
            background: #f8f9fa;
            border-color: #0056b3;
        }
        .file-upload-area.dragover {
            background: #e7f3ff;
            border-color: #0056b3;
        }
        .uploaded-file {
            padding: 10px;
            background: #fff;
            border-left: 3px solid #28a745;
            margin: 5px 0;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .submission-display {
            padding: 20px;
            background: #fff;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin: 20px 0;
        }
        .grade-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 10px;
            text-align: center;
            margin: 20px 0;
        }
        .grade-number {
            font-size: 48px;
            font-weight: bold;
        }
        .feedback-box {
            padding: 20px;
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            border-radius: 4px;
            margin: 20px 0;
        }
        .fa-eye{
            background-color: transparent;
        }
    </style>



    <?php
    if(isset($_SESSION['student'])){

    require_once '../admin/Classes/Assignment.php';
    $assignment_mgr = new Assignment();

    if (!isset($_GET['id'])) {
        header('Location: assignments');
        exit();
    }

    $assignment_id = (int)$_GET['id'];
    $assignment = $assignment_mgr->getAssignmentById($assignment_id);

    if (!$assignment) {
        header('Location: assignments');
        exit();
    }

    // Get student ID
    $sql = "SELECT studentID, name, classesID, sectionid FROM student WHERE username = :username";
    $conn->query($sql);
    $conn->bind(':username', $_SESSION['student']);
    $student = $conn->fetchSingle();

    if (!$student) {
        header("Location: $student_login_link");
        exit();
    }

    $student_id = $student->studentID;


    // Verify student has access (same class and section)
    if ($assignment->class_id != $student->classesID || $assignment->section_id != $student->sectionid) {
        header('Location: assignments');
        exit();
    }

    // Get student's submission if exists
    $sql = "SELECT * FROM assignment_submissions WHERE assignment_id = :assignment_id AND student_id = :student_id";
    $conn->query($sql);
    $conn->bind(':assignment_id', $assignment_id);
    $conn->bind(':student_id', $student_id);
    $submission = $conn->fetchSingle();

    // Check if overdue
    $now = new DateTime();
    $due_date = new DateTime($assignment->due_date);
    $is_overdue = $now > $due_date;
    $can_submit = !$is_overdue || ($assignment->allow_late_submission && $is_overdue);

    ?>

    <title><?php echo htmlspecialchars($assignment->title); ?> | <?php echo $school_name; ?></title>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"> View Assignment </h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->student_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item"><a href="<?php echo $conn->student_url(); ?>assignments">Assignments</a></li>
                            <li class="breadcrumb-item active">Assignments </li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <!-- Assignment Header -->
                <div class="assignment-header">
                    <h2><?php echo htmlspecialchars($assignment->title); ?></h2>
                    <p class="mb-0"><strong>Subject:</strong> <?php echo htmlspecialchars($assignment->subject_name); ?></p>
                    <p class="mb-0"><strong>Type:</strong> <?php echo ucfirst($assignment->assignment_type); ?> | <strong>Total Marks:</strong> <?php echo $assignment->total_marks; ?></p>
                </div>

                <?php if ($is_overdue && !$submission && !$can_submit): ?>
                    <div class="alert-overdue">
                        <h5><i class="fas fa-exclamation-triangle"></i> Assignment Overdue</h5>
                        <p class="mb-0">This assignment was due on <?php echo date('F d, Y \a\t h:i A', strtotime($assignment->due_date)); ?>. Late submissions are not allowed.</p>
                    </div>
                <?php endif; ?>

                <?php if ($is_overdue && !$submission && $can_submit): ?>
                    <div class="alert alert-warning">
                        <h5><i class="fas fa-exclamation-circle"></i> Late Submission</h5>
                        <p class="mb-0">This assignment is overdue, but late submissions are allowed for <?php echo $assignment->late_submission_days; ?> days. Your submission will be marked as late.</p>
                    </div>
                <?php endif; ?>

                <div class="row">
                    <div class="col-lg-8">

                        <!-- Assignment Details -->
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">Assignment Information</h3>
                            </div>
                            <div class="card-body">

                                <?php if ($assignment->description): ?>
                                    <div class="info-box">
                                        <strong>Description</strong><br>
                                        <?php echo nl2br(htmlspecialchars($assignment->description)); ?>
                                    </div>
                                <?php endif; ?>

                                <div class="info-box">
                                    <strong>Instructions</strong><br>
                                    <?php echo nl2br(htmlspecialchars($assignment->instructions)); ?>
                                </div>

                                <?php if ($assignment->attachment_url): ?>
                                    <div class="info-box">
                                        <strong>Assignment Materials</strong><br>
                                        <a href="<?php echo $conn->main_url() . $assignment->attachment_url; ?>" target="_blank" class="btn btn-sm btn-success mt-2">
                                            <i class="fas fa-download"></i> Download Attachment
                                        </a>
                                    </div>
                                <?php endif; ?>

                            </div>
                        </div>

                        <!-- Submission Section -->
                        <?php if ($submission && $submission->is_graded): ?>
                            <!-- Show Grade -->
                            <div class="card mt-3">
                                <div class="card-header bg-success">
                                    <h3 class="card-title text-white">Your Grade</h3>
                                </div>
                                <div class="card-body">
                                    <div class="grade-card">
                                        <div class="grade-number"><?php echo $submission->marks_obtained; ?> / <?php echo $assignment->total_marks; ?></div>
                                        <h4>Grade: <?php echo $submission->grade; ?> (<?php echo number_format($submission->percentage, 1); ?>%)</h4>
                                        <p class="mb-0">Graded by: <?php echo htmlspecialchars($submission->graded_by); ?></p>
                                        <small>on <?php echo date('M d, Y \a\t h:i A', strtotime($submission->graded_at)); ?></small>
                                    </div>

                                    <?php if ($submission->teacher_feedback): ?>
                                        <div class="feedback-box">
                                            <strong><i class="fas fa-comment"></i> Teacher's Feedback</strong><br>
                                            <?php echo nl2br(htmlspecialchars($submission->teacher_feedback)); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                        <?php elseif ($submission): ?>
                            <!-- Show Submission -->
                            <div class="card mt-3">
                                <div class="card-header bg-info">
                                    <h3 class="card-title text-white">Your Submission</h3>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-success">
                                        <i class="fas fa-check-circle"></i> You have submitted this assignment on <?php echo date('M d, Y \a\t h:i A', strtotime($submission->submitted_at)); ?>
                                        <?php if ($submission->submission_status == 'late_submitted'): ?>
                                            <br><span class="badge badge-warning mt-2">Late Submission</span>
                                        <?php endif; ?>
                                    </div>

                                    <?php if ($submission->submission_text): ?>
                                        <div class="submission-display">
                                            <strong>Submitted Text:</strong><br>
                                            <?php echo nl2br(htmlspecialchars($submission->submission_text)); ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($submission->submission_file): ?>
                                        <div class="submission-display">
                                            <strong>Submitted File:</strong><br>
                                            <a href="<?php echo $conn->main_url() . $submission->submission_file; ?>" target="_blank" class="btn btn-success mt-2">
                                                <i class="fas fa-download"></i> Download Your Submission
                                            </a>
                                        </div>
                                    <?php endif; ?>

                                    <?php
                                    $files = $assignment_mgr->getSubmissionFiles($submission->id);
                                    if (!empty($files)):
                                        ?>
                                        <div class="submission-display">
                                            <strong>Submitted Files (<?php echo count($files); ?>):</strong><br>
                                            <?php foreach ($files as $file): ?>
                                                <a href="<?php echo $conn->main_url() . $file->file_path; ?>" target="_blank" class="uploaded-file">
                                                    <span><i class="fas fa-file"></i> <?php echo htmlspecialchars($file->file_name); ?></span>
                                                    <span class="text-muted small"><?php echo $file->file_size; ?></span>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <div class="alert alert-info mt-3">
                                        <i class="fas fa-info-circle"></i> Your submission is being graded. You'll be notified when it's ready.
                                    </div>
                                </div>
                            </div>

                        <?php elseif ($can_submit): ?>
                            <!-- Show Submission Form -->
                            <div class="card mt-3">
                                <div class="card-header bg-primary">
                                    <h3 class="card-title text-white">Submit Your Assignment</h3>
                                </div>
                                <div class="card-body">
                                    <form id="submission-form" method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="assignment_id" value="<?php echo $assignment_id; ?>">
                                        <input type="hidden" name="student_id" value="<?php echo $student_id; ?>">

                                        <div class="submission-area">
                                            <div class="form-group">
                                                <label for="submission_text">Your Answer/Response</label>
                                                <textarea class="form-control" id="submission_text" name="submission_text" rows="8"
                                                          placeholder="Type your answer here..."></textarea>
                                                <small class="form-text text-muted">Provide your detailed response to the assignment</small>
                                            </div>

                                            <div class="form-group">
                                                <label>Upload Files (Optional)</label>
                                                <div class="file-upload-area" id="file-upload-area">
                                                    <i class="fas fa-cloud-upload-alt fa-3x mb-3 text-primary"></i>
                                                    <h5>Drag & Drop files here</h5>
                                                    <p class="text-muted">or click to browse</p>
                                                    <input type="file" id="submission_files" name="submission_files[]" multiple style="display: none;">
                                                </div>
                                                <div id="files-preview" class="mt-3"></div>
                                                <small class="form-text text-muted">You can upload multiple files (PDF, DOC, Images, etc.)</small>
                                            </div>

                                            <button type="submit" class="btn btn-primary btn-lg" id="submit-btn">
                                                <i class="fas fa-paper-plane"></i> Submit Assignment
                                            </button>
                                        </div>
                                    </form>
                                    <div id="submission-msg"></div>
                                </div>
                            </div>

                        <?php else: ?>
                            <div class="card mt-3">
                                <div class="card-body">
                                    <div class="alert alert-danger">
                                        <i class="fas fa-ban"></i> Submissions are closed for this assignment.
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>

                    </div>

                    <!-- Sidebar -->
                    <div class="col-lg-4">

                        <!-- Assignment Info -->
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">Details</h3>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <strong>Due Date:</strong><br>
                                    <?php echo date('F d, Y', strtotime($assignment->due_date)); ?><br>
                                    <?php echo date('h:i A', strtotime($assignment->due_date)); ?>
                                </div>

                                <div class="mb-3">
                                    <strong>Total Marks:</strong><br>
                                    <?php echo $assignment->total_marks; ?> marks
                                </div>

                                <div class="mb-3">
                                    <strong>Type:</strong><br>
                                    <span class="badge badge-info"><?php echo ucfirst($assignment->assignment_type); ?></span>
                                </div>

                                <div class="mb-3">
                                    <strong>Late Submission:</strong><br>
                                    <?php echo $assignment->allow_late_submission ?
                                        'Allowed (' . $assignment->late_submission_days . ' days)' :
                                        'Not allowed'; ?>
                                </div>

                                <?php if ($submission): ?>
                                    <hr>
                                    <div class="mb-3">
                                        <strong>Your Status:</strong><br>
                                        <span class="badge badge-<?php echo $submission->submission_status == 'late_submitted' ? 'warning' : 'success'; ?>">
                                        <?php echo $submission->is_graded ? 'Graded' : 'Submitted'; ?>
                                    </span>
                                    </div>

                                    <div class="mb-3">
                                        <strong>Submitted On:</strong><br>
                                        <?php echo date('M d, Y H:i', strtotime($submission->submitted_at)); ?>
                                    </div>
                                <?php endif; ?>

                                <a href="assignments" class="btn btn-secondary btn-block mt-3">
                                    <i class="fas fa-arrow-left"></i> Back to Assignments
                                </a>
                            </div>
                        </div>

                    </div>
                </div>

            </div>
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>


    <script>
        $(document).ready(function(){
            $('.select2').select2();

        })

    </script>

    <script>
        $(function() {
            var uploadArea = $('#file-upload-area');
            var fileInput = $('#submission_files');
            var selectedFiles = [];

            // Click to upload
            uploadArea.on('click', function(e) {
                // Only trigger file input if the click target is the upload area itself
                // and not a child element like a button
                if (e.target === this) {
                    fileInput.click();
                }
            });

            // Drag and drop
            uploadArea.on('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).addClass('dragover');
            });

            uploadArea.on('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');
            });

            uploadArea.on('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');

                var files = e.originalEvent.dataTransfer.files;
                handleFiles(files);
            });

            // Handle file selection
            fileInput.on('change', function(e) {
                handleFiles(this.files);
            });

            function handleFiles(files) {
                selectedFiles = Array.from(files);
                displayFiles();
            }

            function displayFiles() {
                var preview = $('#files-preview');
                preview.empty();

                selectedFiles.forEach(function(file, index) {
                    var fileSize = (file.size / 1024 / 1024).toFixed(2);
                    var fileDiv = $('<div class="uploaded-file"></div>');
                    fileDiv.html(
                        '<span><i class="fas fa-file"></i> ' + file.name + ' <small class="text-muted">(' + fileSize + ' MB)</small></span>' +
                        '<button type="button" class="btn btn-sm btn-danger remove-file" data-index="' + index + '"><i class="fas fa-times"></i></button>'
                    );
                    preview.append(fileDiv);
                });
            }

            // Remove file event handler using event delegation
            $(document).on('click', '.remove-file', function() {
                var index = $(this).data('index');
                selectedFiles.splice(index, 1);
                displayFiles();
            });

            // Form submission
            $('#submission-form').on('submit', function(e) {
                e.preventDefault();

                var text = $('#submission_text').val().trim();

                if (!text && selectedFiles.length === 0) {
                    alert('Please provide either text response or upload files');
                    return false;
                }

                var formData = new FormData(this);

                // Clear and add selected files
                formData.delete('submission_files[]');
                selectedFiles.forEach(function(file) {
                    formData.append('submission_files[]', file);
                });

                $.ajax({
                    url: 'api/submit-assignment.php',
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        $('#submit-btn').attr('disabled', 'disabled');
                        $('#submit-btn').html('<i class="fas fa-spinner fa-spin"></i> Submitting...');
                    },
                    success: function(data) {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-paper-plane"></i> Submit Assignment');

                        try {
                            var response = JSON.parse(data);
                            if (response.success) {
                                $('#submission-msg').html('<div class="alert alert-success mt-3"><i class="fas fa-check-circle"></i> ' + response.message + '</div>');
                                setTimeout(function() {
                                    location.reload();
                                }, 2000);
                            } else {
                                $('#submission-msg').html('<div class="alert alert-danger mt-3"><i class="fas fa-exclamation-triangle"></i> ' + response.message + '</div>');
                            }
                        } catch(e) {
                            $('#submission-msg').html('<div class="alert alert-danger mt-3">' + data + '</div>');
                        }
                    },
                    error: function() {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-paper-plane"></i> Submit Assignment');
                        alert('An error occurred. Please try again.');
                    }
                });
            });
        });
    </script>


    <?php
    }else{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">


        <?php include '../admin/includes/styles.php'; ?>
        <title>Login to continue </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $student_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>