<?php
/**
 * GET /api/orders/list.php
 * Returns the caller's own orders (as buyer), most recent first.
 */

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

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

$stmt = $pdo->prepare("SELECT id, total_amount, status, created_at FROM orders WHERE buyer_id = ? ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute([$userId]);
$orders = $stmt->fetchAll();

send_json(true, 'OK', [
    'orders' => $orders,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
