<?php

declare(strict_types=1);

function contract_max_owners(): int
{
    return 5;
}

function contract_form_defaults(): array
{
    return [
        'contract_date' => date('Y-m-d'),
        'brand' => 'Gulab',
        'number_of_owners' => '1',
        'country' => 'Deutschland',
        'lieferando_own_delivery_pct' => '15',
        'lieferando_pickup_pct' => '15',
        'lieferando_online_payment_fee' => '0.64',
    ];
}

function contract_field_default(string $name): string
{
    return contract_form_defaults()[$name] ?? '';
}

function contract_commission_fields(string $prefix): array
{
    return [
        ['name' => $prefix . '_own_delivery_pct', 'type' => 'text', 'suffix' => '%', 'span' => 1, 'default' => contract_field_default($prefix . '_own_delivery_pct')],
        ['name' => $prefix . '_platform_delivery_pct', 'type' => 'text', 'suffix' => '%', 'span' => 1],
        ['name' => $prefix . '_pickup_pct', 'type' => 'text', 'suffix' => '%', 'span' => 1, 'default' => contract_field_default($prefix . '_pickup_pct')],
        ['name' => $prefix . '_online_payment_fee', 'type' => 'text', 'span' => 1, 'default' => contract_field_default($prefix . '_online_payment_fee')],
    ];
}

function contract_form_sections(): array
{
    return [
        'general' => [
            'title_key' => 'section_general',
            'icon' => 'storefront',
            'layout' => 'half',
            'fields' => [
                ['name' => 'contract_date', 'type' => 'date', 'required' => true, 'span' => 'full', 'default' => contract_field_default('contract_date')],
                ['type' => 'brand_owners_row', 'span' => 'full'],
                ['name' => 'restaurant_name', 'type' => 'text', 'required' => true, 'span' => 'full'],
                ['name' => 'email', 'type' => 'email', 'span' => 'full'],
            ],
        ],
        'tax' => [
            'title_key' => 'section_tax',
            'icon' => 'receipt_long',
            'layout' => 'half',
            'fields' => [
                ['name' => 'commercial_register', 'type' => 'text', 'span' => 'full'],
                ['name' => 'vat_id', 'type' => 'text', 'span' => 'full'],
                ['name' => 'tax_number', 'type' => 'text', 'span' => 'full'],
                ['name' => 'tax_identification', 'type' => 'text', 'span' => 'full', 'hint_key' => 'hint_tax_identification'],
            ],
        ],
        'company' => [
            'title_key' => 'section_company',
            'icon' => 'business',
            'layout' => 'full',
            'grid' => 'thirds',
            'fields' => [
                ['name' => 'legal_name', 'type' => 'text', 'span' => 1],
                ['type' => 'owner_names_dynamic', 'span' => 'full'],
                ['name' => 'contact_person', 'type' => 'text', 'span' => 1],
                ['name' => 'company_phone', 'type' => 'tel', 'span' => 1],
                ['name' => 'contact_mobile', 'type' => 'tel', 'span' => 1],
                ['name' => 'country', 'type' => 'text', 'span' => 1, 'default' => contract_field_default('country')],
                ['name' => 'street', 'type' => 'text', 'span' => 1],
                ['name' => 'postal_city', 'type' => 'text', 'span' => 1],
            ],
        ],
        'lieferando' => [
            'title_key' => 'section_lieferando',
            'icon' => 'delivery_dining',
            'note_key' => 'note_lieferando_fees',
            'commission' => true,
            'layout' => 'commission',
            'prefix' => 'lieferando',
            'fields' => contract_commission_fields('lieferando'),
        ],
        'wolt' => [
            'title_key' => 'section_wolt',
            'icon' => 'two_wheeler',
            'note_key' => 'note_wolt_fees',
            'commission' => true,
            'layout' => 'commission',
            'prefix' => 'wolt',
            'fields' => contract_commission_fields('wolt'),
        ],
        'uber' => [
            'title_key' => 'section_uber',
            'icon' => 'restaurant',
            'note_key' => 'note_uber_fees',
            'commission' => true,
            'layout' => 'commission',
            'prefix' => 'uber',
            'fields' => contract_commission_fields('uber'),
        ],
    ];
}

function contract_form_layout_groups(): array
{
    $sections = contract_form_sections();
    return [
        'top' => [$sections['general'], $sections['tax']],
        'company' => [$sections['company']],
        'commissions' => [$sections['lieferando'], $sections['wolt'], $sections['uber']],
    ];
}

/** Layout for create page — API fields are in views/contracts/create.php; skip duplicates here. */
function contract_form_create_layout_groups(): array
{
    $sections = contract_form_sections();

    $general = $sections['general'];
    $general['fields'] = array_values(array_filter(
        $general['fields'],
        static fn (array $field): bool => empty($field['name']) || !in_array($field['name'], ['restaurant_name', 'email'], true)
    ));

    $company = $sections['company'];
    $company['fields'] = array_values(array_filter(
        $company['fields'],
        static fn (array $field): bool => empty($field['name']) || !in_array($field['name'], ['company_phone', 'street', 'postal_city'], true)
    ));

    return [
        'top' => [$general, $sections['tax']],
        'company' => [$company],
        'commissions' => [$sections['lieferando'], $sections['wolt'], $sections['uber']],
    ];
}

function contract_all_field_names(): array
{
    $names = [];
    foreach (contract_form_sections() as $section) {
        foreach ($section['fields'] as $field) {
            if (empty($field['name'])) {
                if (($field['type'] ?? '') === 'brand_owners_row') {
                    $names[] = 'number_of_owners';
                }
                continue;
            }
            $names[] = $field['name'];
        }
    }
    return $names;
}

function contract_normalize_owner_count(mixed $value): int
{
    $count = (int)$value;

    return max(1, min(contract_max_owners(), $count));
}

function contract_owner_names_from_post(array $post): array
{
    $count = contract_normalize_owner_count($post['number_of_owners'] ?? 1);
    $names = [];

    if (isset($post['owner_names']) && is_array($post['owner_names'])) {
        foreach ($post['owner_names'] as $name) {
            $name = trim((string)$name);
            if ($name !== '') {
                $names[] = $name;
            }
        }
    }

    if ($names === [] && !empty($post['owner_name'])) {
        $legacy = trim((string)$post['owner_name']);
        if ($legacy !== '') {
            $names[] = $legacy;
        }
    }

    return array_slice($names, 0, $count);
}

function contract_owner_name_display(array $names): string
{
    $filtered = [];

    foreach ($names as $name) {
        $name = trim((string)$name);
        if ($name !== '') {
            $filtered[] = $name;
        }
    }

    return implode(', ', $filtered);
}

function contract_owner_name_for_pdf(array $contract): string
{
    if (!empty($contract['owner_name'])) {
        return trim((string)$contract['owner_name']);
    }

    if (!empty($contract['owner_names']) && is_array($contract['owner_names'])) {
        return contract_owner_name_display($contract['owner_names']);
    }

    return '';
}

function collect_contract_from_post(array $post, string $token): array
{
    if (isset($post['street_address']) && trim((string)$post['street_address']) !== '') {
        $post['street'] = $post['street_address'];
    }

    if (isset($post['zip_city']) && trim((string)$post['zip_city']) !== '') {
        $post['postal_city'] = $post['zip_city'];
    }

    $data = [
        'token' => $token,
        'status' => 'pending',
        'created_at' => date('Y-m-d H:i:s'),
        'signed_at' => null,
        'pdf_path' => '',
    ];

    foreach (contract_all_field_names() as $name) {
        $data[$name] = trim($post[$name] ?? '');
    }

    foreach (contract_form_defaults() as $key => $default) {
        if ($key === 'brand') {
            continue;
        }
        if ($data[$key] === '' && $default !== '') {
            $data[$key] = $default;
        }
    }

    $data['brands'] = contract_brands_from_post($post);
    $data['brand'] = contract_brand_display_names($data['brands']);
    $data['number_of_owners'] = (string)contract_normalize_owner_count($post['number_of_owners'] ?? $data['number_of_owners'] ?? 1);
    $data['owner_names'] = contract_owner_names_from_post($post);
    $data['owner_name'] = contract_owner_name_display($data['owner_names']);

    if ($data['contract_date'] === '') {
        $data['contract_date'] = date('Y-m-d');
    }

    $data['partner_name'] = $data['restaurant_name'] ?: ($data['owner_name'] ?: $data['legal_name']);
    $data['partner_email'] = $data['email'];
    $data['partner_phone'] = $data['company_phone'] ?: $data['contact_mobile'];
    $data['partner_address'] = trim($data['street'] . ', ' . $data['postal_city'] . ', ' . $data['country'], ', ');
    $data['business_name'] = $data['legal_name'] ?: $data['restaurant_name'];
    $data['partnership_type'] = $data['brand'];
    $data['type'] = 'partner';
    $data['contract_url'] = trim($post['contract_url'] ?? '');

    return $data;
}

function contract_brand_label(string $brand): string
{
    return match ($brand) {
        'Flamers' => 'Flamers Pizza',
        default => $brand,
    };
}

function contract_brand_display_names(array $brands): string
{
    $labels = [];

    foreach ($brands as $brand) {
        $brand = trim((string)$brand);
        if ($brand === '') {
            continue;
        }
        $labels[] = contract_brand_label($brand);
    }

    return implode(', ', $labels);
}

function contract_brands_from_post(array $post): array
{
    $allowed = ['Gulab', 'Flamers'];
    $selected = [];

    if (isset($post['brands'])) {
        if (!is_array($post['brands'])) {
            return [];
        }

        foreach ($post['brands'] as $brand) {
            $brand = trim((string)$brand);
            if (in_array($brand, $allowed, true) && !in_array($brand, $selected, true)) {
                $selected[] = $brand;
            }
        }

        return $selected;
    }

    if (!empty($post['brand'])) {
        return contract_parse_brands((string)$post['brand']);
    }

    return ['Gulab'];
}

function contract_parse_brands(string $value): array
{
    $allowed = ['Gulab', 'Flamers'];
    $selected = [];

    if (stripos($value, 'both') !== false || stripos($value, 'beide') !== false) {
        return ['Gulab', 'Flamers'];
    }

    foreach ($allowed as $brand) {
        if (stripos($value, $brand) !== false) {
            $selected[] = $brand;
        }
    }

    return $selected;
}

function contract_selected_brands(array $contract): array
{
    if (!empty($contract['brands']) && is_array($contract['brands'])) {
        $selected = [];
        foreach ($contract['brands'] as $brand) {
            $brand = trim((string)$brand);
            if (in_array($brand, ['Gulab', 'Flamers'], true) && !in_array($brand, $selected, true)) {
                $selected[] = $brand;
            }
        }

        return $selected !== [] ? $selected : ['Gulab'];
    }

    if (!empty($contract['brand'])) {
        return contract_parse_brands((string)$contract['brand']);
    }

    return ['Gulab'];
}

function validate_contract_form(array $data): ?string
{
    if (empty($data['brands'])) {
        return 'flash_brand_required';
    }
    if ($data['restaurant_name'] === '') {
        return 'flash_restaurant_required';
    }
    if ($data['email'] !== '' && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        return 'flash_email_required';
    }

    $ownerCount = contract_normalize_owner_count($data['number_of_owners'] ?? 1);
    $ownerNames = $data['owner_names'] ?? [];
    if (count($ownerNames) < $ownerCount) {
        return 'flash_owner_names_required';
    }

    return null;
}

function field_grid_class(array $field): string
{
    $span = $field['span'] ?? 1;

    if ($span === 'full' || $span === 0) {
        return 'cf-span-full';
    }

    return match ((int)$span) {
        3 => 'cf-span-3',
        2 => 'cf-span-2',
        default => 'cf-span-1',
    };
}

function field_value(array $field): string
{
    $default = $field['default'] ?? '';

    if (is_array($default)) {
        return '';
    }

    return (string)$default;
}

function render_contract_field(array $field): void
{
    $type = $field['type'] ?? 'text';
    $gridClass = field_grid_class($field);

    if ($type === 'brand_checkboxes') {
        render_brand_checkbox_field($field, $gridClass);
        return;
    }

    if ($type === 'brand_owners_row') {
        render_brand_owners_row($gridClass);
        return;
    }

    if ($type === 'radio') {
        render_brand_radio_field($field, $gridClass);
        return;
    }

    if ($type === 'owner_names_dynamic') {
        render_owner_names_dynamic_field($gridClass);
        return;
    }

    $name = $field['name'];
    $required = !empty($field['required']);
    $labelKey = 'field_' . $name;
    $value = field_value($field);
    ?>
<div class="cf-field <?= $gridClass ?>"<?= $name === 'legal_name' ? ' id="cf-field-legal_name"' : '' ?>>
    <label class="form-label" for="<?= e($name) ?>">
        <?= e(__($labelKey)) ?><?= $required ? ' *' : '' ?>
    </label>
    <?php if ($type === 'textarea'): ?>
    <textarea id="<?= e($name) ?>" name="<?= e($name) ?>" class="form-input" rows="2" <?= $required ? 'required' : '' ?>><?= e($value) ?></textarea>
    <?php else: ?>
    <input
        type="<?= e($type) ?>"
        id="<?= e($name) ?>"
        name="<?= e($name) ?>"
        class="form-input"
        value="<?= e($value) ?>"
        <?= !empty($field['min']) ? 'min="' . e((string)$field['min']) . '"' : '' ?>
        <?= !empty($field['max']) ? 'max="' . e((string)$field['max']) . '"' : '' ?>
        <?= $required ? 'required' : '' ?>
    >
    <?php endif; ?>
    <?php if (!empty($field['hint_key'])): ?>
    <p class="cf-hint"><?= e(__($field['hint_key'])) ?></p>
    <?php endif; ?>
</div>
    <?php
}

function render_brand_owners_row(string $gridClass): void
{
    $options = ['Gulab', 'Flamers'];
    $selected = ['Gulab'];
    $ownerCount = contract_field_default('number_of_owners');
    ?>
<div class="cf-field <?= $gridClass ?> cf-brand-owners-row">
    <div class="cf-brand-owners-grid">
        <div class="cf-brand-owners-brand">
            <span class="form-label"><?= e(__('field_brand')) ?></span>
            <div class="brand-radio-group" role="group" aria-label="<?= e(__('field_brand')) ?>">
                <?php foreach ($options as $option): ?>
                <label class="brand-radio-option">
                    <input type="checkbox" name="brands[]" value="<?= e($option) ?>" <?= in_array($option, $selected, true) ? 'checked' : '' ?>>
                    <span><?= e($option) ?></span>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="cf-brand-owners-count">
            <label class="form-label" for="number_of_owners"><?= e(__('field_number_of_owners')) ?> *</label>
            <input
                type="number"
                id="number_of_owners"
                name="number_of_owners"
                class="form-input"
                value="<?= e($ownerCount) ?>"
                min="1"
                max="<?= contract_max_owners() ?>"
                data-owner-label="<?= e(__('field_owner_name')) ?>"
                required
            >
        </div>
    </div>
    <p class="cf-hint"><?= e(__('hint_brand_owner_row')) ?></p>
</div>
    <?php
}

function render_owner_names_dynamic_field(string $gridClass): void
{
    // Owner fields are inserted after legal name by contract-form.js.
}

function render_owner_name_inputs(int $count, array $values = []): void
{
    $count = contract_normalize_owner_count($count);

    for ($i = 1; $i <= $count; $i++) {
        $value = $values[$i - 1] ?? '';
        $label = __('field_owner_name') . ' ' . $i;
        ?>
<div class="cf-field cf-span-1 owner-name-field">
    <label class="form-label" for="owner_name_<?= $i ?>"><?= e($label) ?></label>
    <input
        type="text"
        id="owner_name_<?= $i ?>"
        name="owner_names[]"
        class="form-input owner-name-input"
        value="<?= e($value) ?>"
        required
    >
</div>
        <?php
    }
}

function render_brand_checkbox_field(array $field, string $gridClass): void
{
    $options = $field['options'] ?? ['Gulab', 'Flamers'];
    $selected = $field['default'] ?? ['Gulab'];
    if (!is_array($selected)) {
        $selected = contract_parse_brands((string)$selected);
    }
    ?>
<div class="cf-field <?= $gridClass ?>">
    <span class="form-label"><?= e(__('field_brand')) ?></span>
    <div class="brand-radio-group" role="group" aria-label="<?= e(__('field_brand')) ?>">
        <?php foreach ($options as $option): ?>
        <label class="brand-radio-option">
            <input type="checkbox" name="brands[]" value="<?= e($option) ?>" <?= in_array($option, $selected, true) ? 'checked' : '' ?>>
            <span><?= e($option) ?></span>
        </label>
        <?php endforeach; ?>
    </div>
    <p class="cf-hint"><?= e(__('hint_brand_select')) ?></p>
</div>
    <?php
}

function render_brand_radio_field(array $field, string $gridClass): void
{
    $name = $field['name'];
    $options = $field['options'] ?? ['Gulab', 'Flamers'];
    $selected = $field['default'] ?? 'Gulab';
    ?>
<div class="cf-field <?= $gridClass ?>">
    <span class="form-label"><?= e(__('field_brand')) ?></span>
    <div class="brand-radio-group" role="radiogroup" aria-label="<?= e(__('field_brand')) ?>">
        <?php foreach ($options as $option): ?>
        <label class="brand-radio-option">
            <input type="radio" name="<?= e($name) ?>" value="<?= e($option) ?>" <?= $option === $selected ? 'checked' : '' ?> required>
            <span><?= e($option) ?></span>
        </label>
        <?php endforeach; ?>
    </div>
</div>
    <?php
}

function render_commission_field(array $field, string $prefix): void
{
    $name = $field['name'];
    $labelKey = 'field_' . $name;
    $gridClass = field_grid_class($field);
    $value = field_value($field);
    ?>
<div class="cf-field <?= $gridClass ?>">
    <label class="form-label" for="<?= e($name) ?>"><?= e(__($labelKey)) ?></label>
    <div class="relative">
        <input
            type="text"
            id="<?= e($name) ?>"
            name="<?= e($name) ?>"
            value="<?= e($value) ?>"
            class="form-input <?= !empty($field['suffix']) ? 'pr-10' : '' ?>"
            inputmode="decimal"
        >
        <?php if (!empty($field['suffix'])): ?>
        <span class="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-karvi-400 font-medium"><?= e($field['suffix']) ?></span>
        <?php endif; ?>
    </div>
</div>
    <?php
}

function render_form_section_card(array $section): void
{
    $isCommission = !empty($section['commission']);
    $gridType = $section['grid'] ?? ($isCommission ? 'commission' : 'stacked');
    $gridClass = match ($gridType) {
        'thirds' => 'cf-grid-thirds',
        'commission' => 'cf-grid-commission',
        default => 'cf-grid-stacked',
    };
    ?>
<section class="cf-card <?= $isCommission ? 'cf-card-commission' : '' ?> <?= ($section['layout'] ?? '') === 'full' ? 'cf-card-full' : '' ?>">
    <div class="cf-card-head">
        <span class="material-symbols-rounded cf-card-icon"><?= e($section['icon']) ?></span>
        <h3 class="cf-card-title"><?= e(__($section['title_key'])) ?></h3>
    </div>

    <?php if (!empty($section['note_key'])): ?>
    <p class="cf-card-note"><?= e(__($section['note_key'])) ?></p>
    <?php endif; ?>

    <div class="cf-grid <?= e($gridClass) ?>"<?= ($section['title_key'] ?? '') === 'section_company' ? ' id="company-fields-grid"' : '' ?>>
        <?php foreach ($section['fields'] as $field): ?>
            <?php if ($isCommission): ?>
                <?php render_commission_field($field, $section['prefix']); ?>
            <?php else: ?>
                <?php render_contract_field($field); ?>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
</section>
    <?php
}
