<?php
/**
 * GET /api/admin/subscriptions_list.php
 * Admin-only. Every business account's subscription status, for manual
 * management until real billing is switched on.
 */

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

require_login();
require_role(['admin']);

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

$pdo = Database::connect();

$total = (int) $pdo->query("SELECT COUNT(*) FROM users WHERE account_type = 'business'")->fetchColumn();

$stmt = $pdo->prepare("
    SELECT u.id AS user_id, u.email, bp.business_name,
           bp.subscription_status, bp.subscription_plan, bp.trial_ends_at, bp.subscription_notes
    FROM users u
    JOIN business_profiles bp ON bp.user_id = u.id
    WHERE u.account_type = 'business'
    ORDER BY bp.subscription_status = 'trial' DESC, bp.trial_ends_at ASC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute();
$rows = $stmt->fetchAll();

foreach ($rows as &$r) {
    $r['days_left'] = null;
    if ($r['subscription_status'] === 'trial' && $r['trial_ends_at']) {
        $diff = (strtotime($r['trial_ends_at']) - strtotime(date('Y-m-d'))) / 86400;
        $r['days_left'] = (int) ceil($diff);
    }
}

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