<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");

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

if (!isset($_SESSION["username_" . $dbname])) {
    echo json_encode(['error' => 'not logged in']);
    exit;
}

$zdb      = $_SESSION["zdbyear_" . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];

if (!$zdb) {
    echo json_encode(['items' => [], 'unread' => 0]);
    exit;
}
mysqli_select_db($conn, $zdb);

// ── Self-provision the `notifications` table ────────────────────────────
// Never had a CREATE TABLE anywhere in this codebase (unlike every other
// table this app writes to), so on a DB that never had it hand-created,
// every insert/list/read below was silently dying (mysqli_error) and the
// bell just looked broken. Same auto-migration convention used everywhere
// else here (see transacn in sale.php, dispatchalert_update.php, etc).
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `notifications` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `vouchno` INT(11) NOT NULL DEFAULT 0,
    `reftype` VARCHAR(20) NOT NULL DEFAULT '',
    `audience` VARCHAR(30) NOT NULL DEFAULT '',
    `action` VARCHAR(20) NOT NULL DEFAULT '',
    `message` VARCHAR(255) NOT NULL DEFAULT '',
    `readflag` VARCHAR(1) NOT NULL DEFAULT '',
    `createduser` VARCHAR(50) NOT NULL DEFAULT '',
    `createddate` DATE NULL,
    `createdtime` TIME NULL,
    PRIMARY KEY (`id`),
    KEY `audience` (`audience`),
    KEY `vouchno` (`vouchno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$action    = isset($_POST['action']) ? $_POST['action'] : 'list';
$agentcode = (int)($_SESSION["agentcode_" . $dbname] ?? 0);

// Determine which audiences this user can see
// (Bill Confirmation / China audience removed — that workflow belongs to a
// different application; this bell now only surfaces Sale Order / Sale
// Invoice activity for admin and the relevant salesman.)
$audiences = [];
if ($usertype == 1)        $audiences[] = "'admin'";
// Salesman (usertype 3) sees notifications aimed at them specifically —
// e.g. "your Sale Order was dispatched" — see dispatchalert_update.php.
if ($usertype == 3 && $agentcode > 0) $audiences[] = "'salesman_$agentcode'";

if ($action == 'list') {
    if (count($audiences) == 0) {
        echo json_encode(['items' => [], 'unread' => 0]);
        exit;
    }
    $aud = implode(',', $audiences);
    $r = mysqli_query($conn, "SELECT * FROM `notifications` WHERE `audience` IN ($aud) ORDER BY `id` DESC LIMIT 20")
        or die(mysqli_error($conn));

    $items = [];
    $unread = 0;
    while ($row = mysqli_fetch_assoc($r)) {
        if ($row['readflag'] != 'Y') $unread++;
        $items[] = [
            'id'        => (int)$row['id'],
            'vouchno'   => (int)$row['vouchno'],
            'reftype'   => $row['reftype'],
            'audience'  => $row['audience'],
            'action'    => $row['action'],
            'message'   => $row['message'],
            'readflag'  => $row['readflag'],
            'createduser' => $row['createduser'],
            'createddate' => $row['createddate'],
        ];
    }
    echo json_encode(['items' => $items, 'unread' => $unread]);
    exit;
}

if ($action == 'read') {
    $id = (int)($_POST['id'] ?? 0);
    mysqli_query($conn, "UPDATE `notifications` SET `readflag`='Y' WHERE `id`='$id'") or die(mysqli_error($conn));
    echo json_encode(['ok' => true]);
    exit;
}

if ($action == 'readall') {
    if (count($audiences) > 0) {
        $aud = implode(',', $audiences);
        mysqli_query($conn, "UPDATE `notifications` SET `readflag`='Y' WHERE `audience` IN ($aud)") or die(mysqli_error($conn));
    }
    echo json_encode(['ok' => true]);
    exit;
}

echo json_encode(['error' => 'unknown action']);
