<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include 'includes/styles.php'; ?>
        <title>Add Assignment | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Assignment.php';
        $assignment = new Assignment();
        ?>
        <style>
            .form-section {
                margin-bottom: 30px;
                padding-bottom: 30px;
                border-bottom: 1px solid #dee2e6;
            }
            .form-section:last-child {
                border-bottom: none;
            }
            .section-title {
                font-size: 18px;
                font-weight: 600;
                margin-bottom: 20px;
                color: #333;
                padding-bottom: 10px;
                border-bottom: 2px solid #007bff;
            }
            .info-text {
                font-size: 13px;
                color: #6c757d;
                margin-top: 5px;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Create Assignment</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>assignments">Assignments</a></li>
                                <li class="breadcrumb-item active">Create</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <section class="content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-10">
                            <div class="card card-primary">
                                <div class="card-header">
                                    <h3 class="card-title">Assignment Details</h3>
                                </div>

                                <form class="form-horizontal" id="assignment-add-form" method="POST" enctype="multipart/form-data">
                                    <div class="card-body">

                                        <!-- Basic Information Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-info-circle"></i> Basic Information</h4>

                                            <div class="form-group row">
                                                <label for="title" class="col-sm-3 col-form-label">Assignment Title <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" id="title" name="title" required
                                                           placeholder="e.g., Chapter 5 Essay, Physics Problem Set">
                                                    <small class="info-text">Enter a clear and descriptive title for the assignment</small>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="assignment_type" class="col-sm-3 col-form-label">Assignment Type <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <select name="assignment_type" id="assignment_type" class="form-control" required>
                                                        <option value="">Select type</option>
                                                        <option value="homework">Homework</option>
                                                        <option value="project">Project</option>
                                                        <option value="quiz">Quiz</option>
                                                        <option value="presentation">Presentation</option>
                                                        <option value="other">Other</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="description" class="col-sm-3 col-form-label">Description</label>
                                                <div class="col-sm-9">
                                                <textarea class="form-control" id="description" name="description" rows="3"
                                                          placeholder="Brief description of the assignment..."></textarea>
                                                    <small class="info-text">Students will see this description on the assignment page</small>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="instructions" class="col-sm-3 col-form-label">Instructions <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                <textarea class="form-control" id="instructions" name="instructions" rows="5" required
                                                          placeholder="Detailed instructions for completing the assignment..."></textarea>
                                                    <small class="info-text">Provide clear step-by-step instructions for students</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Classification Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-tag"></i> Classification</h4>

                                            <div class="form-group row">
                                                <label for="class" class="col-sm-3 col-form-label">Class <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <?php
                                                    $sql = "SELECT * FROM classes ORDER BY name";
                                                    $conn->query($sql);
                                                    $classes = $conn->fetchMultiple();
                                                    ?>
                                                    <select name="class" id="classID" class="form-control select2" required>
                                                        <option value="">Select class</option>
                                                        <?php
                                                        if ($conn->rowCount() > 0) {
                                                            foreach ($classes as $class) {
                                                                echo "<option value='{$class->id}'>{$class->name}</option>";
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="section" class="col-sm-3 col-form-label">Section <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <select name="section" id="section" class="form-control select2" required>
                                                        <option value="">Select class first</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="subject" class="col-sm-3 col-form-label">Subject <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <select name="subject" id="subject" class="form-control select2" required>
                                                        <option value="">Select class first</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Due Date & Marks Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-calendar"></i> Due Date & Marks</h4>

                                            <div class="form-group row">
                                                <label for="due_date" class="col-sm-3 col-form-label">Due Date & Time <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <div class="input-group date" id="due_date_picker" data-target-input="nearest">
                                                        <input type="text" class="form-control datetimepicker-input" id="due_date"
                                                               name="due_date" required data-target="#due_date_picker"/>
                                                        <div class="input-group-append" data-target="#due_date_picker" data-toggle="datetimepicker">
                                                            <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                                                        </div>
                                                    </div>
                                                    <small class="info-text">Students cannot submit after this date/time</small>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="total_marks" class="col-sm-3 col-form-label">Total Marks <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="number" class="form-control" id="total_marks" name="total_marks"
                                                           value="100" required min="1">
                                                    <small class="info-text">Maximum marks that can be awarded for this assignment</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Late Submission Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-clock"></i> Late Submission Policy</h4>

                                            <div class="form-group row">
                                                <label for="allow_late" class="col-sm-3 col-form-label">Allow Late Submission</label>
                                                <div class="col-sm-9">
                                                    <div class="custom-control custom-checkbox">
                                                        <input class="custom-control-input" type="checkbox" id="allow_late" name="allow_late" value="1">
                                                        <label class="custom-control-label" for="allow_late">
                                                            Allow students to submit after due date
                                                        </label>
                                                    </div>
                                                    <small class="info-text d-block mt-2">If enabled, students can submit late assignments</small>
                                                </div>
                                            </div>

                                            <div class="form-group row" id="late_days_section" style="display: none;">
                                                <label for="late_days" class="col-sm-3 col-form-label">Late Submission Days</label>
                                                <div class="col-sm-9">
                                                    <input type="number" class="form-control" id="late_days" name="late_days"
                                                           value="0" min="0">
                                                    <small class="info-text">Number of days after due date to allow submissions</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Attachment Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-paperclip"></i> Attachment (Optional)</h4>

                                            <div class="form-group row">
                                                <label for="attachment" class="col-sm-3 col-form-label">Upload File</label>
                                                <div class="col-sm-9">
                                                    <div class="input-group">
                                                        <div class="custom-file">
                                                            <input type="file" class="custom-file-input" id="attachment" name="attachment">
                                                            <label class="custom-file-label" for="attachment">Choose file</label>
                                                        </div>
                                                    </div>
                                                    <small class="info-text">Attach assignment files or rubrics (PDF, DOC, etc.)</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Status Section -->
                                        <div class="form-section">
                                            <h4 class="section-title"><i class="fas fa-signal"></i> Status</h4>

                                            <div class="form-group row">
                                                <label for="status" class="col-sm-3 col-form-label">Status <span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <select name="status" id="status" class="form-control" required>
                                                        <option value="draft">Draft (Save but don't publish)</option>
                                                        <option value="published" selected>Published (Students can see)</option>
                                                    </select>
                                                    <small class="info-text">Draft assignments are not visible to students</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Submit Button -->
                                        <div class="form-group row">
                                            <label class="col-sm-3 col-form-label"></label>
                                            <div class="col-sm-9">
                                                <button type="submit" name="add_assignment" class="btn btn-primary" id="submit-btn">
                                                    <i class="fas fa-save"></i> Create Assignment
                                                </button>
                                                <a href="<?php echo $conn->base_url();?>assignments" class="btn btn-secondary">
                                                    <i class="fas fa-times"></i> Cancel
                                                </a>
                                            </div>
                                        </div>

                                    </div>
                                    <div id="success-msg"></div>
                                </form>
                            </div>

                            <!-- Info Alert -->
                            <div class="alert alert-info mt-3">
                                <h5><i class="icon fas fa-info"></i> Tips:</h5>
                                <ul class="mb-0">
                                    <li>Be clear and specific in your instructions</li>
                                    <li>Set realistic due dates for students</li>
                                    <li>Publish assignments so students can see them</li>
                                    <li>You can edit published assignments anytime</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

        </div>

        <?php include "includes/footer.php"; ?>
        <script>
            $(function() {
                $('.select2').select2();

                // Initialize datetime picker
                $('#due_date_picker').datetimepicker({
                    format: 'YYYY-MM-DD HH:mm',
                    minDate: moment().add(1, 'days')
                });

                // Fetch sections when class changes
                $('#classID').on('change', function() {
                    var classID = $(this).val();
                    if (classID) {
                        $.ajax({
                            type: 'POST',
                            url: 'fetch_section.php',
                            data: 'classesID=' + classID,
                            success: function(html) {
                                $('#section').html(html);
                            }
                        });

                        $.ajax({
                            type: 'POST',
                            url: 'fetch_subject.php',
                            data: 'classesID=' + classID,
                            success: function(html) {
                                $('#subject').html(html);
                            }
                        });
                    }
                });

                // Show/hide late days input
                $('#allow_late').on('change', function() {
                    if ($(this).is(':checked')) {
                        $('#late_days_section').show();
                    } else {
                        $('#late_days_section').hide();
                    }
                });

                // File input label
                $('#attachment').on('change', function(e) {
                    var fileName = e.target.files[0].name;
                    $(this).next('.custom-file-label').text(fileName);
                });

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

                    var formData = new FormData(this);
                    //ensure add_assignment parameter is included.
                    formData.append('add_assignment', '1');

                    $.ajax({
                        url: 'process-add-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> Creating assignment...');
                        },
                        success: function(data) {
                            $('#submit-btn').attr('disabled', false);
                            $('#submit-btn').html('<i class="fas fa-save"></i> Create Assignment');
                            $('#success-msg').html(data);

                            if (data.includes('success')) {
                                setTimeout(function() {
                                    window.location.href = '<?php echo $conn->base_url();?>assignments';
                                }, 2000);
                            }
                        },
                        error: function() {
                            $('#submit-btn').attr('disabled', false);
                            $('#submit-btn').html('<i class="fas fa-save"></i> Create Assignment');
                            alert('An error occurred. Please try again.');
                        }
                    });
                });
            });
        </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </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 $link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>