<?php

declare(strict_types=1);

/**
 * Edit contract form — Edit contract API (PUT /karvipartner/contracts/{contract_id}).
 *
 * @var int $contractId
 * @var array<string,mixed> $contract
 * @var array<string,mixed> $rawData
 * @var string $action
 * @var string $detailsUrl
 * @var string $backUrl
 */

require_once dirname(__DIR__, 2) . '/includes/layout.php';

$post = $_POST ?? [];
$ownerNames = contract_edit_owner_names_list($post['owner_names'] ?? ($post['owner_name'] ?? ($contract['owner_name'] ?? '')));
$ownerNameMode = (string)($post['owner_name_mode'] ?? (is_array($contract['owner_name'] ?? null) ? 'array' : 'string'));
$rawDataJson = (string)($post['raw_data_json'] ?? contract_edit_raw_data_json($rawData));

render_header('title_edit_contract', ['layout' => 'admin', 'page' => 'dashboard']);
render_flash();
?>

<div class="mb-4 flex flex-wrap items-center gap-3">
    <a href="<?= e($detailsUrl) ?>" class="inline-flex items-center gap-1 text-sm text-karvi-600 hover:text-karvi-950">
        <span class="material-symbols-rounded text-base">arrow_back</span>
        <?= e(__('back_to_contract_details')) ?>
    </a>
</div>

<div class="card !p-5 sm:!p-6">
    <div class="mb-5 pb-4 border-b border-karvi-200">
        <h2 class="font-display font-bold text-lg text-karvi-950"><?= e(__('edit_contract_heading')) ?></h2>
        <p class="text-xs text-karvi-500 mt-0.5">Edit contract — PUT /karvipartner/contracts/<?= e((string)$contractId) ?></p>
    </div>

    <form method="POST" action="<?= e($action) ?>" class="compact-form space-y-5">
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="restaurant_name">restaurant_name</label>
                <input type="text" id="restaurant_name" name="restaurant_name" class="form-input" required value="<?= e((string)($post['restaurant_name'] ?? $contract['restaurant_name'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="brand">brand</label>
                <input type="text" id="brand" name="brand" class="form-input" value="<?= e((string)($post['brand'] ?? $contract['brand'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="contract_status">contract_status</label>
                <input type="text" id="contract_status" name="contract_status" class="form-input" value="<?= e((string)($post['contract_status'] ?? $contract['contract_status'] ?? 'draft')) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="owner_name_mode">owner_name format</label>
                <select id="owner_name_mode" name="owner_name_mode" class="form-input">
                    <option value="string" <?= $ownerNameMode === 'string' ? 'selected' : '' ?>>String</option>
                    <option value="array" <?= $ownerNameMode === 'array' ? 'selected' : '' ?>>Array of names</option>
                    <option value="json" <?= $ownerNameMode === 'json' ? 'selected' : '' ?>>JSON (string or array)</option>
                </select>
            </div>
            <div class="form-group sm:col-span-2" data-owner-mode="string">
                <label class="form-label" for="owner_name">owner_name</label>
                <input type="text" id="owner_name" name="owner_name" class="form-input" value="<?= e(is_array($contract['owner_name'] ?? null) ? implode(', ', $contract['owner_name']) : (string)($post['owner_name'] ?? $contract['owner_name'] ?? '')) ?>">
            </div>
            <div class="form-group sm:col-span-2 hidden" data-owner-mode="array">
                <span class="form-label">owner_name (array)</span>
                <div class="space-y-2" id="ownerNamesList">
                    <?php foreach ($ownerNames as $index => $name): ?>
                    <input type="text" name="owner_names[]" class="form-input" value="<?= e((string)$name) ?>" placeholder="Owner name <?= e((string)($index + 1)) ?>">
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn-secondary !py-1.5 !px-3 !text-xs mt-2" id="addOwnerNameRow">+ Add name</button>
            </div>
            <div class="form-group sm:col-span-2 hidden" data-owner-mode="json">
                <label class="form-label" for="owner_name_json">owner_name (JSON)</label>
                <textarea id="owner_name_json" name="owner_name_json" class="form-input font-mono text-xs min-h-[80px]" placeholder='["Max Mustermann","Erika Musterfrau"]'><?= e((string)($post['owner_name_json'] ?? contract_edit_owner_name_json($contract['owner_name'] ?? ''))) ?></textarea>
            </div>
            <div class="form-group">
                <label class="form-label" for="company_phone">company_phone</label>
                <input type="text" id="company_phone" name="company_phone" class="form-input" value="<?= e((string)($post['company_phone'] ?? $contract['company_phone'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="email">email</label>
                <input type="email" id="email" name="email" class="form-input" value="<?= e((string)($post['email'] ?? $contract['email'] ?? '')) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="street_address">street_address</label>
                <input type="text" id="street_address" name="street_address" class="form-input" value="<?= e((string)($post['street_address'] ?? $contract['street_address'] ?? '')) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="zip_city">zip_city</label>
                <input type="text" id="zip_city" name="zip_city" class="form-input" value="<?= e((string)($post['zip_city'] ?? $contract['zip_city'] ?? '')) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="contract_url">contract_url</label>
                <input type="url" id="contract_url" name="contract_url" class="form-input" value="<?= e((string)($post['contract_url'] ?? $contract['contract_url'] ?? '')) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="sign_url">sign_url</label>
                <input type="url" id="sign_url" name="sign_url" class="form-input" value="<?= e((string)($post['sign_url'] ?? $contract['sign_url'] ?? '')) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="customer_ip">customer_ip</label>
                <input type="text" id="customer_ip" name="customer_ip" class="form-input" value="<?= e((string)($post['customer_ip'] ?? contract_edit_nullable_field_value($contract['customer_ip'] ?? null))) ?>">
            </div>
            <div class="form-group flex items-end">
                <label class="inline-flex items-center gap-2 text-sm text-karvi-800">
                    <input type="checkbox" name="terms_accepted" value="1" <?= !empty($post['terms_accepted'] ?? $contract['terms_accepted'] ?? false) ? 'checked' : '' ?>>
                    terms_accepted
                </label>
            </div>
            <div class="form-group">
                <label class="form-label" for="terms_accepted_at">terms_accepted_at</label>
                <input type="text" id="terms_accepted_at" name="terms_accepted_at" class="form-input" placeholder="YYYY-MM-DD HH:MM:SS" value="<?= e((string)($post['terms_accepted_at'] ?? contract_edit_nullable_field_value($contract['terms_accepted_at'] ?? null))) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="sent_at">sent_at</label>
                <input type="text" id="sent_at" name="sent_at" class="form-input" value="<?= e((string)($post['sent_at'] ?? contract_edit_nullable_field_value($contract['sent_at'] ?? null))) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="viewed_at">viewed_at</label>
                <input type="text" id="viewed_at" name="viewed_at" class="form-input" value="<?= e((string)($post['viewed_at'] ?? contract_edit_nullable_field_value($contract['viewed_at'] ?? null))) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="signed_at">signed_at</label>
                <input type="text" id="signed_at" name="signed_at" class="form-input" value="<?= e((string)($post['signed_at'] ?? contract_edit_nullable_field_value($contract['signed_at'] ?? null))) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="signer_device_type">signer_device_type</label>
                <input type="text" id="signer_device_type" name="signer_device_type" class="form-input" value="<?= e((string)($post['signer_device_type'] ?? contract_edit_nullable_field_value($contract['signer_device_type'] ?? null))) ?>">
            </div>
            <div class="form-group">
                <label class="form-label" for="signer_browser">signer_browser</label>
                <input type="text" id="signer_browser" name="signer_browser" class="form-input" value="<?= e((string)($post['signer_browser'] ?? contract_edit_nullable_field_value($contract['signer_browser'] ?? null))) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="signer_os">signer_os</label>
                <input type="text" id="signer_os" name="signer_os" class="form-input" value="<?= e((string)($post['signer_os'] ?? contract_edit_nullable_field_value($contract['signer_os'] ?? null))) ?>">
            </div>
            <div class="form-group sm:col-span-2">
                <label class="form-label" for="raw_data_json">raw_data (JSON)</label>
                <textarea id="raw_data_json" name="raw_data_json" class="form-input font-mono text-xs min-h-[120px]" placeholder='{"anything":"saved as-is"}'><?= e($rawDataJson) ?></textarea>
            </div>
        </div>

        <div class="pt-3 border-t border-karvi-200 flex flex-wrap gap-3">
            <button type="submit" class="btn-primary !py-2.5">
                <span class="material-symbols-rounded">save</span>
                <?= e(__('save_contract_changes')) ?>
            </button>
            <a href="<?= e($detailsUrl) ?>" class="btn-secondary !py-2.5"><?= e(__('cancel')) ?></a>
        </div>
    </form>
</div>

<script>
(function () {
    const modeSelect = document.getElementById('owner_name_mode');
    const blocks = document.querySelectorAll('[data-owner-mode]');
    const addBtn = document.getElementById('addOwnerNameRow');
    const list = document.getElementById('ownerNamesList');

    function syncOwnerMode() {
        const mode = modeSelect ? modeSelect.value : 'string';
        blocks.forEach(function (block) {
            block.classList.toggle('hidden', block.getAttribute('data-owner-mode') !== mode);
        });
    }

    if (modeSelect) {
        modeSelect.addEventListener('change', syncOwnerMode);
        syncOwnerMode();
    }

    if (addBtn && list) {
        addBtn.addEventListener('click', function () {
            const input = document.createElement('input');
            input.type = 'text';
            input.name = 'owner_names[]';
            input.className = 'form-input';
            input.placeholder = 'Owner name';
            list.appendChild(input);
        });
    }
})();
</script>

<?php render_footer(['layout' => 'admin']); ?>
