<?php

declare(strict_types=1);

require_once __DIR__ . '/tp_auth.php';



$teacher_id = tp_require_auth();

$conn       = getDBConnection();



$page  = max(1, (int)($_GET['page'] ?? 1));

$limit = 20;

$offset = ($page - 1) * $limit;



// Announcements for teachers: target_role IN ('all', 'tutor')

$stmt = $conn->prepare(

    "SELECT a.id, a.title, a.body AS message, a.target_role,

            a.created_at,

            COALESCE(u.full_name, 'Admin') AS author

       FROM announcements a

       LEFT JOIN users u ON u.id = a.created_by

      WHERE a.target_role IN ('all', 'tutor')

      ORDER BY a.created_at DESC

      LIMIT ? OFFSET ?"

);

$stmt->bind_param('ii', $limit, $offset);

$stmt->execute();

$notices = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stmt->close();



$r = $conn->query(

    "SELECT COUNT(*) AS n FROM announcements

      WHERE target_role IN ('all','tutor')"

);

$total = (int)($r ? $r->fetch_assoc()['n'] : 0);



tp_json(true, [

    'notices'    => $notices,

    'total'      => $total,

    'page'       => $page,

    'pages'      => (int)ceil($total / $limit),

]);

