<?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'; ?>
        <?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();
        }
        ?>
        <title>Submissions - <?php echo htmlspecialchars($assignment->title); ?> | <?php echo $school_name; ?></title>

        <style>
            .assignment-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .filter-section {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
            }
            .submission-row {
                transition: all 0.3s;
            }
            .submission-row:hover {
                background: #f8f9fa;
            }
            .status-badge {
                padding: 5px 10px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
            }
            .status-not-submitted {
                background: #f8d7da;
                color: #721c24;
            }
            .status-submitted {
                background: #d4edda;
                color: #155724;
            }
            .status-late {
                background: #fff3cd;
                color: #856404;
            }
            .status-graded {
                background: #d1ecf1;
                color: #0c5460;
            }
            .status-pending {
                background: #e2e3e5;
                color: #383d41;
            }
            .stats-box {
                text-align: center;
                padding: 15px;
                background: #fff;
                border-radius: 5px;
                border-left: 4px solid #007bff;
            }
            .stats-number {
                font-size: 24px;
                font-weight: bold;
                color: #007bff;
            }
            .stats-label {
                font-size: 12px;
                color: #6c757d;
                text-transform: uppercase;
            }

            .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">Submissions</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"><a href="<?php echo $conn->base_url();?>view-assignment?id=<?php echo $assignment->id; ?>">View</a></li>
                                <li class="breadcrumb-item active">Submissions</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <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); ?> | <strong>Class:</strong> <?php echo htmlspecialchars($assignment->class_name . ' - ' . $assignment->section_name); ?></p>
                        <p class="mb-0"><strong>Due Date:</strong> <?php echo date('F d, Y H:i', strtotime($assignment->due_date)); ?> | <strong>Total Marks:</strong> <?php echo $assignment->total_marks; ?></p>
                    </div>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-lg-3 col-6">
                            <div class="stats-box">
                                <div class="stats-number"><?php echo $assignment->total_students ?? 0; ?></div>
                                <div class="stats-label">Total Students</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-6">
                            <div class="stats-box">
                                <div class="stats-number"><?php echo $assignment->submitted_count ?? 0; ?></div>
                                <div class="stats-label">Submitted</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-6">
                            <div class="stats-box">
                                <div class="stats-number"><?php echo $assignment->graded_count ?? 0; ?></div>
                                <div class="stats-label">Graded</div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-6">
                            <div class="stats-box">
                                <div class="stats-number"><?php echo $assignment->average_marks ? number_format($assignment->average_marks, 1) : 'N/A'; ?></div>
                                <div class="stats-label">Avg Marks</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Submissions</h3>
                        </div>
                        <div class="card-body">
                            <form method="GET" id="filter-form">
                                <input type="hidden" name="id" value="<?php echo $assignment->id; ?>">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select name="filter_status" class="form-control select2">
                                                <option value="">All Status</option>
                                                <option value="not_submitted" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'not_submitted') ? 'selected' : ''; ?>>Not Submitted</option>
                                                <option value="submitted" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'submitted') ? 'selected' : ''; ?>>Submitted</option>
                                                <option value="late_submitted" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'late_submitted') ? 'selected' : ''; ?>>Late Submitted</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Grading Status</label>
                                            <select name="filter_graded" class="form-control select2">
                                                <option value="">All</option>
                                                <option value="0" <?php echo (isset($_GET['filter_graded']) && $_GET['filter_graded'] == '0') ? 'selected' : ''; ?>>Not Graded</option>
                                                <option value="1" <?php echo (isset($_GET['filter_graded']) && $_GET['filter_graded'] == '1') ? 'selected' : ''; ?>>Graded</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>&nbsp;</label>
                                            <button type="submit" class="btn btn-primary btn-block">
                                                <i class="fas fa-filter"></i> Apply Filters
                                            </button>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>&nbsp;</label>
                                            <a href="<?php echo $conn->base_url();?>submissions?id=<?php echo $assignment->id; ?>" class="btn btn-secondary btn-block">
                                                <i class="fas fa-redo"></i> Reset
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Submissions Table -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Submissions (<?php echo $assignment->submitted_count ?? 0; ?> / <?php echo $assignment->total_students ?? 0; ?>)</h3>
                        </div>
                        <div class="card-body">
                            <table id="submissions-table" class="table table-bordered table-hover">
                                <thead>
                                <tr>
                                    <th>Student Name</th>
                                    <th>Reg No</th>
                                    <th>Status</th>
                                    <th>Submitted Date</th>
                                    <th>Files</th>
                                    <th>Grading</th>
                                    <th>Marks</th>
                                    <th>Grade</th>
                                    <th>Actions</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php
                                $sql = "SELECT asub.*, st.name as student_name, st.registerNO,
                                               COUNT(DISTINCT asf.id) as file_count
                                        FROM assignment_submissions asub
                                        LEFT JOIN student st ON asub.student_id = st.studentID
                                        LEFT JOIN assignment_submission_files asf ON asub.id = asf.submission_id
                                        WHERE asub.assignment_id = :assignment_id";

                                if (isset($_GET['filter_status']) && !empty($_GET['filter_status'])) {
                                    $sql .= " AND asub.submission_status = '" . $_GET['filter_status'] . "'";
                                }
                                if (isset($_GET['filter_graded']) && $_GET['filter_graded'] !== '') {
                                    $sql .= " AND asub.is_graded = " . (int)$_GET['filter_graded'];
                                }

                                $sql .= " GROUP BY asub.id ORDER BY asub.submission_status DESC, asub.submitted_at DESC";

                                $conn->query($sql);
                                $conn->bind(':assignment_id', $assignment_id);
                                $submissions = $conn->fetchMultiple();

                                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';
                                        }

                                        $grading_class = $sub->is_graded ? 'graded' : 'pending';
                                        $grading_text = $sub->is_graded ? 'Graded' : 'Pending';
                                        ?>
                                        <tr class="submission-row">
                                            <td>
                                                <strong><?php echo htmlspecialchars($sub->student_name); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($sub->registerNO); ?></td>
                                            <td>
                                        <span class="status-badge status-<?php echo $status_class; ?>">
                                            <?php echo $status_text; ?>
                                        </span>
                                            </td>
                                            <td>
                                                <?php if ($sub->submitted_at): ?>
                                                    <?php echo date('M d, Y H:i', strtotime($sub->submitted_at)); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($sub->file_count > 0): ?>
                                                    <span class="badge badge-info">
                                                <i class="fas fa-paperclip"></i> <?php echo $sub->file_count; ?> file(s)
                                            </span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                        <span class="status-badge status-<?php echo $grading_class; ?>">
                                            <?php echo $grading_text; ?>
                                        </span>
                                            </td>
                                            <td>
                                                <?php if ($sub->is_graded): ?>
                                                    <strong><?php echo $sub->marks_obtained; ?> / <?php echo $assignment->total_marks; ?></strong>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($sub->is_graded): ?>
                                                    <span class="badge badge-<?php echo $sub->grade == 'A' || $sub->grade == 'B' ? 'success' : 'warning'; ?>">
                                                <?php echo $sub->grade; ?>
                                            </span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?php echo $conn->base_url();?>grade-submission?id=<?php echo $sub->id; ?>" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-tasks"></i> Grade
                                                </a>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                } else {
                                    echo '<tr><td colspan="9" class="text-center text-muted">No submissions found</td></tr>';
                                }
                                ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

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

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


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

            $('#submissions-table').DataTable({
                "responsive": true,
                "lengthChange": true,
                "autoWidth": false,
                "paging": true,
                "pageLength": 25
            });
        });
    </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 '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
}
?>