<script>
    import { onMount } from 'svelte';
    import { t } from '../../translations.svelte.js';
    import { useTinyRouter } from 'svelte-tiny-router';
    import ContactSelector from '../../Components/ContactSelector.svelte';

    let router = useTinyRouter();
    let company = $state(null);
    let error = $state(null);
    let docType = $state(null);
    let document = $state({
        type : +router.query.document_type,
        customer : {
            name : ''
        },
        sender : {
            name : 'sender',
            company : +router.query.company_id
        }
    });

    async function loadCompanies(){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/companies`;
        var resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            const companies = await resp.json();
            for (let c of companies) {
                if (c.id == document.sender.company) company = c;
            }
            document.sender.name = '';
            if (company.name)         document.sender.name        += company.name+"\n";
            if (company.address)      document.sender.name        += company.address+"\n";
            if (company.tax_number)   document.sender.tax_id       = company.tax_number;
            if (company.bank_account) document.sender.bank_account = company.bank_account;
            if (company.court)        document.sender.court        = company.court;
        } else {
            error = await resp.text();
        }
    }

    async function loadDocType(){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/types`;
        var resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            const types = await resp.json();
            docType = t('document.type_'+types[document.type]);
        } else {
            error = await resp.text();
        }
    }

    function load(){
        loadCompanies();
        loadDocType();
    }

    function contactSelected(contact){
        var addr = '';
        if (contact.ORG) addr += contact.ORG.trim()+"\n";
        if (contact.N) {
            var name = (contact.N.given+" "+contact.N.family).trim()+"\n";
            if (name != addr) addr += name;
        }
        if (contact.ADR.street)   addr += contact.ADR.street+"\n";
        if (contact.ADR.locality) addr += contact.ADR.post_code + " "+ contact.ADR.locality + "\n";
        if (contact.ADR.county)   addr += contact.ADR.country+"\n";
        document.customer.name   = addr;
        document.customer.tax_id = contact['X-TAX-NUMBER'];
        document.customer.id     = contact['X-CUSTOMER-NUMBER'];
        document.customer.email  = contact.EMAIL.val;
    }

    async function submit(){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document`;
        const resp = await fetch(url,{
            method: 'POST',
            credentials: 'include',
            body: JSON.stringify(document)
        });
        if (resp.ok){
            const json = await resp.json();
            router.navigate(`/document/${json.id}/view`);
        } else {
            error = await resp.text();
        }
    }

    onMount(load);
</script>

<style>
    label{display:block}
</style>

<fieldset>
    {#if error}
    <span class="error">{error}</span>
    {/if}
    {#if docType}
    <legend>{t('document.add_new',docType)}</legend>
    {/if}
    {#if company}
    Company: {company.name}
    <fieldset>
        <legend>{t('document.customer')}</legend>
        <ContactSelector caption={t('document.select_customer')} onselect={contactSelected} />
        <label>
            <textarea bind:value={document.customer.name}></textarea>
            {t('document.customer_address')}
        </label>
        <label>
            <input bind:value={document.customer.tax_id} />
            {t('document.tax_id')}
        </label>
        <label>
            <input bind:value={document.customer.id} />
            {t('document.customer_id')}
        </label>
        <label>
            <input bind:value={document.customer.email} />
            {t('document.email')}
        </label>
    </fieldset>
    {/if}
    <fieldset>
        <legend>{t('document.sender')}</legend>
        <label>
            <textarea bind:value={document.sender.name}></textarea>
            {t('document.sender_name')}
        </label>
        <label>
            <input bind:value={document.sender.tax_id} />
            {t('document.sender_tax_id')}
        </label>
        <label>
            <textarea bind:value={document.sender.bank_account}></textarea>
            {t('document.sender_bank_account')}
        </label>
        <label>
            <input bind:value={document.sender.court} />
            {t('document.sender_local_court')}
        </label>
    </fieldset>
    <button onclick={submit}>{t('document.create_new')}</button>
</fieldset>