<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

golder_require_method('GET');
$master = golder_master_pdo();
$user = golder_portal_api_require_login($master);
$userId = (int)($user['id'] ?? 0);

$customer = golder_customer_by_portal_user_id($master, $userId);
$customerPayload = null;
if ($customer) {
    $effective = golder_customer_effective_plan($customer);
    $customerPayload = [
        'id' => (int)($customer['id'] ?? 0),
        'username' => (string)($customer['username'] ?? ''),
        'plan_type' => (string)($effective['plan_type'] ?? ''),
        'max_pc_devices' => (int)($effective['max_pc_devices'] ?? 0),
        'max_web_sessions' => (int)($effective['max_web_sessions'] ?? 0),
        'desktop_expiry_date' => (string)($effective['desktop_expiry_date'] ?? ''),
        'sync_expiry_date' => (string)($effective['sync_expiry_date'] ?? ''),
        'sync_status' => (string)($effective['sync_status'] ?? 'disabled'),
        'web_mobile_enabled' => !empty($effective['web_mobile_enabled']),
        'expiry_date' => (string)($effective['expiry_date'] ?? ''),
        'license_status' => (string)($customer['license_status'] ?? ''),
    ];
}

$activeDemo = null;
$stDemo = $master->prepare(
    'SELECT id, status, demo_code, demo_username, demo_password_enc, demo_expires_at, created_at
     FROM demo_requests
     WHERE portal_user_id = :uid
     ORDER BY created_at DESC
     LIMIT 1'
);
$stDemo->execute([':uid' => $userId]);
$demoRow = $stDemo->fetch();
if (is_array($demoRow)) {
    $activeDemo = $demoRow;
    $activeDemo['demo_password'] = golder_decrypt_demo_secret((string)($demoRow['demo_password_enc'] ?? ''));
    unset($activeDemo['demo_password_enc']);
}

golder_json_response([
    'status' => 'ok',
    'user' => $user,
    'customer' => $customerPayload,
    'demo' => $activeDemo,
]);








