<?php
/**
 * notification_api.php
 * ─────────────────────────────────────────────────────────────────────────────
 * Lightweight AJAX endpoint consumed by the bell icon included in every page.
 *
 * Actions (POST json body OR form-data):
 *   action=count            → returns { unread: N }
 *   action=mark_read        → body: notification_id=N
 *   action=mark_all_read    → marks all eligible notifications as read
 *   action=recent           → returns last 8 notifications with read state
 *
 * Include this URL in your topbar bell JS:  fetch('notification_api.php', ...)
 */

session_start();
include 'config.php';

header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorised']);
    exit();
}

$user_id = $_SESSION['user_id'];
$uid     = mysqli_real_escape_string($conn, $user_id);

/* ── Fetch role / division / location for this user ── */
$me = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT role, division, location FROM users WHERE id = '$uid'"
));
$my_role     = strtolower($me['role']     ?? 'employee');
$my_division = strtolower($me['division'] ?? '');
$my_location = strtolower($me['location'] ?? '');

$mr = mysqli_real_escape_string($conn, $my_role);
$md = mysqli_real_escape_string($conn, $my_division);
$ml = mysqli_real_escape_string($conn, $my_location);

$eligible_where = "
    n.is_active = 1
    AND (n.expires_at IS NULL OR n.expires_at >= CURDATE())
    AND (
        n.target_type = 'all'
        OR (n.target_type = 'role'     AND LOWER(n.target_value) = '$mr')
        OR (n.target_type = 'division' AND LOWER(n.target_value) = '$md')
        OR (n.target_type = 'location' AND LOWER(n.target_value) = '$ml')
        OR (n.target_type = 'user'     AND n.target_value = '$uid')
    )
";

/* ── Parse action ── */
$input  = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_POST['action'] ?? $_GET['action'] ?? '';

/* ══ COUNT ════════════════════════════════════════════════════════════════ */
if ($action === 'count') {
    $result = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COUNT(*) AS cnt
         FROM empnotification n
         LEFT JOIN empnotification_reads r ON r.notification_id = n.id AND r.user_id = '$uid'
         WHERE $eligible_where AND r.id IS NULL"
    ));
    echo json_encode(['unread' => (int)($result['cnt'] ?? 0)]);
    exit();
}

/* ══ MARK ONE READ ════════════════════════════════════════════════════════ */
if ($action === 'mark_read') {
    $nid = intval($input['notification_id'] ?? $_POST['notification_id'] ?? 0);
    if ($nid > 0) {
        mysqli_query($conn,
            "INSERT IGNORE INTO empnotification_reads (notification_id, user_id)
             VALUES ($nid, '$uid')"
        );
    }
    echo json_encode(['ok' => true]);
    exit();
}

/* ══ MARK ALL READ ════════════════════════════════════════════════════════ */
if ($action === 'mark_all_read') {
    $ids_result = mysqli_query($conn,
        "SELECT n.id
         FROM empnotification n
         LEFT JOIN empnotification_reads r ON r.notification_id = n.id AND r.user_id = '$uid'
         WHERE $eligible_where AND r.id IS NULL"
    );
    while ($row = mysqli_fetch_assoc($ids_result)) {
        $nid = (int)$row['id'];
        mysqli_query($conn,
            "INSERT IGNORE INTO empnotification_reads (notification_id, user_id)
             VALUES ($nid, '$uid')"
        );
    }
    echo json_encode(['ok' => true]);
    exit();
}

/* ══ RECENT (for bell dropdown) ═══════════════════════════════════════════ */
if ($action === 'recent') {
    $result = mysqli_query($conn,
        "SELECT n.id, n.title, n.message, n.type, n.created_at,
                (r.id IS NOT NULL) AS is_read
         FROM empnotification n
         LEFT JOIN empnotification_reads r ON r.notification_id = n.id AND r.user_id = '$uid'
         WHERE $eligible_where
         ORDER BY n.created_at DESC
         LIMIT 8"
    );
    $items = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $items[] = [
            'id'         => (int)$row['id'],
            'title'      => $row['title'],
            'message'    => mb_substr($row['message'], 0, 90) . (mb_strlen($row['message']) > 90 ? '…' : ''),
            'type'       => $row['type'],
            'is_read'    => (bool)$row['is_read'],
            'created_at' => $row['created_at'],
            'time_ago'   => relTime($row['created_at']),
        ];
    }
    $unread_count = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT COUNT(*) AS cnt
         FROM empnotification n
         LEFT JOIN empnotification_reads r ON r.notification_id = n.id AND r.user_id = '$uid'
         WHERE $eligible_where AND r.id IS NULL"
    ));
    echo json_encode(['items' => $items, 'unread' => (int)($unread_count['cnt'] ?? 0)]);
    exit();
}

/* ── Default ── */
http_response_code(400);
echo json_encode(['error' => 'Unknown action']);
exit();

function relTime($dt) {
    $diff = time() - strtotime($dt);
    if ($diff < 60)    return 'Just now';
    if ($diff < 3600)  return floor($diff/60) . 'm ago';
    if ($diff < 86400) return floor($diff/3600) . 'h ago';
    if ($diff < 604800) return floor($diff/86400) . 'd ago';
    return date('d M Y', strtotime($dt));
}