[]]); exit; } $user_id = $_SESSION['user_id']; $role = $_SESSION['role'] ?? 'student'; $filter = $_GET['filter'] ?? 'urgent'; $days_before = getSetting($pdo, 'days_before_due') ?: 3; $sql = "SELECT a.id, a.title, a.due_date, a.status, a.created_at, u.name as student_name, DATEDIFF(a.due_date, CURDATE()) as days_left FROM assignments a LEFT JOIN users u ON a.student_id = u.id WHERE 1=1"; $params = []; if ($role !== 'admin') { $sql .= " AND a.student_id = :student_id"; $params[':student_id'] = $user_id; } if ($filter === 'urgent') { $sql .= " AND a.status = 'pending' AND DATEDIFF(a.due_date, CURDATE()) <= :days_before AND DATEDIFF(a.due_date, CURDATE()) >= 0"; $params[':days_before'] = $days_before; } elseif ($filter === 'pending') { $sql .= " AND a.status = 'pending'"; } elseif ($filter === 'completed') { $sql .= " AND a.status = 'completed'"; } // "งานที่ถูกเพิ่มล่าสุดอยู่บนสุด" $sql .= " ORDER BY a.id DESC"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $assignments = $stmt->fetchAll(); $data = []; foreach ($assignments as $index => $item) { $status_html = ''; if ($item['status'] === 'pending') { $status_html = 'รอดำเนินการ'; } else { $status_html = 'เสร็จสิ้น'; } // Date formatting: วัน-เดือน-ปี (พ.ศ.) $due_timestamp = strtotime($item['due_date']); $due_date_th = date('d-m-', $due_timestamp) . (date('Y', $due_timestamp) + 543); $created_timestamp = strtotime($item['created_at']); $created_date_th = date('d-m-', $created_timestamp) . (date('Y', $created_timestamp) + 543); $due_html = $due_date_th; if ($item['status'] === 'pending') { if ($item['days_left'] < 0) { // เลยกำหนด สีดำ $due_html = "{$due_date_th} เลยกำหนด " . abs($item['days_left']) . " วัน"; } elseif ($item['days_left'] <= $days_before) { // อยู่ในช่วงเตือน สีส้ม $due_html = "{$due_date_th} เหลือ {$item['days_left']} วัน"; } else { // ปกติ $due_html = "{$due_date_th} เหลือ {$item['days_left']} วัน"; } } $row = [ 'index' => $index + 1, 'title' => htmlspecialchars($item['title'] ?? ''), 'created_at' => $created_date_th, 'due_date' => $due_html, 'status' => $status_html ]; if ($role === 'admin') { $row['student'] = htmlspecialchars($item['student_name'] ?? 'ไม่ระบุ'); } $data[] = $row; } echo json_encode(['data' => $data]); } catch (Exception $e) { // Return error as JSON so DataTables can at least parse it, or we can see it in network tab echo json_encode(['error' => $e->getMessage(), 'data' => []]); }