let officeReady=false,currentBooking=null,addinSession='';

Office.onReady(info=>{
    officeReady=info.host===Office.HostType.Outlook;
});

document.addEventListener('DOMContentLoaded',()=>{
    document.getElementById('usePrepared').addEventListener('click',exchangeToken);
    document.getElementById('attachBtn').addEventListener('click',attachPdf);
});

async function exchangeToken(){
    const token=(document.getElementById('handoffCode').value||'').trim().toUpperCase();

    if(!token){
        show('No prepared RoomZ booking was found. Enter the one-time code shown in RoomZ.','error');
        return;
    }

    busy('usePrepared',true,'Connecting…');

    try{
        const response=await fetch('api/exchange_token.php',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({token:token,code:token})
        });

        const data=await readJson(response);
        if(!response.ok||!data.ok){
            throw new Error(data.message||'Token exchange failed.');
        }

        addinSession=data.session_token;
        currentBooking=data.booking;

        document.getElementById('handoffCode').value='';
        document.getElementById('bookingTitle').textContent=
            currentBooking.order_no||`Booking #${currentBooking.id}`;
        document.getElementById('guestName').textContent=
            currentBooking.guest_name||'Guest';
        document.getElementById('stayDates').textContent=
            `${currentBooking.check_in||'—'} to ${currentBooking.check_out||'—'}`;
        document.getElementById('agentName').textContent=
            currentBooking.agent_name||'Direct';

        document.getElementById('connectCard').classList.add('hidden');
        document.getElementById('bookingCard').classList.remove('hidden');
        show('Booking loaded securely.','ok');
    }catch(error){
        addinSession='';
        currentBooking=null;
        show(error.message,'error');
    }finally{
        busy('usePrepared',false,'Use prepared booking');
    }
}

async function attachPdf(){
    if(!officeReady||!Office.context.mailbox.item){
        show('Open this add-in inside an Outlook reply or compose window.','error');
        return;
    }

    if(!addinSession||!currentBooking){
        show('The prepared booking session is missing. Generate and enter a new RoomZ code.','error');
        return;
    }

    busy('attachBtn',true,'Preparing PDF…');

    try{
        const response=await fetch('api/document.php',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json',
                'Authorization':'Bearer '+addinSession
            },
            /*
             * Send the session in JSON as well as the header. Shared hosting
             * frequently strips Authorization headers before PHP receives them.
             */
            body:JSON.stringify({
                document_type:document.getElementById('documentType').value,
                session_token:addinSession
            })
        });

        const data=await readJson(response);
        if(!response.ok||!data.ok){
            throw new Error(data.message||'PDF generation failed.');
        }

        busy('attachBtn',true,'Attaching…');

        await new Promise((resolve,reject)=>{
            Office.context.mailbox.item.addFileAttachmentFromBase64Async(
                data.base64,
                data.filename,
                {isInline:false},
                result=>{
                    if(result.status===Office.AsyncResultStatus.Succeeded){
                        resolve(result.value);
                    }else{
                        reject(new Error(
                            (result.error&&result.error.message)
                            ||'Outlook could not attach the PDF.'
                        ));
                    }
                }
            );
        });

        show(`${data.filename} was attached to this reply.`,'ok');
    }catch(error){
        show(error.message,'error');
    }finally{
        busy('attachBtn',false,'Attach PDF to this reply');
    }
}

function busy(id,on,text){
    const button=document.getElementById(id);
    button.disabled=on;
    button.textContent=text;
}

function show(text,type){
    const box=document.getElementById('message');
    box.textContent=text;
    box.className=`message ${type}`;
}

async function readJson(response){
    const text=await response.text();
    try{
        return JSON.parse(text);
    }catch(error){
        if(/<!doctype|<html/i.test(text)){
            throw new Error('The RoomZ server returned an HTML page instead of API JSON.');
        }
        throw new Error(text.trim()||`Unexpected server response (${response.status}).`);
    }
}
