<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/api_client.php';
require_once __DIR__ . '/../includes/invoice_contract.php';

auth_require();

$mode = $invoiceCreateMode ?? 'website';
$config = invoice_contract_mode_config($mode);
$selectedPosType = trim((string)($_POST['pos_contract_type'] ?? 'karvi_pos'));
$defaults = invoice_default_form_values($mode, $selectedPosType);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = generate_token();
    $contractData = collect_invoice_contract_from_post($_POST, $token, $mode);

    $validationError = validate_invoice_contract_form($contractData);
    if ($validationError) {
        set_flash($validationError, 'error', true);
        redirect($config['create_path']);
    }

    $environmentError = admin_create_environment_check();
    if ($environmentError) {
        set_flash($environmentError, 'error');
        redirect($config['create_path']);
    }

    try {
        $contract = invoice_save_contract($contractData);
        invoice_store_created_contract_session($contract, $mode);
        redirect($config['create_path']);
    } catch (Throwable $e) {
        set_flash(api_error_message($e), 'error');
    }
}

auth_start();
$createdContract = $_SESSION['invoice_contract_created'] ?? null;
unset($_SESSION['invoice_contract_created']);
if (!is_array($createdContract) || (string)($createdContract['mode'] ?? '') !== $mode) {
    $createdContract = null;
} elseif (empty($createdContract['display_link']) && !empty($createdContract['share_link'])) {
    $createdContract['display_link'] = (string)$createdContract['share_link'];
}
if (is_array($createdContract) && trim((string)($createdContract['display_link'] ?? '')) === '') {
    $createdContract = null;
}

render_header($config['form_title_key'], ['layout' => 'admin', 'page' => $config['create_page']]);
render_flash();
?>

<div class="invoice-page-head mb-6">
    <a href="<?= e(app_path($config['list_path'])) ?>" class="btn-secondary invoice-back-btn">
        <span class="material-symbols-rounded">arrow_back</span>
        <?= e(__('back')) ?>
    </a>
    <h2 class="font-display font-bold text-xl sm:text-2xl text-karvi-950 text-center flex-1"><?= e(__($config['form_title_key'])) ?></h2>
    <div class="invoice-page-head-spacer" aria-hidden="true"></div>
</div>

<form method="POST" action="<?= e(app_path($config['create_path'])) ?>" id="invoiceContractForm" class="invoice-contract-form">
    <div class="invoice-contract-grid">
        <div class="invoice-contract-left space-y-3">
            <div class="card invoice-field-card">
                <div class="form-group">
                    <label class="form-label" for="contract_date"><?= e(__('invoice_contract_date')) ?> *</label>
                    <input type="date" id="contract_date" name="contract_date" class="form-input" value="<?= e($defaults['contract_date']) ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="installment_months"><?= e(__('invoice_installment_months')) ?></label>
                    <input type="number" id="installment_months" name="installment_months" class="form-input" min="1" max="120" value="<?= e($defaults['installment_months']) ?>">
                </div>
            </div>

            <?php if ($mode === 'pos'): ?>
            <div class="card invoice-field-card">
                <div class="form-group !mb-0">
                    <span class="form-label"><?= e(__('invoice_pos_contract_type')) ?></span>
                    <div class="invoice-pos-type-group">
                        <?php foreach (invoice_pos_contract_types() as $typeKey => $typeConfig): ?>
                        <label class="invoice-pos-type-option">
                            <input
                                type="radio"
                                name="pos_contract_type"
                                value="<?= e($typeKey) ?>"
                                <?= $selectedPosType === $typeKey ? 'checked' : '' ?>
                            >
                            <span><?= e(__($typeConfig['label_key'])) ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="card invoice-field-card">
                <h3 class="invoice-section-title"><?= e(__('invoice_customer_details')) ?></h3>
                <div class="invoice-customer-fields space-y-3">
                    <div class="form-group">
                        <label class="form-label" for="customer_contact"><?= e(__('invoice_customer_contact')) ?> *</label>
                        <input type="text" id="customer_contact" name="customer_contact" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="customer_company"><?= e(__('invoice_customer_company')) ?></label>
                        <input type="text" id="customer_company" name="customer_company" class="form-input">
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="customer_street"><?= e(__('invoice_customer_street')) ?></label>
                        <input type="text" id="customer_street" name="customer_street" class="form-input">
                    </div>
                    <div class="form-group !mb-0">
                        <label class="form-label" for="customer_city"><?= e(__('invoice_customer_city')) ?></label>
                        <input type="text" id="customer_city" name="customer_city" class="form-input">
                    </div>
                </div>
            </div>
        </div>

        <div class="card invoice-field-card invoice-contract-right">
            <h3 class="invoice-section-title"><?= e(__('invoice_services_line_items')) ?></h3>

            <div class="invoice-actions-row">
                <?php if ($mode === 'website'): ?>
                <label class="invoice-optional-label">
                    <input type="checkbox" name="optional_printer" value="1" id="optional_printer" class="invoice-optional-checkbox">
                    <span class="invoice-optional-badge"><?= e(__('invoice_optional')) ?></span>
                    <span class="invoice-optional-text"><?= e((string)$defaults['optional_item']['description']) ?></span>
                </label>
                <input
                    type="text"
                    name="optional_printer_price"
                    id="optional_printer_price"
                    class="form-input invoice-optional-price-input"
                    value="<?= e(invoice_format_money((float)$defaults['optional_item']['unit_price_net'])) ?>"
                    inputmode="decimal"
                    aria-label="<?= e((string)$defaults['optional_item']['description']) ?>"
                >
                <?php endif; ?>
                <?php if ($mode === 'pos'): ?>
                <button type="button" id="invoiceSelectServicesBtn" class="btn-primary invoice-select-services-btn">
                    <span class="material-symbols-rounded">inventory_2</span>
                    <?= e(__('invoice_select_services')) ?>
                </button>
                <?php endif; ?>
                <button type="button" id="invoiceAddLineBtn" class="btn-secondary invoice-add-line-btn">
                    <span class="material-symbols-rounded">add</span>
                    <?= e(__('invoice_add_line_item')) ?>
                </button>
            </div>

            <div class="invoice-line-table-wrap">
                <table class="invoice-line-table">
                    <thead>
                        <tr>
                            <th><?= e(__('invoice_col_description')) ?></th>
                            <th><?= e(__('invoice_col_quantity')) ?></th>
                            <th><?= e(__('invoice_col_unit_price')) ?></th>
                            <th><?= e(__('invoice_col_total')) ?></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="invoiceLineItemsBody">
                        <?php if (empty($defaults['line_items'])): ?>
                        <tr id="invoiceEmptyRow" class="invoice-empty-row">
                            <td colspan="5" class="text-center text-sm text-karvi-500 py-6"><?= e(__('invoice_no_line_items')) ?></td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($defaults['line_items'] as $index => $item): ?>
                        <tr class="invoice-line-row">
                            <td>
                                <input type="text" name="line_description[]" class="form-input invoice-line-description" value="<?= e((string)$item['description']) ?>" required>
                            </td>
                            <td>
                                <input type="number" name="line_quantity[]" class="form-input invoice-line-qty" min="1" value="<?= e((string)$item['quantity']) ?>" required>
                            </td>
                            <td>
                                <input type="text" name="line_unit_price[]" class="form-input invoice-line-price" value="<?= e((string)$item['unit_price_net']) ?>" required>
                            </td>
                            <td class="invoice-line-total-cell">
                                <span class="invoice-line-total"><?= e(invoice_format_money(invoice_parse_money((string)$item['unit_price_net']) * (int)$item['quantity'])) ?></span>
                            </td>
                            <td>
                                <button type="button" class="invoice-line-remove btn-ghost" title="<?= e(__('invoice_remove_line')) ?>"<?= $index === 0 ? ' hidden' : '' ?>>
                                    <span class="material-symbols-rounded">close</span>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="invoice-totals-grid">
                <div class="invoice-total-item">
                    <span><?= e(__('invoice_subtotal')) ?></span>
                    <strong id="invoiceSubtotal"><?= e(invoice_format_money(0)) ?></strong>
                </div>
                <div class="invoice-total-item">
                    <span><?= e(__('invoice_vat')) ?></span>
                    <strong id="invoiceVat"><?= e(invoice_format_money(0)) ?></strong>
                </div>
                <div class="invoice-total-item invoice-total-discount">
                    <span><?= e(__('invoice_discount')) ?></span>
                    <input type="text" name="discount" id="invoiceDiscount" class="form-input invoice-discount-input" value="<?= e($defaults['discount']) ?>">
                </div>
                <div class="invoice-total-item">
                    <span><?= e(__('invoice_net')) ?></span>
                    <strong id="invoiceNet"><?= e(invoice_format_money(0)) ?></strong>
                </div>
            </div>

            <div class="invoice-total-amount">
                <span><?= e(__('invoice_total_amount')) ?></span>
                <strong id="invoiceTotal"><?= e(invoice_format_money(0)) ?></strong>
            </div>
        </div>
    </div>

    <button type="submit" class="btn-primary invoice-submit-btn w-full mt-6">
        <?= e(__('invoice_create_generate_link')) ?>
    </button>
</form>

<?php if ($mode === 'pos'): ?>
<div id="invoiceServicesModal" class="admin-modal hidden" role="dialog" aria-modal="true" aria-labelledby="invoiceServicesModalTitle">
    <div class="admin-modal-backdrop" data-services-modal-close></div>
    <div class="admin-modal-dialog invoice-services-dialog">
        <div class="admin-modal-head">
            <div class="flex items-start justify-between gap-3">
                <div>
                    <h3 id="invoiceServicesModalTitle" class="font-display font-bold text-lg text-karvi-950"><?= e(__('invoice_select_services')) ?></h3>
                    <p class="text-sm text-karvi-500 mt-1"><?= e(__('invoice_select_services_sub')) ?></p>
                </div>
                <button type="button" class="btn-ghost !p-2" data-services-modal-close aria-label="<?= e(__('cancel')) ?>">
                    <span class="material-symbols-rounded">close</span>
                </button>
            </div>
        </div>
        <div class="admin-modal-body invoice-services-body">
            <div class="invoice-service-list">
                <?php foreach (invoice_pos_service_catalog() as $service): ?>
                <div class="invoice-service-item">
                    <div class="invoice-service-item-main">
                        <p class="invoice-service-item-title"><?= e($service['title']) ?></p>
                        <p class="invoice-service-item-price"><?= e(invoice_format_money((float)$service['price'])) ?> <span><?= e($service['suffix']) ?></span></p>
                    </div>
                    <button
                        type="button"
                        class="btn-secondary invoice-service-add-btn"
                        data-service-title="<?= e($service['title']) ?>"
                        data-service-price="<?= e(invoice_format_money((float)$service['price'])) ?>"
                    >
                        <span class="material-symbols-rounded">add</span>
                        <?= e(__('invoice_service_add')) ?>
                    </button>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="invoice-service-group">
                <button type="button" class="invoice-service-group-toggle" id="invoiceDisplaysToggle" aria-expanded="true">
                    <span><?= e(__('invoice_display_screens')) ?></span>
                    <span class="material-symbols-rounded invoice-service-group-icon">expand_less</span>
                </button>
                <div class="invoice-service-list invoice-service-list-collapsible" id="invoiceDisplaysList">
                    <?php foreach (invoice_pos_display_catalog() as $display): ?>
                    <div class="invoice-service-item">
                        <div class="invoice-service-item-main">
                            <p class="invoice-service-item-title"><?= e($display['title']) ?></p>
                            <p class="invoice-service-item-price"><?= e(invoice_format_money((float)$display['price'])) ?> <span><?= e($display['suffix']) ?></span></p>
                        </div>
                        <button
                            type="button"
                            class="btn-secondary invoice-service-add-btn"
                            data-service-title="<?= e($display['title']) ?>"
                            data-service-price="<?= e(invoice_format_money((float)$display['price'])) ?>"
                        >
                            <span class="material-symbols-rounded">add</span>
                            <?= e(__('invoice_service_add')) ?>
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (is_array($createdContract) && trim((string)($createdContract['display_link'] ?? '')) !== ''): ?>
<div id="invoiceContractCreatedModal" class="admin-modal" role="dialog" aria-modal="true" aria-labelledby="invoiceContractCreatedModalTitle">
    <div class="admin-modal-backdrop" data-created-modal-close></div>
    <div class="admin-modal-dialog invoice-created-dialog">
        <div class="invoice-created-header">
            <div class="invoice-created-header-main">
                <div class="invoice-created-icon" aria-hidden="true">
                    <span class="material-symbols-rounded">check_circle</span>
                </div>
                <div class="invoice-created-copyline">
                    <div class="invoice-created-text">
                        <h3 id="invoiceContractCreatedModalTitle" class="invoice-created-title"><?= e(__('invoice_contract_created_modal_title')) ?></h3>
                        <p class="invoice-created-sub"><?= e(__('invoice_contract_created_modal_sub')) ?></p>
                    </div>
                    <button type="button" data-copy="invoiceCreatedContractLink" class="btn-secondary invoice-created-copy-btn">
                        <span class="material-symbols-rounded">content_copy</span>
                        <?= e(__('copy_link_btn')) ?>
                    </button>
                </div>
            </div>
            <?php if (!empty($createdContract['contract_id'])): ?>
            <div class="invoice-created-meta">
                <span class="invoice-created-id-badge">#<?= e((string)$createdContract['contract_id']) ?></span>
                <?php if (!empty($createdContract['api_message'])): ?>
                <span class="invoice-created-status"><?= e((string)$createdContract['api_message']) ?></span>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="invoice-created-link-card">
            <label class="invoice-created-link-label" for="invoiceCreatedContractLink"><?= e(__('invoice_contract_created_link_label')) ?></label>
            <div class="invoice-created-link-row">
                <input type="text" id="invoiceCreatedContractLink" readonly value="<?= e((string)$createdContract['display_link']) ?>" class="form-input invoice-created-link-input">
                <button type="button" data-copy="invoiceCreatedContractLink" class="btn-secondary invoice-created-link-copy" title="<?= e(__('copy_link_btn')) ?>">
                    <span class="material-symbols-rounded">content_copy</span>
                </button>
            </div>
        </div>

        <div class="invoice-created-actions">
            <a href="<?= e((string)$createdContract['display_link']) ?>" target="_blank" rel="noopener noreferrer" class="btn-primary invoice-created-open-btn">
                <span class="material-symbols-rounded">open_in_new</span>
                <?= e(__('open_link')) ?>
            </a>
            <button type="button" class="btn-secondary" data-created-modal-close><?= e(__('invoice_contract_created_modal_close')) ?></button>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
<?php
$posTypeDefaults = [];
if ($mode === 'pos') {
    foreach (invoice_pos_contract_types() as $typeKey => $typeConfig) {
        unset($typeConfig);
        $posTypeDefaults[$typeKey] = [
            'line_items' => array_map(
                static fn(array $item): array => [
                    'description' => (string)($item['description'] ?? ''),
                    'price' => (string)($item['unit_price_net'] ?? '0,00 €'),
                ],
                invoice_pos_default_line_items($typeKey)
            ),
        ];
    }
}
?>
window.KARVI_INVOICE_FORM = <?= json_encode([
    'mode' => $mode,
    'vatRate' => 19,
    'optionalPrice' => (float)($defaults['optional_item']['unit_price_net'] ?? 0),
    'hasOptionalPrinter' => invoice_mode_has_optional_printer($mode),
    'posTypeDefaults' => $posTypeDefaults,
    'labels' => [
        'remove_line' => __('invoice_remove_line'),
        'no_line_items' => __('invoice_no_line_items'),
    ],
], JSON_UNESCAPED_UNICODE) ?>;
</script>

<?php
$invoiceFooterScripts = ['/assets/js/invoice-contract-form.js'];
if (is_array($createdContract) && trim((string)($createdContract['display_link'] ?? '')) !== '') {
    $invoiceFooterScripts[] = '/assets/js/invoice-contract-created-modal.js';
}
render_footer(['layout' => 'admin', 'scripts' => $invoiceFooterScripts]); ?>
