<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

$userlogin = $_SESSION['studentid'];
$intake    = $_SESSION['intake'];
$program   = $_SESSION['program'];

if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

// HANDLE SUBMISSION BEFORE ANY OUTPUT
if (isset($_POST['submit_work'])) {
    $assignmentId   = $_POST['assignment_id'];
    $studentId      = $_SESSION['studentid'];
    $uploadDir      = "submissions/";
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

    // Fetch assignment details
    $sql_assign = "SELECT program, intake, year, period, email, course FROM assignments WHERE id='$assignmentId'";
    $res_assign = mysqli_query($conn, $sql_assign);
    $assign = mysqli_fetch_assoc($res_assign);

    $program       = $assign['program'];
    $intake        = $assign['intake'];
    $year          = $assign['year'];
    $period        = $assign['period'];
    $teacher_email = $assign['email'];
    $course        = $assign['course'];

    $fileName   = basename($_FILES["submission"]["name"]);
    $targetFile = $uploadDir . time() . "_" . $fileName;

    if (move_uploaded_file($_FILES["submission"]["tmp_name"], $targetFile)) {
        $sql = "INSERT INTO submit 
        (assignment_id, student_id, program, course, intake, year, period, email, file, marks, submitted_at)
        VALUES 
        ('$assignmentId', '$studentId', '$program', '$course', '$intake', '$year', '$period', '$teacher_email', '$targetFile', 0, NOW())
        ON DUPLICATE KEY UPDATE 
        file='$targetFile', 
        marks=0,
        submitted_at=NOW()";

        if (mysqli_query($conn, $sql)) {
            header("Location: assignment.php?success=Assignment Successfully Submitted");
            exit();
        } else {
            $error = "Database error: " . mysqli_error($conn);
        }
    } else {
        $error = "Failed to upload file.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
      <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <link rel="icon" href="favicon.png" type="image/png">
   <!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <meta name="theme-color" content="var(--primary)">
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rowdies:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
.content{
    padding:15px;
}
</style>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <div class="in." style="padding:15px">
        <h5 style='color:var(--primary); margin-bottom:15px;'>  
            <img src="icons/write.png" width="40px"/> Assignments
        </h5>

        <?php
        if (isset($error)) echo "<div style='color:red;'>$error</div>";
        if (isset($_GET['success'])) echo "<div style='color:green;'>{$_GET['success']}</div>";

        // Fetch assignments
        $query = "SELECT id, program, period, intake, file, course, email, posteddate, duedate, year
                  FROM assignments
                  WHERE program = '$program' AND intake = '$intake'
                  ORDER BY posteddate DESC";
        $result = mysqli_query($conn, $query);

        $grouped = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $key = $row['year'] . ' - ' . $row['period']. ' - '.$row['course'];
            $grouped[$key][] = $row;
        }

        foreach ($grouped as $group => $rows) {
            echo "<div style='margin:10px 0; font-weight:bold; color:#444; font-size:16px;'>📘 Year/Semester: $group</div>";

            foreach ($rows as $r) {
                $due = strtotime($r['duedate']);
                $now = time();
                $isOverdue = ($due < $now);

                // Check if student already submitted
                $checkSubmit = mysqli_query($conn, "SELECT * FROM submit WHERE assignment_id='{$r['id']}' AND student_id='$userlogin'");
                $submitted = mysqli_num_rows($checkSubmit) > 0 ? true : false;

                $submitText = $submitted ? "✔️ Submitted" : "✍️ Submit";
                $btnDisabled = $isOverdue || $submitted ? "disabled" : "";

                $btnColor = $submitted ? "#FFA500" : "var(--primary)"; // orange if submitted

                echo "
                <div style='background:#fff; width:100%; border-radius:12px; box-shadow:0 2px 6px rgba(0,0,0,0.08); margin-bottom:12px; padding:14px 16px;'>
                    <div style='font-size:15px; font-weight:600; color:var(--primary);'>{$r['course']}</div>
                    <div style='font-size:13px; margin-top:4px;'>📅 Posted: <span style='color:#666;'>{$r['posteddate']}</span></div>
                    <div style='font-size:13px; margin-top:2px;'>⏳ Due: <span style='color:".($isOverdue?"red":"var(--primary)")."; font-weight:bold;'>{$r['duedate']}</span></div>
                    <div style='margin-top:6px; display:flex; gap:10px;'>
                        <a href='uploads/{$r['file']}' target='_blank' style='display:inline-block; padding:6px 12px; background:var(--primary); color:#fff; border-radius:8px; font-size:13px; text-decoration:none;'>📂 Download</a>
                        <button class='btn btn-sm' data-toggle='modal' data-target='#submitModal{$r['id']}' style='background:$btnColor; color:#fff;' $btnDisabled>$submitText</button>
                    </div>
                </div>

                <!-- SUBMISSION MODAL -->
                <div class='modal fade' id='submitModal{$r['id']}' tabindex='-1' role='dialog'>
                    <div class='modal-dialog modal-dialog-centered' role='document'>
                        <div class='modal-content'>
                            <div class='modal-header'>
                                <h5 class='modal-title'>Submit Assessment - {$r['course']}</h5>
                                <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                    <span aria-hidden='true'>&times;</span>
                                </button>
                            </div>
                            <form method='POST' enctype='multipart/form-data'>
                                <div class='modal-body'>
                                    <input type='hidden' name='assignment_id' value='{$r['id']}'>
                                    <input type='hidden' name='program' value='{$r['program']}'>
                                    <input type='hidden' name='course' value='{$r['course']}'>
                                    <input type='hidden' name='intake' value='{$r['intake']}'>
                                    <input type='hidden' name='year' value='{$r['year']}'>
                                    <input type='hidden' name='period' value='{$r['period']}'>
                                    <input type='hidden' name='teacher_email' value='{$r['email']}'>
                                    <div class='form-group'>
                                        <label>Upload File</label>
                                        <input type='file' name='submission' accept='.pdf,.doc,.docx,.zip' class='form-control' required $btnDisabled>
                                    </div>
                                </div>
                                <div class='modal-footer'>
                                    <button type='submit' name='submit_work' class='btn btn-success' $btnDisabled>Submit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                ";
            }
        }
        ?>
    </div>
</div>
</body>
</html>