<?php
/**
 * Batch PDF Generator CLI Script
 * Uses curl to CI4 web endpoint (avoids slow CLI database queries)
 * 
 * Usage: php script.php accessnumbers.txt
 * 
 * Input file format: One accessnumber per line
 * Example:
 *   202403110001
 *   202403110002
 *   202403110003
 */

// Check command line arguments
if ($argc < 2) {
    echo "Usage: php script.php <accessnumbers_file>\n";
    echo "Example: php script.php batch.txt\n\n";
    echo "File format: One accessnumber per line\n";
    exit(1);
}

$inputFile = $argv[1];

if (!file_exists($inputFile)) {
    echo "Error: File not found: $inputFile\n";
    exit(1);
}

// Base URL for CI4 endpoint
// Using batch/pdf endpoint (no auth required)
// Dev: localhost/gdc_cmod/ | Prod: glenlis/cmod/
$baseUrl = 'http://localhost/gdc_cmod/batch/pdf';

// Read accessnumbers from file
$lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
    echo "Error: Could not read file: $inputFile\n";
    exit(1);
}

$accessnumbers = array_filter(array_map('trim', $lines));
$total = count($accessnumbers);

if ($total === 0) {
    echo "Error: No accessnumbers found in file\n";
    exit(1);
}

echo "Processing $inputFile\n";
echo "Found $total access number(s) via $baseUrl\n";
echo str_repeat("-", 60) . "\n";

// Statistics
$stats = [
    'success' => 0,
    'failed' => 0,
    'details' => []
];

// Process each accessnumber
foreach ($accessnumbers as $index => $accessnumber) {
    $current = $index + 1;
    $startTime = microtime(true);
    echo "[$current/$total] $accessnumber... ";
    
    try {
        $url = "$baseUrl/$accessnumber/pdf";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, true); // Include headers in output
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
        $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            throw new \Exception("cURL error: $curlError");
        }
        
        // Debug: Show redirect info
        if ($httpCode !== 200) {
            $debug = "HTTP $httpCode";
            if ($redirectUrl) {
                $debug .= " -> $redirectUrl";
            }
            if ($finalUrl !== $url) {
                $debug .= " (final: $finalUrl)";
            }
            throw new \Exception($debug);
        }
        
        // Remove headers from response body
        $headerSize = strpos($response, "\r\n\r\n");
        if ($headerSize !== false) {
            $response = substr($response, $headerSize + 4);
        }
        
        $data = json_decode($response, true);
        
        if (!isset($data['success']) || !$data['success']) {
            $error = $data['error'] ?? 'Unknown error';
            throw new \Exception($error);
        }
        
        $jobId = $data['jobId'] ?? 'unknown';
        $lang = $data['lang'] ?? 'Unknown';
        $isRegen = $data['isRegen'] ?? false;
        $regenText = $isRegen ? ' (regen)' : '';
        
        $elapsed = round((microtime(true) - $startTime) * 1000);
        echo "QUEUED (job: $jobId, lang: $lang$regenText, ${elapsed}ms)\n";
        
        $stats['success']++;
        $stats['details'][] = [
            'accessnumber' => $accessnumber,
            'status' => 'success',
            'jobId' => $jobId,
            'language' => $lang,
            'time_ms' => $elapsed
        ];
        
    } catch (\Exception $e) {
        $elapsed = round((microtime(true) - $startTime) * 1000);
        echo "FAILED (" . $e->getMessage() . ", ${elapsed}ms)\n";
        
        $stats['failed']++;
        $stats['details'][] = [
            'accessnumber' => $accessnumber,
            'status' => 'failed',
            'error' => $e->getMessage(),
            'time_ms' => $elapsed
        ];
    }
}

echo str_repeat("-", 60) . "\n";
echo "Complete: " . $stats['success'] . " queued, " . $stats['failed'] . " failed\n";

// Save detailed log
$logFile = 'batch_pdf_' . date('Ymd_His') . '.log';
$logContent = "Batch PDF Generation Log\n";
$logContent .= "Generated: " . date('Y-m-d H:i:s') . "\n";
$logContent .= "Input file: $inputFile\n";
$logContent .= "Endpoint: $baseUrl\n";
$logContent .= "Total: $total, Success: {$stats['success']}, Failed: {$stats['failed']}\n";
$logContent .= str_repeat("-", 60) . "\n";

foreach ($stats['details'] as $detail) {
    $logContent .= $detail['accessnumber'] . " | " . $detail['status'];
    if (isset($detail['jobId'])) {
        $logContent .= " | job: " . $detail['jobId'];
        $logContent .= " | lang: " . $detail['language'];
    }
    if (isset($detail['error'])) {
        $logContent .= " | error: " . $detail['error'];
    }
    $logContent .= " | " . $detail['time_ms'] . "ms\n";
}

file_put_contents($logFile, $logContent);
echo "Log saved to: $logFile\n";

exit($stats['failed'] > 0 ? 1 : 0);
