<?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>View 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();
        }
        ?>
        <style>
            .assignment-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 30px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                gap: 15px;
                margin: 20px 0;
            }
            .stat-card {
                text-align: center;
                padding: 20px;
                background: #f8f9fa;
                border-radius: 8px;
                border-left: 4px solid #007bff;
            }
            .stat-number {
                font-size: 28px;
                font-weight: bold;
                color: #007bff;
            }
            .stat-label {
                font-size: 12px;
                color: #6c757d;
                text-transform: uppercase;
                margin-top: 5px;
            }
            .info-box {
                padding: 15px;
                background: #f8f9fa;
                border-left: 4px solid #007bff;
                margin-bottom: 15px;
                border-radius: 4px;
            }
            .info-label {
                font-weight: 600;
                color: #333;
            }
            .submission-item {
                padding: 15px;
                background: #fff;
                border-left: 3px solid #28a745;
                margin-bottom: 15px;
                border-radius: 4px;
            }
            .submission-item.ungraded {
                border-left-color: #ffc107;
            }
            .submission-item.not-submitted {
                border-left-color: #dc3545;
            }
            .status-badge {
                display: inline-block;
                padding: 5px 10px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
            }
            .status-submitted {
                background: #d4edda;
                color: #155724;
            }
            .status-late {
                background: #fff3cd;
                color: #856404;
            }
            .status-graded {
                background: #d1ecf1;
                color: #0c5460;
            }
            .status-not-submitted {
                background: #f8d7da;
                color: #721c24;
            }

            .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">Assignment Details</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">View</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

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

                    <!-- Assignment Header -->
                    <div class="assignment-header">
                        <div class="row">
                            <div class="col-md-8">
                                <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>Class/Section:</strong> <?php echo htmlspecialchars($assignment->class_name . ' - ' . $assignment->section_name); ?></p>
                            </div>
                            <div class="col-md-4 text-right">
                            <span class="badge badge-<?php echo $assignment->status == 'published' ? 'success' : 'warning'; ?>" style="font-size: 14px; padding: 10px 15px;">
                                <?php echo strtoupper($assignment->status); ?>
                            </span>
                                <br>
                                <small class="text-muted mt-2">Type: <?php echo strtoupper($assignment->assignment_type); ?></small>
                            </div>
                        </div>
                    </div>

                    <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">

                                    <div class="info-box">
                                        <div class="info-label">Description: &nbsp;</div>
                                        <p class="mb-0"> <?php echo nl2br(htmlspecialchars($assignment->description ?? 'No description')); ?></p>
                                    </div>

                                    <div class="info-box">
                                        <div class="info-label">Instructions: &nbsp; &nbsp;</div>
                                        <p class="mb-0">&nbsp;<?php echo nl2br(htmlspecialchars($assignment->instructions)); ?></p>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="info-box">
                                                <div class="info-label">Due Date & Time: &nbsp;</div>
                                                <p class="mb-0"><?php echo date('F d, Y \a\t h:i A', strtotime($assignment->due_date)); ?></p>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="info-box">
                                                <div class="info-label">Total Marks: &nbsp;</div>
                                                <p class="mb-0"><?php echo $assignment->total_marks; ?> marks</p>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="info-box">
                                                <div class="info-label">Late Submission: &nbsp;</div>
                                                <p class="mb-0">
                                                    <?php echo $assignment->allow_late_submission ?
                                                        'Allowed (' . $assignment->late_submission_days . ' days after due date)' :
                                                        'Not allowed'; ?>
                                                </p>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="info-box">
                                                <div class="info-label">Created By: &nbsp;</div>
                                                <p class="mb-0"><?php echo htmlspecialchars($assignment->created_by); ?> (<?php echo strtoupper($assignment->creator_type); ?>)</p>
                                            </div>
                                        </div>
                                    </div>

                                    <?php if ($assignment->attachment_url): ?>
                                        <div class="info-box">
                                            <div class="info-label">Attachment: &nbsp;</div>
                                            <a href="<?php echo $conn->main_url() . $assignment->attachment_url; ?>" target="_blank" class="btn btn-sm btn-primary">
                                                <i class="fas fa-download"></i> Download File
                                            </a>
                                        </div>
                                    <?php endif; ?>

                                </div>
                            </div>

                            <!-- Statistics -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Submission Statistics</h3>
                                </div>
                                <div class="card-body">
                                    <div class="stats-grid">
                                        <div class="stat-card">
                                            <div class="stat-number"><?php echo $assignment->total_students ?? 0; ?></div>
                                            <div class="stat-label">Total Students</div>
                                        </div>
                                        <div class="stat-card">
                                            <div class="stat-number"><?php echo $assignment->submitted_count ?? 0; ?></div>
                                            <div class="stat-label">Submitted</div>
                                        </div>
                                        <div class="stat-card">
                                            <div class="stat-number"><?php echo $assignment->graded_count ?? 0; ?></div>
                                            <div class="stat-label">Graded</div>
                                        </div>
                                        <div class="stat-card">
                                            <div class="stat-number"><?php echo $assignment->average_marks ? number_format($assignment->average_marks, 1) : 'N/A'; ?></div>
                                            <div class="stat-label">Avg Marks</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Submissions List -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Student Submissions (<?php echo $assignment->submitted_count ?? 0; ?> / <?php echo $assignment->total_students ?? 0; ?>)</h3>
                                </div>
                                <div class="card-body">
                                    <?php
                                    $submissions = $assignment_mgr->getSubmissions($assignment_id);

                                    if (!empty($submissions)) {
                                        foreach ($submissions as $sub) {
                                            $status_class = 'not-submitted';
                                            $status_text = 'Not Submitted';

                                            if ($sub->submission_status == 'submitted') {
                                                $status_class = 'submitted';
                                                $status_text = 'Submitted';
                                            } elseif ($sub->submission_status == 'late_submitted') {
                                                $status_class = 'late';
                                                $status_text = 'Late Submitted';
                                            }
                                            ?>
                                            <div class="submission-item <?php echo $sub->submission_status == 'not_submitted' ? 'not-submitted' : ($sub->is_graded ? 'graded' : 'ungraded'); ?>">
                                                <div class="row align-items-center">
                                                    <div class="col-md-6">
                                                        <strong><?php echo htmlspecialchars($sub->student_name); ?></strong> (<?php echo htmlspecialchars($sub->registerNO); ?>)<br>
                                                        <small class="text-muted">
                                                            <?php if ($sub->submitted_at): ?>
                                                                Submitted: <?php echo date('M d, Y H:i', strtotime($sub->submitted_at)); ?>
                                                            <?php else: ?>
                                                                Not yet submitted
                                                            <?php endif; ?>
                                                        </small>
                                                    </div>
                                                    <div class="col-md-3">
                                            <span class="status-badge status-<?php echo $status_class; ?>">
                                                <?php echo $status_text; ?>
                                            </span>
                                                        <?php if ($sub->is_graded): ?>
                                                            <br>
                                                            <span class="badge badge-success mt-2">
                                                <i class="fas fa-check"></i> Graded
                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="col-md-3 text-right">
                                                        <?php if ($sub->submitted_at): ?>
                                                            <a href="<?php echo $conn->teacher_url();?>grade-submission?id=<?php echo $sub->id; ?>" class="btn btn-sm btn-primary">
                                                                <i class="fas fa-tasks"></i> Grade
                                                            </a>
                                                        <?php else: ?>
                                                            <span class="text-muted">Pending</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <?php if ($sub->is_graded): ?>
                                                    <div class="mt-2 pt-2 border-top">
                                                        <small><strong>Marks:</strong> <?php echo $sub->marks_obtained . ' / ' . $assignment->total_marks; ?> (<?php echo number_format($sub->percentage, 1); ?>%) - Grade: <?php echo $sub->grade; ?></small>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <?php
                                        }
                                    } else {
                                        echo '<p class="text-muted">No submissions yet</p>';
                                    }
                                    ?>
                                </div>
                            </div>

                        </div>

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

                            <!-- Quick Actions -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Actions</h3>
                                </div>
                                <div class="card-body">
                                    <a href="<?php echo $conn->teacher_url();?>edit-assignment?id=<?php echo $assignment->id; ?>" class="btn btn-info btn-block mb-2">
                                        <i class="fas fa-edit"></i> Edit Assignment
                                    </a>
                                    <button class="btn btn-danger btn-block delete-assignment" data-id="<?php echo $assignment->id; ?>" data-title="<?php echo htmlspecialchars($assignment->title); ?>">
                                        <i class="fas fa-trash"></i> Delete Assignment
                                    </button>
                                    <a href="<?php echo $conn->teacher_url();?>submissions?id=<?php echo $assignment->id;?>" class="btn btn-success btn-block mt-2">
                                        <i class="fas fa-eye"></i> View Submissions
                                    </a>
                                    <a href="<?php echo $conn->teacher_url();?>assignments" class="btn btn-secondary btn-block mt-2">
                                        <i class="fas fa-arrow-left"></i> Back to Assignments
                                    </a>
                                </div>
                            </div>

                            <!-- Summary -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Summary</h3>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <small class="text-muted">Status</small>
                                        <p class="mb-0">
                                        <span class="badge badge-<?php echo $assignment->status == 'published' ? 'success' : 'warning'; ?>">
                                            <?php echo strtoupper($assignment->status); ?>
                                        </span>
                                        </p>
                                    </div>

                                    <div class="mb-3">
                                        <small class="text-muted">Type</small>
                                        <p class="mb-0"><?php echo ucfirst($assignment->assignment_type); ?></p>
                                    </div>

                                    <div class="mb-3">
                                        <small class="text-muted">Due Date</small>
                                        <p class="mb-0"><?php echo date('M d, Y', strtotime($assignment->due_date)); ?></p>
                                    </div>

                                    <div class="mb-3">
                                        <small class="text-muted">Submission Rate</small>
                                        <div class="progress">
                                            <?php
                                            $submission_rate = $assignment->total_students > 0 ?
                                                round(($assignment->submitted_count / $assignment->total_students) * 100) : 0;
                                            ?>
                                            <div class="progress-bar bg-success" role="progressbar"
                                                 style="width: <?php echo $submission_rate; ?>%"
                                                 aria-valuenow="<?php echo $submission_rate; ?>"
                                                 aria-valuemin="0" aria-valuemax="100">
                                                <?php echo $submission_rate; ?>%
                                            </div>
                                        </div>
                                    </div>

                                    <div>
                                        <small class="text-muted">Grading Rate</small>
                                        <div class="progress">
                                            <?php
                                            $grading_rate = $assignment->submitted_count > 0 ?
                                                round(($assignment->graded_count / $assignment->submitted_count) * 100) : 0;
                                            ?>
                                            <div class="progress-bar bg-info" role="progressbar"
                                                 style="width: <?php echo $grading_rate; ?>%"
                                                 aria-valuenow="<?php echo $grading_rate; ?>"
                                                 aria-valuemin="0" aria-valuemax="100">
                                                <?php echo $grading_rate; ?>%
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>

                </div>
            </section>
        </div>

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


    <script>
        $(function() {
            $('.delete-assignment').on('click', function() {
                var assignmentId = $(this).data('id');
                var assignmentTitle = $(this).data('title');

                Swal.fire({
                    title: 'Are you sure?',
                    text: 'You are about to delete "' + assignmentTitle + '". This cannot be undone!',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'delete-assignment.php',
                            method: 'POST',
                            data: { assignment_id: assignmentId },
                            success: function(response) {
                                var data =JSON.parse(response);
                                if (data.success) {
                                    Swal.fire(
                                        'Deleted!',
                                        data.message,
                                        'success'
                                    ).then(() => {
                                        window.location.href = "<?php echo $conn->teacher_url(). 'assignments'; ?>"
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        data.message,
                                        'error'
                                    );
                                }
                            },
                            error: function() {
                                Swal.fire(
                                    'Error!',
                                    'An error occurred. Please try again.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });
        });
    </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
}
?>