<?php
namespace App\Libraries;

use App\Models\DepositToAccountRefModel;

class QuickbooksAccountsLibrary
{
    /**
     * Run a raw query against the QuickBooks Online API.
     */
    public function runQuery(string $realm, string $tok, string $q): array
    {
        $url = "https://quickbooks.api.intuit.com/v3/company/{$realm}/query?query=" . urlencode($q);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer {$tok}",
                "Accept: application/json",
                "Content-Type: application/text",
            ],
            CURLOPT_RETURNTRANSFER => true,
        ]);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code !== 200) {
            throw new \RuntimeException("QBO API error {$code}: {$resp}");
        }
        return json_decode($resp, true);
    }

    /**
     * Pull account records from QBO and upsert into the model.
     */
    public function pullAccounts(string $realm, string $tok, DepositToAccountRefModel $model): void
    {
        $start = 1;
        $max   = 1000;
        do {
            $q = "SELECT Id, Name FROM Account ORDERBY Id STARTPOSITION {$start} MAXRESULTS {$max}";
            $rows = $this->runQuery($realm, $tok, $q)['QueryResponse']['Account'] ?? [];
            foreach ($rows as $acct) {
                $model->upsertAccount([
                    'account_id'   => $acct['Id']   ?? '',
                    'account_name' => $acct['Name'] ?? '',
                ]);
            }
            $start += $max;
        } while (count($rows) === $max);
    }
}
