<?php
/**
 * customer/ajax/lookup.php
 * Public endpoint — no session required.
 * Returns points balance + transaction history for a card code.
 * Read-only. Never reveals personal data beyond what the cardholder owns.
 */
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/functions.php';

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

// Rate-limit: max 20 lookups per IP per minute (simple in-session counter)
if (session_status() === PHP_SESSION_NONE) session_start();
$now = time();
$_SESSION['cust_hits'] = array_filter(
    $_SESSION['cust_hits'] ?? [],
    fn($t) => $t > $now - 60
);
$_SESSION['cust_hits'][] = $now;
if (count($_SESSION['cust_hits']) > 20) {
    jsonResponse(['success' => false, 'error' => 'Too many requests. Please wait a moment.'], 429);
}

$cardCode = trim($_POST['card_code'] ?? $_GET['card_code'] ?? '');
if (!$cardCode) {
    jsonResponse(['success' => false, 'error' => 'Please enter your card number.']);
}

$db   = getDB();
$stmt = $db->prepare("SELECT * FROM members WHERE card_code = ? AND status = 'active'");
$stmt->execute([$cardCode]);
$member = $stmt->fetch();

if (!$member) {
    jsonResponse(['success' => false, 'error' => 'Card not found. Check your card number and try again.']);
}

if (!$member['name']) {
    jsonResponse(['success' => false, 'error' => 'This card has not been registered yet. Please visit the store to register.']);
}

// Points balance
$balance = getMemberBalance((int)$member['id']);

// Points expiry
$expiryDays = (int)(getSetting('expiry_days', 0));
$expiryNote = '';
if ($expiryDays > 0 && $balance > 0) {
    // Find oldest earn transaction
    $oldestStmt = $db->prepare("
        SELECT created_at FROM transactions
        WHERE member_id = ? AND type = 'earn'
        ORDER BY created_at ASC LIMIT 1
    ");
    $oldestStmt->execute([$member['id']]);
    $oldest = $oldestStmt->fetchColumn();
    if ($oldest) {
        $expiryDate = date('F j, Y', strtotime($oldest) + $expiryDays * 86400);
        $daysLeft   = ceil((strtotime($oldest) + $expiryDays * 86400 - $now) / 86400);
        if ($daysLeft > 0) {
            $expiryNote = 'Points expire in ' . $daysLeft . ' day' . ($daysLeft === 1 ? '' : 's') . ' (' . $expiryDate . ')';
        } else {
            $expiryNote = 'Some points may have expired.';
        }
    }
}

// Redemption value
$pointPesoVal = (float)(getSetting('point_peso_value', 1));
$minRedeem    = (int)(getSetting('min_redeem', 50));
$redeemValue  = round($balance * $pointPesoVal, 2);
$canRedeem    = $balance >= $minRedeem;

// Recent transactions (last 10)
$txnStmt = $db->prepare("
    SELECT type, amount, points, created_at, notes
    FROM transactions
    WHERE member_id = ?
    ORDER BY created_at DESC
    LIMIT 10
");
$txnStmt->execute([$member['id']]);
$transactions = $txnStmt->fetchAll();

// Stats
$statsStmt = $db->prepare("
    SELECT
        COUNT(*) AS total_txns,
        COALESCE(SUM(CASE WHEN type='earn' THEN amount ELSE 0 END), 0) AS total_spend,
        COALESCE(SUM(CASE WHEN type='earn' THEN points ELSE 0 END), 0) AS total_earned,
        COALESCE(SUM(CASE WHEN type='redeem' THEN points ELSE 0 END), 0) AS total_redeemed
    FROM transactions WHERE member_id = ?
");
$statsStmt->execute([$member['id']]);
$stats = $statsStmt->fetch();

// Store design
$design = [
    'store_name'     => getSetting('store_name',           'Rewards'),
    'bg_type'        => getSetting('card_bg_type',         'gradient'),
    'gradient_dir'   => getSetting('card_gradient_dir',    '135deg'),
    'color1'         => getSetting('card_gradient_color1', '#1e3a8a'),
    'color2'         => getSetting('card_gradient_color2', '#1d4ed8'),
    'color3'         => getSetting('card_gradient_color3', '#0ea5e9'),
    'text_color'     => getSetting('card_text_color',      '#ffffff'),
    'accent_color'   => getSetting('card_accent_color',    '#facc15'),
    'bg_image'       => getSetting('card_bg_image',        ''),
    'logo_icon'      => getSetting('card_logo_icon',       'star-fill'),
    'show_shimmer'   => getSetting('card_show_shimmer',    '1'),
    'label_text'     => getSetting('card_label_text',      'MEMBER CARD'),
    'subtitle_text'  => getSetting('card_subtitle_text',   'REWARDS MEMBER'),
    'card_qr_text'   => getSetting('card_qr_text',         ''),
];

jsonResponse([
    'success'      => true,
    'member'       => [
        'name'          => $member['name'],
        'card_code'     => $member['card_code'],
        'registered_at' => $member['registered_at'],
        'initials'      => strtoupper(implode('', array_map(
            fn($w) => $w[0],
            array_slice(explode(' ', $member['name']), 0, 2)
        ))),
    ],
    'balance'      => $balance,
    'redeem_value' => $redeemValue,
    'can_redeem'   => $canRedeem,
    'min_redeem'   => $minRedeem,
    'expiry_note'  => $expiryNote,
    'point_value'  => $pointPesoVal,
    'stats'        => $stats,
    'transactions' => $transactions,
    'design'       => $design,
]);
