<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/i18n.php';
require_once __DIR__ . '/../includes/contract_form.php';
require_once __DIR__ . '/../includes/api_service.php';
require_once __DIR__ . '/../includes/pdf_generator.php';

init_i18n();

$post = [
    'contract_date' => date('Y-m-d'),
    'number_of_owners' => '1',
    'owner_names' => ['John Doe'],
    'brands' => ['Gulab'],
    'restaurant_name' => 'Test Restaurant',
    'email' => 'test@example.com',
    'legal_name' => 'Test GmbH',
    'owner_name' => 'John Doe',
    'contact_person' => 'John Doe',
    'company_phone' => '+491111111',
    'contact_mobile' => '+492222222',
    'street' => 'Test Street 1',
    'postal_city' => '60315 Frankfurt',
    'country' => 'Deutschland',
    'commercial_register' => 'HRB 999',
    'vat_id' => 'DE999',
    'tax_number' => 'T999',
    'tax_identification' => 'ST999',
    'lieferando_own_delivery_pct' => '15',
    'lieferando_pickup_pct' => '15',
    'lieferando_online_payment_fee' => '0.64',
];

$token = bin2hex(random_bytes(8));
$contractData = collect_contract_from_post($post, $token);
$error = validate_contract_form($contractData);

if ($error) {
    echo 'Validation failed: ' . $error . PHP_EOL;
    exit(1);
}

try {
    $contract = api_save_contract($contractData);
    $contract = array_merge($contractData, $contract);
    $contract['token'] = $contract['token'] ?? $token;
    $contract['id'] = $contract['id'] ?? 0;

    $pdfFilename = generate_contract_pdf($contract);
    api_update_contract($contract['token'], [
        'pdf_path' => $pdfFilename,
        'pdf_url' => rtrim(app_config()['base_url'], '/') . '/uploads/contracts/' . $pdfFilename,
    ]);

    echo 'Create flow OK' . PHP_EOL;
    echo 'Token: ' . $contract['token'] . PHP_EOL;
    echo 'PDF: ' . $pdfFilename . PHP_EOL;
    echo 'Link: ' . contract_url($contract['token']) . PHP_EOL;
} catch (Throwable $e) {
    echo 'Create flow FAILED: ' . $e->getMessage() . PHP_EOL;
    exit(1);
}
