<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte.js';

    let   content = $state(null);
    let   doc     = $state(null);
    let   email   = $state(null);
    const router  = useTinyRouter();
    let   subject = $state(null);
    let { id }    = $props();

    async function loadDoc(){
        let url  = api(`document/${id}`);
        let resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            doc     = await resp.json();
            email   = doc.customer.email;
            subject = t('new_document_from',{type:t(doc.type),sender:doc.company.name,number:doc.number}),
            yikes();
        } else {
            error(resp);
            return;
        }
        url  = api(`document/${id}/settings`);
        resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            const settings = await resp.json();
            content        = settings.content;
        } else {
            error(resp);
        }
    }

    async function doSend(){
        var data = {email:email,subject:subject,content:content};
        const url  = api(`document/${id}/send`);
        const resp = await fetch(url,{
            credentials : 'include',
            method      : 'POST',
            body        : JSON.stringify(data)
        });
        if (resp.ok){
            router.navigate(`/document?company_id=${doc.company.id}`);
        } else {
            error(resp);
        }
    }

    onMount(loadDoc);
</script>

<fieldset>
    <legend>{t('customer_email')} / {t('subject')}</legend>
    <input type="text" bind:value={email} />
    <input type="text" bind:value={subject} />
</fieldset>
<fieldset>
    <legend>{t('message')}</legend>
    <textarea bind:value={content}></textarea>
</fieldset>
<fieldset>
    <legend>{t('actions')}</legend>
    <button onclick={() => router.navigate(`/document/${id}/view`)}>{t('abort')}</button>
    <button onclick={doSend}>{t('do_send')}</button>
</fieldset>