<?php
/* ============================================================================
 *  dismiss_login_notification.php   →  place in the SAME folder as login.php
 *
 *  Marks ONE received-payment notification as read, from the login screen,
 *  when the user taps the ✕ on a card.
 *
 *  SAFETY: This is callable without logging in, so it is tightly scoped:
 *   - it requires BOTH the account identifier (username/email/customer_code)
 *     AND the transaction id;
 *   - it only ever sets customer_read_at = NOW() on a row that is genuinely a
 *     received payment (to_type='customer') belonging to THAT account and
 *     still unread. It cannot read data back, move money, or change anything
 *     else. Worst case a guesser can mark someone's own alerts read.
 * ==========================================================================*/

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

require_once '../config/database.php';

/* accept JSON body or normal POST fields */
$raw  = file_get_contents('php://input');
$body = json_decode($raw, true);
if (!is_array($body)) { $body = $_POST; }

$login = trim($body['u'] ?? '');
$txId  = (int) ($body['id'] ?? 0);

$out = ['success' => false];

if ($login === '' || mb_strlen($login) < 2 || $txId <= 0) {
    echo json_encode($out);
    exit;
}

try {
    /* resolve the account → its customer wallet id (active accounts only) */
    $hasUsername = (bool) $pdo->query("SHOW COLUMNS FROM users LIKE 'username'")->fetch();

    if ($hasUsername) {
        $sql = "SELECT c.id AS customer_id
                  FROM customers c
                  JOIN users u ON u.id = c.user_id
                 WHERE (u.username = ? OR u.email = ? OR c.customer_code = ?)
                   AND u.status = 'active'
                 LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$login, $login, $login]);
    } else {
        $sql = "SELECT c.id AS customer_id
                  FROM customers c
                  JOIN users u ON u.id = c.user_id
                 WHERE (u.email = ? OR c.customer_code = ?)
                   AND u.status = 'active'
                 LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$login, $login]);
    }

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row && !empty($row['customer_id'])) {
        $cid = (int) $row['customer_id'];

        /* mark ONLY this account's own unread received payment as read */
        $upd = $pdo->prepare(
            "UPDATE transactions
                SET customer_read_at = NOW()
              WHERE id = ?
                AND to_type = 'customer'
                AND to_id = ?
                AND customer_read_at IS NULL"
        );
        $upd->execute([$txId, $cid]);

        $out['success'] = true;
        $out['updated'] = $upd->rowCount();   // 1 if it was marked, 0 if already read / not theirs
    }
} catch (Throwable $e) {
    $out = ['success' => false];
}

echo json_encode($out);