<?php
declare(strict_types=1);

require_once __DIR__ . '/admin_bootstrap.php';

$pdo = admin_get_pdo();
admin_require_auth($pdo);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method !== 'GET') {
    admin_json_error('Metoda niedozwolona', 405);
}

$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPageRaw = isset($_GET['perPage']) ? (int)$_GET['perPage'] : (isset($_GET['limit']) ? (int)$_GET['limit'] : 20);
$perPage = min(100, max(1, $perPageRaw));
$offset = ($page - 1) * $perPage;

$email = trim((string)($_GET['email'] ?? ''));
$createdFrom = trim((string)($_GET['createdFrom'] ?? ''));
$createdTo = trim((string)($_GET['createdTo'] ?? ''));

$where = [];
$params = [];

if ($email !== '') {
    $where[] = 'email LIKE :email';
    $params[':email'] = '%' . $email . '%';
}

if ($createdFrom !== '') {
    $where[] = 'created_at >= :createdFrom';
    $params[':createdFrom'] = $createdFrom;
}

if ($createdTo !== '') {
    $where[] = 'created_at <= :createdTo';
    $params[':createdTo'] = $createdTo;
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM PREOrder $whereSql");
    $countStmt->execute($params);
    $totalRecords = (int)$countStmt->fetchColumn();

    $totalPages = max(1, (int)ceil($totalRecords / $perPage));
    if ($page > $totalPages) {
        $page = $totalPages;
        $offset = ($page - 1) * $perPage;
    }

    $sql = "SELECT id, email, ip_address, created_at
            FROM PREOrder
            $whereSql
            ORDER BY created_at DESC, id DESC
            LIMIT :limit OFFSET :offset";

    $stmt = $pdo->prepare($sql);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    admin_json_response([
        'success' => true,
        'data' => $rows,
        'pagination' => [
            'currentPage' => $page,
            'perPage' => $perPage,
            'totalPages' => $totalPages,
            'totalRecords' => $totalRecords,
            'hasNextPage' => $page < $totalPages,
            'hasPreviousPage' => $page > 1,
        ],
        'filters' => [
            'email' => $email,
            'createdFrom' => $createdFrom,
            'createdTo' => $createdTo,
        ],
    ]);
} catch (Throwable $e) {
    admin_json_error('Błąd pobierania zapisów PREOrder', 500);
}
