<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

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

// Load variables from POST or SESSION
$program = $_POST['program'] ?? $_SESSION['program'] ?? '';
$period  = $_POST['period']  ?? $_SESSION['period']  ?? '';
$intake  = $_POST['intake']  ?? $_SESSION['intake']  ?? '';
$course  = $_POST['course']  ?? $_SESSION['course']  ?? '';
$year    = $_POST['year']    ?? $_SESSION['year']    ?? '';
$email   = $_POST['email']   ?? $_SESSION['email']   ?? '';

// Save to SESSION
if (isset($_POST['submit'])) {
    $_SESSION['program'] = $program;
    $_SESSION['period']  = $period;
    $_SESSION['intake']  = $intake;
    $_SESSION['course']  = $course;
    $_SESSION['year']    = $year;
    $_SESSION['email']   = $email;
}

$success = "";
$error = "";

// Get submission counts
$total_count_sql = "SELECT COUNT(*) as total_count 
                   FROM submit 
                   WHERE program='$program' 
                     AND period='$period' 
                     AND intake='$intake' 
                     AND course='$course' 
                     AND year='$year' 
                     AND email='$email'";
$total_count_result = $conn->query($total_count_sql);
$total_count = $total_count_result->fetch_assoc()['total_count'];

$graded_count_sql = "SELECT COUNT(*) as graded_count 
                    FROM submit 
                    WHERE program='$program' 
                      AND period='$period' 
                      AND intake='$intake' 
                      AND course='$course' 
                      AND year='$year' 
                      AND email='$email'
                      AND marks IS NOT NULL 
                      AND marks != ''";
$graded_count_result = $conn->query($graded_count_sql);
$graded_count = $graded_count_result->fetch_assoc()['graded_count'];

$pending_count_sql = "SELECT COUNT(*) as pending_count 
                     FROM submit 
                     WHERE program='$program' 
                       AND period='$period' 
                       AND intake='$intake' 
                       AND course='$course' 
                       AND year='$year' 
                       AND email='$email'
                       AND (marks IS NULL OR marks = '')";
$pending_count_result = $conn->query($pending_count_sql);
$pending_count = $pending_count_result->fetch_assoc()['pending_count'];

// Export functionality
if (isset($_POST['export_results'])) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=assignment_results_' . date('Y-m-d') . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // CSV header
    fputcsv($output, array('Student ID', 'Program', 'Course', 'Intake', 'Year', 'Semester', 'Marks', 'Submitted At'));
    
    // Query submissions
    $export_sql = "SELECT `student_id`, `program`, `course`, `intake`, `year`, `period`, `marks`, `submitted_at` 
            FROM submit 
            WHERE program='$program' 
              AND period='$period' 
              AND intake='$intake' 
              AND course='$course' 
              AND year='$year' 
              AND email='$email'
            ORDER BY submitted_at DESC";
    $export_result = $conn->query($export_sql);
    
    if ($export_result->num_rows > 0) {
        while($row = $export_result->fetch_assoc()) {
            fputcsv($output, array(
                $row['student_id'],
                $row['program'],
                $row['course'],
                $row['intake'],
                $row['year'],
                ($row['period'] == "1" ? "Semester 1" : ($row['period'] == "2" ? "Semester 2" : "-")),
                $row['marks'] !== null && $row['marks'] !== '' ? $row['marks'] : 'Not Graded',
                $row['submitted_at']
            ));
        }
    }
    fclose($output);
    exit();
}

if (isset($_POST['update_marks'])) {
    $submission_id = intval($_POST['submission_id']);
    $marks = intval($_POST['marks']);

    // Update marks in submit table
    $update = $conn->query("UPDATE submit SET marks = '$marks' WHERE id = '$submission_id'");

    if ($update) {
        $sub = $conn->query("SELECT student_id, course, intake, year, period AS term, marks 
                             FROM submit WHERE id = '$submission_id' LIMIT 1");
        if ($sub && $sub->num_rows > 0) {
            $row = $sub->fetch_assoc();
            $studentid = $conn->real_escape_string($row['student_id']);
            $course    = $conn->real_escape_string($row['course']);
            $intake    = $conn->real_escape_string($row['intake']);
            $year      = $conn->real_escape_string($row['year']);
            $term      = $conn->real_escape_string($row['term']);
            $new_marks = intval($row['marks']);

            // Check existing record in results
            $check = $conn->query("SELECT * FROM results 
                                   WHERE studentid='$studentid' AND course='$course' 
                                   AND intake='$intake' AND year='$year' AND term='$term' LIMIT 1");

            if ($check && $check->num_rows > 0) {
                $r = $check->fetch_assoc();

                // Clear sequential logic: Checks ca → ca1 → ca2 in order
                if (empty($r['ca']) || $r['ca'] === '' || $r['ca'] === null) {
                    // Step 1: Check CA field first
                    $update_query = $conn->query("UPDATE results SET ca='$new_marks' 
                                          WHERE studentid='$studentid' AND course='$course' 
                                          AND intake='$intake' AND year='$year' AND term='$term'");
                    if (!$update_query) {
                        $_SESSION['error'] = "Error updating CA marks: " . $conn->error;
                        header("location:assignmentsubmited.php");
                        exit();
                    }
                } 
                elseif (empty($r['ca1']) || $r['ca1'] === '' || $r['ca1'] === null) {
                    // Step 2: If CA is filled, check CA1 field next
                    $update_query = $conn->query("UPDATE results SET ca1='$new_marks' 
                                          WHERE studentid='$studentid' AND course='$course' 
                                          AND intake='$intake' AND year='$year' AND term='$term'");
                    if (!$update_query) {
                        $_SESSION['error'] = "Error updating CA1 marks: " . $conn->error;
                        header("location:assignmentsubmited.php");
                        exit();
                    }
                }
                elseif (empty($r['ca2']) || $r['ca2'] === '' || $r['ca2'] === null) {
                    // Step 3: If both CA and CA1 are filled, check CA2 field last
                    $update_query = $conn->query("UPDATE results SET ca2='$new_marks' 
                                          WHERE studentid='$studentid' AND course='$course' 
                                          AND intake='$intake' AND year='$year' AND term='$term'");
                    if (!$update_query) {
                        $_SESSION['error'] = "Error updating CA2 marks: " . $conn->error;
                        header("location:assignmentsubmited.php");
                        exit();
                    }
                }
                else {
                    // All three CA fields are already filled
                    $_SESSION['error'] = "All CA slots (ca, ca1, ca2) are already filled for this student.";
                    header("location:assignmentsubmited.php");
                    exit();
                }

            } else {
                // No existing record - insert new one with marks in CA field
                $sql_insert = "
                    INSERT INTO results (studentid, course, intake, term, year, ca, ca1, ca2)
                    VALUES ('$studentid', '$course', '$intake', '$term', '$year', '$new_marks', NULL, NULL)
                ";
                $insert_query = $conn->query($sql_insert);
                if (!$insert_query) {
                    $_SESSION['error'] = "Error inserting results: " . $conn->error;
                    header("location:assignmentsubmited.php");
                    exit();
                }
            }

            $_SESSION['success'] = "Marks updated successfully and stored in results.";
            header("location:assignmentsubmited.php");
            exit();
        }
    } else {
        $_SESSION['error'] = "Error updating submit table: " . $conn->error;
        header("location:assignmentsubmited.php");
        exit();
    }
}

// Query submissions
$sql = "SELECT `id`, `assignment_id`, `student_id`, `program`, `course`, 
               `intake`, `year`, `period`, `email`, `file`, `marks`, `submitted_at` 
        FROM submit 
        WHERE program='$program' 
          AND period='$period' 
          AND intake='$intake' 
          AND course='$course' 
          AND year='$year' 
          AND email='$email'
        ORDER BY submitted_at DESC";
$result = $conn->query($sql);

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Submitted Assignments</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    .stats-card {
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .stats-card.total { background: linear-gradient(45deg, #28a745, #20c997); color: white; }
    .stats-card.graded { background: linear-gradient(45deg, #007bff, #0056b3); color: white; }
    .stats-card.pending { background: linear-gradient(45deg, #ffc107, #e0a800); color: white; }
    .stats-number {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    .stats-label {
        font-size: 1rem;
        opacity: 0.9;
    }
    .table-responsive {
        max-height: 600px;
        overflow-y: auto;
    }
  </style>
</head>
<body>
<?php include "../include/nav.php"; ?>
<div class="content">
<div class="container mt-5">
  <h3 class="mb-4 text"><i class="fa fa-tasks"></i> Submitted Assignments</h3>

  <!-- Statistics Cards -->
  <div class="row mb-4">
    <div class="col-md-4">
      <div class="stats-card total text-center">
        <div class="stats-number"><?= $total_count ?></div>
        <div class="stats-label"><i class="fa fa-paper-plane"></i> Total Submissions</div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="stats-card graded text-center">
        <div class="stats-number"><?= $graded_count ?></div>
        <div class="stats-label"><i class="fa fa-check-circle"></i> Marked</div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="stats-card pending text-center">
        <div class="stats-number"><?= $pending_count ?></div>
        <div class="stats-label"><i class="fa fa-clock"></i> Pending Marking</div>
      </div>
    </div>
  </div>

  <!-- Export Button -->
  <form method="post" class="mb-3">
    <button type="submit" name="export_results" class="btn btn-success">
        <i class="fa fa-download"></i> Export Results to CSV
    </button>
  </form>

  <!-- Success -->
  <?php if(isset($_SESSION['success'])): ?>
    <div class="alert alert-success text-center">
      <i class="fa fa-check-circle"></i> <?= $_SESSION['success']; ?>
    </div>
    <?php unset($_SESSION['success']); ?>
  <?php endif; ?>

  <!-- Error -->
  <?php if(isset($_SESSION['error'])): ?>
    <div class="alert alert-danger text-center">
      <i class="fa fa-exclamation-triangle"></i> <?= $_SESSION['error']; ?>
    </div>
    <?php unset($_SESSION['error']); ?>
  <?php endif; ?>

  <!-- Search -->
  <div class="mb-3">
    <input type="text" id="searchInput" class="form-control" placeholder="Search by student ID, email, course, program...">
  </div>

  <div class="table-responsive">
    <table class="table table-bordered table-striped align-middle" id="submissionsTable">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Student ID</th>
          <th>Program</th>
          <th>Course</th>
          <th>Intake</th>
          <th>Year</th>
          <th>Semester</th>
          <th>File</th>
          <th>Submitted At</th>
          <th>Marks</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
      <?php if ($result->num_rows > 0) { 
        $sn = 1;
        while($row = $result->fetch_assoc()) { 
          // Check if marks are graded (not null, not empty string)
          $marks = $row['marks'];
          $is_graded = ($marks !== null && $marks !== '' && $marks !== 'NULL' && $marks !== 'null');
        ?>
        <tr>
          <td><?= $sn++; ?></td>
          <td><?= htmlspecialchars($row['student_id']); ?></td>
          <td><?= htmlspecialchars($row['program']); ?></td>
          <td><?= htmlspecialchars($row['course']); ?></td>
          <td><?= htmlspecialchars($row['intake']); ?></td>
          <td><?= htmlspecialchars($row['year']); ?></td>
          <td><?= $row['period']=="1"?"Semester 1":($row['period']=="2"?"Semester 2":"-"); ?></td>
          <td>
            <?php if (!empty($row['file'])) { ?>
              <a href="../../students/login/<?= htmlspecialchars($row['file']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                <i class="fa fa-download"></i> View
              </a>
            <?php } else { echo "No File"; } ?>
          </td>
          <td><?= htmlspecialchars($row['submitted_at']); ?></td>
          <td>
            <?php if ($is_graded) { ?>
              <span class="badge bg-success"><?= htmlspecialchars($marks) ?></span>
            <?php } else { ?>
              <span class="badge bg-warning text-dark">Not Graded</span>
            <?php } ?>
          </td>
          <td>
            <?php if ($is_graded) { ?>
              <button class="btn btn-sm btn-secondary" disabled title="Already graded">
                  <i class="fa fa-lock"></i> Locked
              </button>
            <?php } else { ?>
              <!-- Modal trigger -->
              <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#markModal<?= $row['id']; ?>">
                <i class="fa fa-edit"></i> Grade
              </button>
            <?php } ?>
          </td>
        </tr>

        <!-- Modal -->
        <div class="modal fade" id="markModal<?= $row['id']; ?>" tabindex="-1">
          <div class="modal-dialog">
            <div class="modal-content">
              <form method="post">
                <div class="modal-header">
                  <h5 class="modal-title">Grade Assignment</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                  <p><strong>Student ID:</strong> <?= htmlspecialchars($row['student_id']); ?></p>
                  <p><strong>Email:</strong> <?= htmlspecialchars($row['email']); ?></p>
                  <p><strong>Course:</strong> <?= htmlspecialchars($row['course']); ?></p>
                  <div class="mb-3">
                    <label class="form-label">Marks</label>
                    <input type="number" name="marks" class="form-control" value="0" min="0" max="100" required>
                  </div>
                  <input type="hidden" name="submission_id" value="<?= $row['id']; ?>">
                </div>
                <div class="modal-footer">
                  <button type="submit" name="update_marks" class="btn btn-primary">Save Marks</button>
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      <?php } } else { ?>
        <tr><td colspan="11" class="text-center text-muted">No submissions found for the selected criteria.</td></tr>
      <?php } ?>
      </tbody>
    </table>
  </div>
</div>

<script>
// Table search
document.getElementById("searchInput").addEventListener("keyup", function() {
  let filter = this.value.toLowerCase();
  document.querySelectorAll("#submissionsTable tbody tr").forEach(row => {
    let text = row.textContent.toLowerCase();
    row.style.display = text.includes(filter) ? "" : "none";
  });
});

// Auto-focus on search input
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('searchInput').focus();
});
</script>

</body>
</html>