<?php
/**
 * Temporary CourierIT1 PDF download checker.
 *
 * Usage:
 * php backend/tmp_courierit1_pdf_check.php --list-companies
 * php backend/tmp_courierit1_pdf_check.php --company=pickpack --order-id=2687272
 * php backend/tmp_courierit1_pdf_check.php --company=pickpack --order-id=2687272 --out=label.pdf
 * php backend/tmp_courierit1_pdf_check.php --base-url=https://courierit1.net.nz/api --token=eyJ... --order-id=2687272
 */

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "Run this from the command line.\n");
    exit(1);
}

function tmp_load_env(string $path): array {
    if (!file_exists($path)) return [];
    $parsed = parse_ini_file($path, false, INI_SCANNER_RAW);
    return is_array($parsed) ? $parsed : [];
}

function tmp_apply_db_prefix(string $name, string $prefix): string {
    $name = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim($name)));
    $prefix = preg_replace('/[^a-z0-9_]/', '_', strtolower(trim($prefix)));
    $prefix = ltrim($prefix, '_');
    if ($prefix === '' || $name === '' || strpos($name, $prefix) === 0) return $name;
    return substr($prefix . $name, 0, 64);
}

function tmp_fail(string $message): void {
    fwrite(STDERR, $message . "\n");
    exit(1);
}

function tmp_http_json(string $method, string $url, array $headers = [], $payload = null): array {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if ($payload !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([
        'Accept: application/json, text/javascript, */*; q=0.01',
        'Content-Type: application/json; charset=UTF-8',
        'X-Requested-With: XMLHttpRequest',
    ], $headers));
    $raw = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);
    return ['http' => $http, 'error' => $err, 'raw' => (string)$raw, 'json' => json_decode((string)$raw, true)];
}

function tmp_download(string $url, string $token, string $out): array {
    $fh = fopen($out, 'wb');
    if (!$fh) tmp_fail("Could not open output file: {$out}");

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fh);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/pdf,application/octet-stream,*/*',
        'Authorization: Bearer ' . $token,
        'X-Requested-With: XMLHttpRequest',
    ]);
    $ok = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $err = curl_error($ch);
    curl_close($ch);
    fclose($fh);

    return [
        'ok' => (bool)$ok,
        'http' => $http,
        'content_type' => $contentType,
        'error' => $err,
        'bytes' => file_exists($out) ? filesize($out) : 0,
    ];
}

$opts = getopt('', [
    'company:',
    'order-id:',
    'out::',
    'provider::',
    'base-url::',
    'token::',
    'username::',
    'api-key::',
    'password::',
    'list-companies',
]);
$company = preg_replace('/[^a-z0-9\-_]/', '', strtolower(trim((string)($opts['company'] ?? ''))));
$orderId = trim((string)($opts['order-id'] ?? ''));
$out = trim((string)($opts['out'] ?? ''));
$provider = preg_replace('/[^a-z0-9\-_]/', '', strtolower(trim((string)($opts['provider'] ?? 'courierit1'))));
if ($provider === '') $provider = 'courierit1';

if ($orderId === '' && !array_key_exists('list-companies', $opts)) {
    tmp_fail("Usage: php backend/tmp_courierit1_pdf_check.php --company=COMPANY_SLUG --order-id=COURIERIT1_ORDER_ID [--out=label.pdf]\nOr: php backend/tmp_courierit1_pdf_check.php --base-url=https://courierit1.net.nz/api --token=TOKEN --order-id=ORDER_ID\nOr: php backend/tmp_courierit1_pdf_check.php --list-companies");
}
if ($out === '') {
    $out = __DIR__ . DIRECTORY_SEPARATOR . 'tmp_courierit1_label_' . preg_replace('/[^a-zA-Z0-9_\-]/', '_', $orderId) . '.pdf';
}

$env = tmp_load_env(__DIR__ . '/.env');
$dbHost = $env['DB_HOST'] ?? 'localhost';
$dbUser = $env['DB_USER'] ?? '';
$dbPass = trim((string)($env['DB_PASS'] ?? ''), "\"'");
$dbPrefix = $env['DB_NAME_PREFIX'] ?? '';
$masterDbName = tmp_apply_db_prefix($env['MASTER_DB_NAME'] ?? 'pickpack_ship_master', $dbPrefix);

$master = new mysqli($dbHost, $dbUser, $dbPass, $masterDbName);
if ($master->connect_error) tmp_fail('Master DB connection failed: ' . $master->connect_error);

$baseOverride = trim((string)($opts['base-url'] ?? ''));
$tokenOverride = trim((string)($opts['token'] ?? ''));
$usernameOverride = trim((string)($opts['username'] ?? ''));
$passwordOverride = (string)($opts['api-key'] ?? $opts['password'] ?? '');

if (array_key_exists('list-companies', $opts)) {
    $res = $master->query("SELECT slug, business_name, client_db_name, allowed_couriers, is_active FROM pp_clients ORDER BY slug");
    if (!$res) tmp_fail('Could not list companies: ' . $master->error);
    while ($row = $res->fetch_assoc()) {
        echo ($row['is_active'] ? 'active' : 'inactive') . "\t"
            . $row['slug'] . "\t"
            . $row['client_db_name'] . "\t"
            . ($row['allowed_couriers'] ?: 'all couriers') . "\t"
            . $row['business_name'] . "\n";
    }
    exit(0);
}

$settings = [];
if ($company !== '') {
    $stmt = $master->prepare("SELECT client_db_name FROM pp_clients WHERE slug = ? AND is_active = 1 LIMIT 1");
    $stmt->bind_param('s', $company);
    $stmt->execute();
    $clientRow = $stmt->get_result()->fetch_assoc();
    if (!$clientRow || empty($clientRow['client_db_name'])) tmp_fail("Company not found or has no client DB: {$company}. Try --list-companies.");

    $clientDbName = (string)$clientRow['client_db_name'];
    $db = new mysqli($dbHost, $dbUser, $dbPass, $clientDbName);
    if ($db->connect_error) tmp_fail('Client DB connection failed: ' . $db->connect_error);

    $stmt = $db->prepare("SELECT `key`, `value` FROM pp_settings WHERE company_id = 1 AND category = 'shipping' AND provider_slug = ?");
    $stmt->bind_param('s', $provider);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res) while ($row = $res->fetch_assoc()) $settings[$row['key']] = $row['value'];
}

$base = rtrim((string)($baseOverride !== '' ? $baseOverride : ($settings['base_url'] ?? 'https://courierit1.net.nz/api')), '/');
$token = trim((string)($tokenOverride !== '' ? $tokenOverride : ($settings['bearer_token'] ?? '')));
$username = trim((string)($usernameOverride !== '' ? $usernameOverride : ($settings['username'] ?? '')));
$password = (string)($passwordOverride !== '' ? $passwordOverride : ($settings['api_key'] ?? ''));

if ($token === '') {
    if ($username === '' || $password === '') {
        $keys = $settings ? implode(', ', array_keys($settings)) : 'none';
        tmp_fail("CourierIT1 bearer_token is empty and username/api_key are not configured for provider '{$provider}'. Settings keys found: {$keys}.\nYou can test directly with --base-url=... --token=...");
    }
    $login = tmp_http_json('POST', $base . '/users/login', [], [
        'username' => $username,
        'password' => $password,
        'remember' => true,
        'shopify' => null,
    ]);
    if ($login['http'] < 200 || $login['http'] >= 300) {
        tmp_fail('CourierIT1 login failed HTTP ' . $login['http'] . ': ' . ($login['error'] ?: $login['raw']));
    }
    $token = (string)($login['json']['result']['token'] ?? $login['json']['token'] ?? '');
    if ($token === '') tmp_fail('CourierIT1 login did not return a token: ' . $login['raw']);
}

$url = $base . '/consignments/pdf-labels-download/' . rawurlencode($orderId) . '/parcels/true';
$result = tmp_download($url, $token, $out);

echo "URL: {$url}\n";
echo "Output: {$out}\n";
echo "HTTP: {$result['http']}\n";
echo "Content-Type: {$result['content_type']}\n";
echo "Bytes: {$result['bytes']}\n";
if ($result['error'] !== '') echo "Curl error: {$result['error']}\n";

$head = file_exists($out) ? file_get_contents($out, false, null, 0, 8) : '';
if ($result['http'] >= 200 && $result['http'] < 300 && $result['bytes'] > 0 && str_starts_with((string)$head, '%PDF')) {
    echo "OK: downloaded a PDF.\n";
    exit(0);
}

echo "WARN: response did not look like a PDF. Open the output file to inspect the body.\n";
exit(2);
