<?php
/**
 * GET /api/loyalty/history.php
 * Returns the caller's points transaction log, most recent first, plus current balance.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = require_login();

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$stmt = $pdo->prepare('SELECT points_balance FROM loyalty_points WHERE user_id = ?');
$stmt->execute([$userId]);
$balance = $stmt->fetch();

$countStmt = $pdo->prepare('SELECT COUNT(*) FROM loyalty_transactions WHERE user_id = ?');
$countStmt->execute([$userId]);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare("SELECT points, reason, created_at FROM loyalty_transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute([$userId]);
$transactions = $stmt->fetchAll();

send_json(true, 'OK', [
    'points_balance' => $balance ? (int) $balance['points_balance'] : 0,
    'transactions' => $transactions,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
