<?php
require 'autoload/class.Env.php';
Env::load('.env');
$domain = Env::get('FAKTUROWNIA_API_DOMAIN');
$token = Env::get('FAKTUROWNIA_API_TOKEN');
$start = Env::get('FAKTUROWNIA_START_DATE');
$base = strpos($domain, 'http') === 0 ? $domain : 'https://' . $domain;

function fetchAll($urlBase) {
  $all = [];
  for ($page = 1; $page <= 50; $page++) {
    $url = $urlBase . '&page=' . $page . '&per_page=100';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $body = curl_exec($ch);
    curl_close($ch);
    $arr = json_decode((string)$body, true);
    if (!is_array($arr) || count($arr) === 0) break;
    foreach ($arr as $row) $all[] = $row;
    if (count($arr) < 100) break;
  }
  return $all;
}

function normalizeDate(array $doc): string {
  $date = (string)($doc['issue_date'] ?? $doc['sell_date'] ?? $doc['created_at'] ?? '');
  return substr($date, 0, 10);
}

$sales = fetchAll($base . '/invoices.json?api_token=' . urlencode($token));
$costs = fetchAll($base . '/invoices.json?api_token=' . urlencode($token) . '&income=no');

$sf = [];
foreach ($sales as $doc) {
  $date = normalizeDate($doc);
  if ($date && strtotime($date) >= strtotime($start) && (($doc['income'] ?? true) !== false)) $sf[] = $doc;
}

$cf = [];
foreach ($costs as $doc) {
  $date = normalizeDate($doc);
  if ($date && strtotime($date) >= strtotime($start)) $cf[] = $doc;
}

echo 'sales_from_start(issue_date_first)=' . count($sf) . PHP_EOL;
echo 'costs_from_start(issue_date_first)=' . count($cf) . PHP_EOL;
