<?php
session_start();
if(isset($_SESSION['teacher'])){
    $username = $_SESSION['teacher'];

    ?>
    <!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'; ?>
        <title>Edit Assignment | <?php echo $school_name; ?></title>
        <?php
        require_once '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();
        }

        $user_type = $_SESSION['teacher'];

        // Check permission (creator can edit)
        if (
            $assignment->created_by != $_SESSION['teacher']
        ) {
            header('Location: assignments');
            exit();
        }
        ?>
        <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;
            }
            .current-attachment {
                padding: 10px;
                background: #e7f3ff;
                border-left: 3px solid #007bff;
                border-radius: 4px;
                margin-bottom: 10px;
            }

            .fa-eye, .fa-edit, .fa-trash {
                background-color: transparent;
            }
        </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">Edit Assignment</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>">Home</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>assignments">Assignments</a></li>
                                <li class="breadcrumb-item active">Edit</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">Edit Assignment Details</h3>
                                </div>

                                <form class="form-horizontal" id="assignment-edit-form" method="POST" enctype="multipart/form-data">
                                    <div class="card-body">
                                        <input type="hidden" name="assignment_id" value="<?php echo $assignment->id; ?>">

                                        <!-- 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
                                                           value="<?php echo htmlspecialchars($assignment->title); ?>">
                                                </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="homework" <?php echo ($assignment->assignment_type == 'homework') ? 'selected' : ''; ?>>Homework</option>
                                                        <option value="project" <?php echo ($assignment->assignment_type == 'project') ? 'selected' : ''; ?>>Project</option>
                                                        <option value="quiz" <?php echo ($assignment->assignment_type == 'quiz') ? 'selected' : ''; ?>>Quiz</option>
                                                        <option value="presentation" <?php echo ($assignment->assignment_type == 'presentation') ? 'selected' : ''; ?>>Presentation</option>
                                                        <option value="other" <?php echo ($assignment->assignment_type == 'other') ? 'selected' : ''; ?>>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"><?php echo htmlspecialchars($assignment->description ?? ''); ?></textarea>
                                                </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><?php echo htmlspecialchars($assignment->instructions); ?></textarea>
                                                </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"
                                                               value="<?php echo date('Y-m-d H:i', strtotime($assignment->due_date)); ?>"/>
                                                        <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>
                                                </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="<?php echo $assignment->total_marks; ?>" required min="1">
                                                </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"
                                                            <?php echo ($assignment->allow_late_submission) ? 'checked' : ''; ?>>
                                                        <label class="custom-control-label" for="allow_late">
                                                            Allow students to submit after due date
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="form-group row" id="late_days_section" <?php echo ($assignment->allow_late_submission) ? '' : '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="<?php echo $assignment->late_submission_days; ?>" min="0">
                                                </div>
                                            </div>
                                        </div>

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

                                            <?php if ($assignment->attachment_url): ?>
                                                <div class="current-attachment">
                                                    <strong>Current File:</strong>
                                                    <a href="<?php echo $conn->main_url() . $assignment->attachment_url; ?>" target="_blank">
                                                        <?php echo htmlspecialchars(basename($assignment->attachment_url)); ?>
                                                    </a>
                                                </div>
                                            <?php endif; ?>

                                            <div class="form-group row">
                                                <label for="attachment" class="col-sm-3 col-form-label">Upload New 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">Leave empty to keep current attachment</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" <?php echo ($assignment->status == 'draft') ? 'selected' : ''; ?>>Draft (Students cannot see)</option>
                                                        <option value="published" <?php echo ($assignment->status == 'published') ? 'selected' : ''; ?>>Published (Students can see)</option>
                                                        <option value="closed" <?php echo ($assignment->status == 'closed') ? 'selected' : ''; ?>>Closed (No new submissions)</option>
                                                    </select>
                                                </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="edit_assignment" class="btn btn-primary" id="submit-btn">
                                                    <i class="fas fa-save"></i> Update Assignment
                                                </button>
                                                <a href="<?php echo $conn->teacher_url();?>view-assignment?id=<?php echo $assignment->id; ?>" class="btn btn-info">
                                                    <i class="fas fa-eye"></i> View Assignment
                                                </a>
                                                <a href="<?php echo $conn->teacher_url();?>assignments" class="btn btn-secondary">
                                                    <i class="fas fa-times"></i> Cancel
                                                </a>
                                            </div>
                                        </div>

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

        <?php include "../admin/includes/footer.php"; ?>
    </div>


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

            // Initialize datetime picker
            $('#due_date_picker').datetimepicker({
                format: 'YYYY-MM-DD HH:mm'
            });

            // 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) {
                if (this.files.length > 0) {
                    var fileName = e.target.files[0].name;
                    $(this).next('.custom-file-label').text(fileName);
                }
            });

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

                var formData = new FormData(this);
                formData.append('edit_assignment', '1');

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

                        if (data.includes('success')) {
                            setTimeout(function() {
                                window.location.href = '<?php echo $conn->teacher_url();?>view-assignment?id=<?php echo $assignment->id; ?>';
                            }, 2000);
                        }
                    },
                    error: function() {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-save"></i> Update Assignment');
                        alert('An error occurred. Please try again.');
                    }
                });
            });
        });
    </script>
    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPE html>
    <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 '../admin/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 $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>