<?php
declare(strict_types=1);
if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}
require_once ACC_PATH . 'includes/helpers/svc-accounting.php';

global $wpdb;
$report = $wpdb->get_row(
    "SELECT * FROM {$wpdb->prefix}svc_reports WHERE status='final' ORDER BY id DESC LIMIT 1",
    ARRAY_A
);
if ( ! $report ) {
    echo json_encode( [ 'error' => 'no final report' ] );
    exit( 1 );
}
$result = Svc_Accounting::on_report_finalized( $report );
$post = null;
if ( empty( $result['pending'] ) && ( $result['skipped'] ?? false ) ) {
    $post = [ 'skipped' => true, 'message' => 'already posted' ];
} elseif ( ! empty( $result['event_id'] ) || ! empty( $report['acc_revenue_event_id'] ) ) {
    $post = Svc_Accounting::post_report_by_accountant( (int) $report['id'] );
}
$queue = Svc_Accounting::pending_queue();
echo json_encode( [
    'report_id' => $report['id'],
    'total' => $report['total'],
    'prepare' => $result,
    'accountant_post' => $post,
    'pending_counts' => $queue['counts'] ?? [],
    'portal' => Svc_Accounting::portal_settings(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
