<?php
/* ============================================================================
 *  check_login_notification.php   →  place in the SAME folder as login.php
 *                                     (e.g. /seven-credit-system/auth/)
 *
 *  Powers the "New Money Received" notifications on the LOGIN screen — one
 *  card per unread received payment, newest first.
 *
 *  Returns, for an identified account, the list of UNREAD received payments
 *  with sender name, amount and time. Used before login, so it only ever
 *  reads received-money rows for the account whose username/email/code was
 *  supplied — nothing else.
 * ==========================================================================*/

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, 'items' => []];

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);

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

        /* 2) Total unread count (same rule as the dashboard). */
        $cnt = $pdo->prepare(
            "SELECT COUNT(*) FROM transactions
              WHERE to_type = 'customer' AND to_id = ? AND customer_read_at IS NULL"
        );
        $cnt->execute([$cid]);
        $out['unread'] = (int) $cnt->fetchColumn();

        /* 3) The unread payments themselves, newest first, with sender resolved.
         *    from_type 'customer' -> customers.full_name
         *    from_type 'partner'  -> partner_shops.shop_name
         *    from_type 'admin'    -> Seven Digital */
        $q = $pdo->prepare("
            SELECT t.id, t.amount, t.created_at, t.from_type, t.from_id,
                   cu.full_name AS customer_name,
                   ps.shop_name  AS partner_name
              FROM transactions t
              LEFT JOIN customers     cu ON (t.from_type = 'customer' AND cu.id = t.from_id)
              LEFT JOIN partner_shops ps ON (t.from_type = 'partner'  AND ps.id = t.from_id)
             WHERE t.to_type = 'customer'
               AND t.to_id = ?
               AND t.customer_read_at IS NULL
             ORDER BY t.created_at DESC, t.id DESC
             LIMIT 20
        ");
        $q->execute([$cid]);
        $rows = $q->fetchAll(PDO::FETCH_ASSOC);

        $items = [];
        foreach ($rows as $r) {
            if ($r['from_type'] === 'customer') {
                $sender = $r['customer_name'] ?: 'Customer';
            } elseif ($r['from_type'] === 'partner') {
                $sender = $r['partner_name'] ?: 'Shop';
            } else {
                $sender = 'Seven Digital';
            }
            $amt = (float) $r['amount'];

            /* DB stores times in UTC (server default) — convert to Lao time (UTC+7)
               so the card shows the real local time the payment arrived. */
            $createdLocal = $r['created_at'];
            try {
                $dt = new DateTime($r['created_at'], new DateTimeZone('UTC'));
                $dt->setTimezone(new DateTimeZone('Asia/Vientiane'));
                $createdLocal = $dt->format('Y-m-d H:i:s');
            } catch (Throwable $e) { /* keep raw value if parsing fails */ }

            $items[] = [
                'id'         => (int) $r['id'],
                'sender'     => $sender,
                'amount'     => $amt,
                'amount_fmt' => number_format($amt, fmod($amt, 1) == 0.0 ? 0 : 2),
                'created_at' => $createdLocal,
            ];
        }
        $out['items'] = $items;
    }
} catch (Throwable $e) {
    /* fail closed — never leak DB errors to an unauthenticated caller */
    $out = ['success' => false, 'found' => false, 'unread' => 0, 'items' => []];
}

echo json_encode($out);