<?php
/* ============================================================================
 *  check_login_notification.php   →  place in the SAME folder as login.php
 *                                     (e.g. /seven-credit-system/auth/)
 *
 *  Purpose: let the LOGIN screen show the same "New Money Received"
 *  notification the user normally sees on their dashboard — BEFORE they log in.
 *
 *  SECURITY: This endpoint is unauthenticated (same as lookup_user.php), so it
 *  deliberately returns ONLY a COUNT of unread received payments.
 *  It never returns amounts, sender names, balances or transaction details.
 *  Tapping the banner on the login page just asks the person to log in to view.
 * ==========================================================================*/

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

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

$login = trim($_GET['u'] ?? '');
$out   = ['success' => true, 'found' => false, 'unread' => 0];

/* need at least 2 chars before we look anyone up */
if ($login === '' || mb_strlen($login) < 2) {
    echo json_encode($out);
    exit;
}

try {
    /* 1) Resolve the typed login (username / email / customer_code) to a
     *    customer wallet id — only for ACTIVE accounts. */
    $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);

    /* 2) Count unread received payments — identical rule to the dashboard. */
    if ($row && !empty($row['customer_id'])) {
        $out['found'] = true;
        $cnt = $pdo->prepare(
            "SELECT COUNT(*) FROM transactions
              WHERE to_type = 'customer'
                AND to_id = ?
                AND customer_read_at IS NULL"
        );
        $cnt->execute([(int) $row['customer_id']]);
        $out['unread'] = (int) $cnt->fetchColumn();
    }
} catch (Throwable $e) {
    /* fail closed — never leak DB errors to an unauthenticated caller */
    $out = ['success' => false, 'found' => false, 'unread' => 0];
}

echo json_encode($out);