<?php

require __DIR__ . '/../vendor/autoload.php';

$app = require __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

$service = app(App\Services\LoadDocumentService::class);
$ref = new ReflectionClass($service);
$extractText = $ref->getMethod('extractText');
$extractText->setAccessible(true);
$extractFields = $ref->getMethod('extractFields');
$extractFields->setAccessible(true);

$folders = [
    'working' => 'C:/Users/Hp/Downloads/working',
    'not_working' => 'C:/Users/Hp/Downloads/not working',
];

$rows = [];

foreach ($folders as $group => $folder) {
    if (!is_dir($folder)) {
        continue;
    }

    $files = glob($folder . '/*.pdf') ?: [];
    sort($files);

    foreach ($files as $filePath) {
        $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $text = (string) $extractText->invoke($service, $filePath, $ext);
        $fields = (array) $extractFields->invoke($service, $text);

        $rows[] = [
            'group' => $group,
            'file' => basename($filePath),
            'size' => filesize($filePath) ?: 0,
            'text_len' => strlen($text),
            'miles' => $fields['miles'] ?? null,
            'gross_rate' => $fields['gross_rate'] ?? null,
            'pickup_date' => $fields['pickup_date'] ?? null,
            'delivery_date' => $fields['delivery_date'] ?? null,
            'registration_number' => $fields['registration_number'] ?? null,
            'company_name' => $fields['company_name'] ?? null,
        ];
    }
}

$outPath = __DIR__ . '/audit_load_parser_results.json';
file_put_contents($outPath, json_encode($rows, JSON_PRETTY_PRINT));

echo "Wrote: {$outPath}" . PHP_EOL;
echo "Rows: " . count($rows) . PHP_EOL;
