<?php
session_start();
require_once(__DIR__ . '/../config.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'student') {
    header("Location: login.php");
    exit();
}

include('../header/header.php');

$student_id = $_SESSION['user_id'];

// Handle status update (e.g., from started to in_progress)
if (isset($_POST['update_status'])) {
    $assignment_id = $_POST['assignment_id'];
    $new_status = $_POST['status'];
    
    // Check if a submission record exists
    $stmt = $pdo->prepare("SELECT id FROM submissions WHERE assignment_id = ? AND student_id = ?");
    $stmt->execute([$assignment_id, $student_id]);
    $submission = $stmt->fetch();
    
    if ($submission) {
        $stmt = $pdo->prepare("UPDATE submissions SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $submission['id']]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO submissions (assignment_id, student_id, status) VALUES (?, ?, ?)");
        $stmt->execute([$assignment_id, $student_id, $new_status]);
    }
    $success = "Assignment status updated to " . str_replace('_', ' ', $new_status) . ".";
}

// Fetch assignments for courses the student is enrolled in
$stmt = $pdo->prepare("
    SELECT a.*, c.course_name, s.status, s.grade, s.feedback, s.submitted_at
    FROM assignments a
    JOIN courses c ON a.course_id = c.id
    JOIN enrollments e ON c.id = e.course_id
    LEFT JOIN submissions s ON a.id = s.assignment_id AND s.student_id = ?
    WHERE e.student_id = ? AND e.status = 'enrolled'
    ORDER BY a.due_date ASC
");
$stmt->execute([$student_id, $student_id]);
$assignments = $stmt->fetchAll();
?>
<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">My Assignments</h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Assignments</li>
            </ol>
        </nav>
    </div>

    <?php if (isset($success)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <?php if (empty($assignments)): ?>
            <div class="col-12 text-center py-5">
                <div class="bg-white p-5 rounded shadow-sm">
                    <i class="fas fa-tasks fa-4x text-muted mb-3"></i>
                    <h4 class="text-muted">No assignments found for your courses.</h4>
                    <p>When your lecturers create assignments, they will appear here.</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($assignments as $a): 
                $status = $a['status'] ?? 'not_started';
                $status_class = '';
                switch($status) {
                    case 'started': $status_class = 'bg-info'; break;
                    case 'in_progress': $status_class = 'bg-warning text-dark'; break;
                    case 'submitted': $status_class = 'bg-primary'; break;
                    case 'graded': $status_class = 'bg-success'; break;
                    default: $status_class = 'bg-secondary'; $status = 'Not Started';
                }
            ?>
                <div class="col-md-6 col-xl-4">
                    <div class="card h-100 shadow-sm border-0 animate__animated animate__fadeInUp">
                        <div class="card-header bg-white border-0 pt-4 px-4 d-flex justify-content-between align-items-start">
                            <span class="badge <?php echo $status_class; ?> text-capitalize p-2">
                                <?php echo str_replace('_', ' ', $status); ?>
                            </span>
                            <small class="text-muted">Due: <?php echo date('M d, Y H:i', strtotime($a['due_date'])); ?></small>
                        </div>
                        <div class="card-body p-4">
                            <h5 class="fw-bold mb-1"><?php echo htmlspecialchars($a['title']); ?></h5>
                            <p class="text-primary small mb-3"><?php echo htmlspecialchars($a['course_name']); ?></p>
                            <p class="text-muted small mb-4"><?php echo htmlspecialchars(substr($a['description'], 0, 120)) . (strlen($a['description']) > 120 ? '...' : ''); ?></p>
                            
                            <?php if ($status == 'graded'): ?>
                                <div class="bg-light p-3 rounded mb-4">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span class="fw-bold small">Grade:</span>
                                        <span class="badge bg-success fs-6"><?php echo $a['grade']; ?>%</span>
                                    </div>
                                    <?php if ($a['feedback']): ?>
                                        <div class="small text-muted italic">
                                            "<?php echo htmlspecialchars($a['feedback']); ?>"
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>

                            <div class="d-grid gap-2 mt-auto">
                                <?php if ($status == 'not_started'): ?>
                                    <form method="POST" class="d-grid">
                                        <input type="hidden" name="assignment_id" value="<?php echo $a['id']; ?>">
                                        <input type="hidden" name="status" value="started">
                                        <button type="submit" name="update_status" class="btn btn-outline-primary">Start Assignment</button>
                                    </form>
                                <?php elseif ($status == 'started'): ?>
                                    <form method="POST" class="d-grid">
                                        <input type="hidden" name="assignment_id" value="<?php echo $a['id']; ?>">
                                        <input type="hidden" name="status" value="in_progress">
                                        <button type="submit" name="update_status" class="btn btn-warning">Mark In Progress</button>
                                    </form>
                                <?php endif; ?>

                                <?php if ($status != 'submitted' && $status != 'graded'): ?>
                                    <a href="submit_assignment.php?id=<?php echo $a['id']; ?>" class="btn btn-primary">
                                        <i class="fas fa-upload me-2"></i>Submit Work
                                    </a>
                                <?php else: ?>
                                    <button class="btn btn-secondary disabled">
                                        <i class="fas fa-check-circle me-2"></i>Submitted on <?php echo date('M d', strtotime($a['submitted_at'])); ?>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<?php include('../footer/footer.php'); ?>
