<?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>All Assignments | <?php echo $school_name; ?></title>

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

        // Get teacher info
        $sql = "SELECT * FROM teachers WHERE username = :username";
        $conn->query($sql);
        $conn->bind(':username', $username);
        $teacher = $conn->fetchSingle();

        if (!$teacher) {
            header("Location: $teacher_login_link");
            exit();
        }

        $teacher_id = $teacher->id;
        $teacher_name = $teacher->name;
        ?>
        <style>
            .assignment-card {
                transition: all 0.3s;
                border-left: 4px solid #007bff;
                height: 100%;
            }
            .assignment-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            .assignment-status{
                display: inline-block;
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
            }
            .status-draft {
                background: #e2e3e5;
              color: #383d41;
            }
            .status-published {
                background: #d4edda;
                color: #155724;
            }
            .status-closed {
                background: #f8d7da;
                color: #721c24;
            }
            .due-date-badge {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
            }
            .due-soon {
                background: #fff3cd;
                color: #856404;
            }
            .due-overdue {
                background: #f8d7da;
                color: #721c24;
            }
            .due-future {
                background: #d4edda;
                color: #155724;
            }
          .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
                gap: 10px;
                margin: 10px 0;
            }
            .stat-box {
                text-align: center;
                padding: 10px;
                background: #f8f9fa;
                border-radius: 5px;
            }
            .stat-number {
                font-size: 18px;
                font-weight: bold;
                color: #007bff;
            }
            .stat-label {
                font-size: 11px;
                color: #6c757d;
                text-transform: uppercase;
            }
            .fa-eye, .fa-edit, .fa-trash {
                background-color: transparent;
            }

        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
   <divclass="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">Assignments</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 active">Assignments</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

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

                    <!-- Statistics Cards -->
                    <?php
                        $sql = "SELECT 
                        COUNT(*) as total,
                        SUM(CASE WHEN status = 'published' THEN 1 ELSE 0 END) as published,
                        SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) as draft,
                        SUM(CASE WHEN NOW() > due_date AND status= 'published' THEN 1 ELSE 0 END) as overdue
                        FROM assignments WHERE created_by =:teacher_username";
                    $conn->query($sql);
                    $conn->bind(':teacher_username', $username);
                    $stats = $conn->fetchSingle();
                    ?>
                    <div class="row">
                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-info">
                                <div class="inner">
                                    <h3><?php echo $stats->total ?? 0; ?></h3>
                                    <p>Total Assignments</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-tasks"></i>
                               </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-success">
                                <div class="inner">
                                    <h3><?php echo $stats->published ?? 0; ?></h3>
                                    <p>Published</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-warning">
                                <div class="inner">
                                    <h3><?php echo $stats->draft ?? 0; ?></h3>
                                    <p>Drafts</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-pencil-alt"></i>
                                </div>
                            </div>
                        </div>

                       <div class="col-lg-3 col-6">
                            <div class="small-box bg-danger">
                                <div class="inner">
                                    <h3><?php echo $stats->overdue ?? 0; ?></h3>
                                    <p>Overdue</p>
                                </div>
                               <div class="icon">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Assignments</h3>
                            <div class="card-tools">
                                <a href="<?php echo $conn->teacher_url();?>add-assignment" class="btn btn-primary btn-sm">
                                    <i class="fas fa-plus"></i> Create Assignment
                                </a>
                            </div>
                        </div>
                       <div class="card-body">
                            <form method="GET" id="filter-form">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Class</label>
                                            <select name="filter_class" id="filter_class" class="form-control select2">
                                                <option value="">All Classes</option>
                                                <?php
                                                $sql = "SELECT * FROM classes WHERE teacher_name =:teacher_name ORDER BY name";
                                                $conn->query($sql);
                                                $conn->bind(':teacher_name', $teacher_name);
                                                $classes = $conn->fetchMultiple();
                                                foreach ($classes as $class) {
                                                    $selected =(isset($_GET['filter_class']) && $_GET['filter_class'] == $class->id) ? 'selected' : '';
                                                    echo "<option value='{$class->id}' {$selected}>{$class->name}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>

                                   <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="draft" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'draft') ? 'selected' : ''; ?>>Draft</option>
                                                <option value="published" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'published') ? 'selected' : ''; ?>>Published</option>
                                               <option value="closed" <?php echo (isset($_GET['filter_status']) && $_GET['filter_status'] == 'closed') ? 'selected' : ''; ?>>Closed</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Type</label>
                                            <select name="filter_type" class="form-control select2">
                                                <option value="">All Types</option>
                                                <option value="homework" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'homework') ? 'selected' : '';?>>Homework</option>
                                                <option value="project" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'project') ? 'selected' : ''; ?>>Project</option>
                                                <option value="quiz" <?php echo (isset($_GET['filter_type']) &&$_GET['filter_type'] == 'quiz') ? 'selected' : ''; ?>>Quiz</option>
                                                <option value="presentation" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'presentation') ? 'selected' : ''; ?>>Presentation</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>
                            </form>
                        </div>
                    </div>

                    <!-- Assignments List (Grid View) -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Assignments</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" id="toggle-view">
                                    <i class="fas fa-th" id="view-icon"></i> Toggle View
                                </button>
                            </div>
                        </div>
                        <div class="card-body">

                            <!-- Grid View -->
                            <div id="grid-view">
                                <div class="row">
                                    <?php
                                    $sql = "SELECT a.*, s.subject_name, c.name as class_name, sec.name as section_name,
                                        stats.total_students, stats.submitted_count, stats.graded_count,stats.average_marks
                                        FROM assignments a
                                        LEFT JOIN subjects s ON a.subject_id = s.id
                                        LEFT JOIN classes c ON a.class_id = c.id
                                        LEFT JOIN sections sec ON a.section_id = sec.id
                                        LEFT JOIN assignment_statistics stats ON a.id = stats.assignment_id
                                        WHERE 1=1 AND created_by =:username";

                                    if (isset($_GET['filter_class']) && !empty($_GET['filter_class'])) {
                                        $sql .= " AND a.class_id = " . (int)$_GET['filter_class'];
                                    }
                                    if (isset($_GET['filter_status']) && !empty($_GET['filter_status'])){
                                        $sql .= " AND a.status = '" . $_GET['filter_status'] . "'";
                                    }
                                    if (isset($_GET['filter_type']) && !empty($_GET['filter_type'])) {
                                        $sql .= " AND a.assignment_type = '" . $_GET['filter_type'] . "'";
                                    }

                                   $sql .= " ORDER BY a.due_date DESC";

                                    $conn->query($sql);
                                    $conn->bind(':username', $username);
                                    $assignments = $conn->fetchMultiple();

                                    if (!empty($assignments)) {
                                    foreach ($assignments as $assign) {
                                    $now = new DateTime();
                                    $due_date = new DateTime($assign->due_date);
                                    $diff = $now->diff($due_date);

                                    if ($now > $due_date) {
                                        $due_class = 'due-overdue';
                                        $due_text = 'Overdue (' . $diff->days . 'd ago)';
                                    } elseif ($diff->days <= 3) {
                                       $due_class = 'due-soon';
                                        $due_text = 'Due in ' . $diff->days . ' days';
                                    } else {
                                        $due_class = 'due-future';
                                        $due_text = 'Due in ' . $diff->days . ' days';
                                    }
                                    ?>
                                   <div class="col-md-4 col-sm-6 mb-4">
                                        <div class="card assignment-card">
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <h5 class="card-title mb-0"><?php echo htmlspecialchars($assign->title); ?></h5>
                                                    <span class="assignment-status status-<?php echo $assign->status; ?>">
                                                    <?php echo strtoupper($assign->status); ?>
                                                </span>
                                                </div>

                                                <p class="text-muted small mb-2">
                                                    <i class="fas fa-book"></i> <?php echo htmlspecialchars($assign->subject_name); ?><br>
                                                    <i class="fas fa-school"></i> <?php echo htmlspecialchars($assign->class_name . ' - ' . $assign->section_name); ?><br>
                                                    <i class="fas fa-tag"></i> <?php echo ucfirst($assign->assignment_type); ?>
                                                </p>

                                                <div class="mb-2">
                                                <span class="due-date-badge <?php echo $due_class; ?>">
                                                    <i class="fas fa-clock"></i> <?php echo $due_text; ?>
                                                </span>
                                                </div>

                                                <div class="stats-grid">
                                                    <div class="stat-box">
                                                        <div class="stat-number"><?php echo $assign->submitted_count ?? 0; ?></div>
                                                        <div class="stat-label">Submitted</div>
                                                    </div>
                                                    <div class="stat-box">
                                                        <div class="stat-number"><?php echo $assign->graded_count ?? 0; ?></div>
                                                        <div class="stat-label">Graded</div>
                                                    </div>
                                                    <div class="stat-box">
                                                        <div class="stat-number"><?php echo $assign->average_marks ? number_format($assign->average_marks,1) : 'N/A'; ?></div>
                                                        <div class="stat-label">Avg</div>
                                                    </div>
                                                </div>

                                                <div class="btn-group btn-block mt-3">
                                                    <a href="<?php echo $conn->teacher_url();?>view-assignment?id=<?php echo$assign->id; ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-eye"></i> View
                                                    </a>
                                                    <a href="<?php echo $conn->teacher_url();?>edit-assignment?id=<?php echo $assign->id; ?>" class="btn btn-sm btn-info">
                                                       <i class="fas fa-edit"></i> Edit
                                                    </a>
                                                    <button class="btn btn-sm btn-danger delete-assignment" data-id="<?php echo $assign->id; ?>" data-title="<?php echo htmlspecialchars($assign->title); ?>">
                                                        <i class="fas fa-trash"></i>Delete
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                   </div>
                                        <?php
                                        }
                                        } else {
                                            echo '<div class="col-12"><div class="alert alert-info">No assignments found. <a href="' . $conn->teacher_url() . 'add-assignment">Create your first assignment</a></div></div>';
                                        }
                                        ?>
                               </div>
                            </div>

                            <!-- Table View (Hidden by default) -->
                            <div id="table-view" style="display: none;">
                                <table id="assignments-table" class="table table-bordered table-striped">
                                    <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Type</th>
                                        <th>Class/Section</th>
                                        <th>Due Date</th>
                                        <th>Status</th>
                                        <th>Submitted</th>
                                        <th>Graded</th>
                                        <th>Avg Marks</th>
                                        <th>Actions</th>
                                   </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    if (!empty($assignments)) {
                                        foreach ($assignments as $assign) {
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($assign->title); ?></td>
                                                <td><span class="badge badge-info"><?php echo strtoupper($assign->assignment_type); ?></span></td>
                                                <td><?php echo htmlspecialchars($assign->class_name . ' - ' . $assign->section_name); ?></td>
                                                <td><?php echo date('M d, Y H:i', strtotime($assign->due_date)); ?></td>
                                               <td><span class="assignment-status status-<?php echo $assign->status; ?>"><?php echo strtoupper($assign->status); ?></span></td>
                                                <td><?php echo $assign->submitted_count ?? 0; ?></td>
                                                <td><?php echo $assign->graded_count ?? 0; ?></td>
                                                <td><?php echo $assign->average_marks ? number_format($assign->average_marks, 1) : 'N/A'; ?></td>
                                                <td>
                                                    <div class="btn-group btn-sm">
                                                        <a href="<?php echo $conn->teacher_url();?>view-assignment?id=<?php echo $assign->id; ?>" class="btn btn-primary" title="View">
                                                           <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="<?php echo $conn->teacher_url();?>edit-assignment?id=<?php echo $assign->id; ?>" class="btn btn-info" title="Edit">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                            <button class="btn btn-danger delete-assignment" data-id="<?php echo $assign->id; ?>" data-title="<?php echo htmlspecialchars($assign->title); ?>"title="Delete">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

        </div>


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

                $('#assignments-table').DataTable({
                    "responsive": true,
                    "lengthChange": true,
                    "autoWidth": false
                });
            });

            // Toggle between grid and table view
            $('#toggle-view').on('click', function() {
                $('#grid-view').toggle();
                $('#table-view').toggle();

                var icon = $('#view-icon');
                if (icon.hasClass('fa-th')) {
                    icon.removeClass('fa-th').addClass('fa-list');
                } else {
                    icon.removeClass('fa-list').addClass('fa-th');
                }
            });

            // Delete assignment
            $('.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(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Error!',
                                        data.message,
                                        'error'
                                    );
                                }
                            },
                        error: function() {
                                Swal.fire(
                                    'Error!',
                                    'An error occurred. Please try again.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });
        </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 tocontinue | <?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
}
?>