<div style="padding:24px 32px 24px">
<div class="tile" id="payTile">
  
      <div class="tile-status" id="tileStatus"><?= ($feeAgreed && $payAddress && $payCity && $payCountry) ? '✓ Complete' : '⊗ Incomplete' ?></div>
    </div>
    <span style="font-size:16px;color:#888" id="tileChev">∧</span>
  </div>

  <div id="tileContent">
  <div class="tile-inner">
  <div class="pay-wrap">

    <!-- ── BILLING DETAILS ─────────────────────────────────── -->
    <div class="sec-title">Billing Details</div>
    <div class="sec-desc">Please fill in the Invoice recipient details below. These details will be used if the article publishing charges (APCs) are not covered by an institutional partner.</div>

    <!-- Invoice Recipient dropdown -->
    <div class="fg">
      <label class="fl req" for="invoiceRcpt">Invoice Recipient</label>
      <div class="rcpt-dd">
        <select class="fi" id="invoiceRcpt" onchange="onRcptChange(this)">
          <?php foreach($authors as $a):
            $name = trim(($a['first_name']??'').' '.($a['middle_name']??'').' '.($a['last_name']??''));
            $val  = 'author_'.$a['author_id'];
          ?>
          <option value="<?= $val ?>"
                  data-type="author"
                  data-id="<?= $a['author_id'] ?>"
                  data-email="<?= p($a['email']??$a['institutional_email']??'') ?>"
                  data-affil="<?= p($a['affil_name']??'') ?>"
                  <?= (($invoiceType==='author'&&(string)$invoiceAuthorId===(string)$a['author_id'])||($invoiceType!=='other'&&$a['is_corresponding']&&!$invoiceAuthorId))?'selected':'' ?>>
            <?= p($name) ?><?= $a['is_corresponding'] ? ' — CORRESPONDING AUTHOR' : '' ?>
          </option>
          <?php endforeach; ?>
          <option value="other" data-type="other" <?= $invoiceType==='other'?'selected':'' ?>>Other</option>
        </select>
      </div>
    </div>

    <!-- Other person fields (shown when "Other" selected) -->
    <div class="other-fields <?= $invoiceType==='other'?'show':'' ?>" id="otherFields">
      <div class="grid3" style="margin-bottom:14px">
        <div class="fg" style="margin-bottom:0">
          <label class="fl req" for="otherFirst">First name</label>
          <input type="text" class="fi" id="otherFirst" placeholder="First name" value="<?= p($otherFirst) ?>" oninput="pay_dirty();clearErr(this)">
        </div>
        <div class="fg" style="margin-bottom:0">
          <label class="fl" for="otherMiddle">Middle name (optional)</label>
          <input type="text" class="fi" id="otherMiddle" placeholder="Middle name (optional)" value="<?= p($otherMiddle) ?>" oninput="pay_dirty()">
        </div>
        <div class="fg" style="margin-bottom:0">
          <label class="fl req" for="otherLast">Last name</label>
          <input type="text" class="fi" id="otherLast" placeholder="Last name" value="<?= p($otherLast) ?>" oninput="pay_dirty();clearErr(this)">
        </div>
      </div>
      <div class="grid2-1" style="margin-bottom:14px">
        <div class="fg" style="margin-bottom:0">
          <label class="fl req" for="otherEmail">Billing Email</label>
          <input type="email" class="fi" id="otherEmail" placeholder="Billing Email" value="<?= p($otherEmail) ?>" oninput="pay_dirty();clearErr(this)">
        </div>
        <div class="fg" style="margin-bottom:0">
          <label class="fl" for="otherTitle">Title</label>
          <select class="fi" id="otherTitle" onchange="pay_dirty()">
            <option value="">Title (optional)</option>
            <?php foreach(['Dr','Prof','Mr','Mrs','Ms','Mx'] as $t): ?>
            <option value="<?= $t ?>" <?= sel($otherTitle,$t) ?>><?= $t ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>
    </div>

    <!-- Affiliation -->
    <div class="fg">
      <label class="fl" for="affilInp">Affiliation (optional)</label>
      <div class="affil-wrap">
        <input type="text" class="fi" id="affilInp" placeholder="Affiliation (optional)"
               value="<?= p($affiliation) ?>" oninput="pay_dirty()">
        <button type="button" class="affil-clear" id="affilClear"
                style="<?= $affiliation ? '' : 'display:none' ?>"
                onclick="document.getElementById('affilInp').value='';this.style.display='none';pay_dirty()">&#x2715;</button>
      </div>
    </div>

    <!-- Billing Email (for author selection) -->
    <div class="fg" id="authorEmailFg" style="<?= $invoiceType==='other'?'display:none':'' ?>">
      <label class="fl req" for="billingEmail">Billing Email</label>
      <input type="email" class="fi" id="billingEmail"
             placeholder="Billing Email" value="<?= p($billingEmail) ?>"
             oninput="pay_dirty();clearErr(this)">
    </div>

    <!-- Phone Number -->
    <div class="fg">
      <label class="fl req" for="phoneNum">Phone Number</label>
      <div class="phone-row">
        <select class="fi" id="phoneCode" onchange="pay_dirty()">
          <option value="">Country</option>
          <?php foreach($phoneCodes as $code => $label): ?>
          <option value="<?= $code ?>" <?= sel($phoneCode,$code) ?>><?= $code ?> <?= $label ?></option>
          <?php endforeach; ?>
        </select>
        <input type="tel" class="fi" id="phoneNum" placeholder="Phone Number"
               value="<?= p($phoneNum) ?>" oninput="pay_dirty();clearErr(this)">
      </div>
    </div>

    <!-- Address -->
    <div class="fg">
      <label class="fl req" for="address">Address</label>
      <textarea class="fi fi-ta" id="address" placeholder="Address"
                oninput="pay_dirty();clearErr(this)"><?= p($payAddress) ?></textarea>
    </div>

    <!-- City / ZIP / Country -->
    <div class="grid3">
      <div class="fg">
        <label class="fl req" for="city">City</label>
        <input type="text" class="fi" id="city" placeholder="City"
               value="<?= p($payCity) ?>" oninput="pay_dirty();clearErr(this)">
      </div>
      <div class="fg">
        <label class="fl req" for="zip">Zip/Postal code</label>
        <input type="text" class="fi" id="zip" placeholder="Zip/Postal code"
               value="<?= p($payZip) ?>" oninput="pay_dirty();clearErr(this)">
      </div>
      <div class="fg">
        <label class="fl req" for="countryDisplay">Country/Region</label>
        <div class="country-dd" id="countryDd">
          <input type="text" class="fi country-inp" id="countryDisplay"
                 placeholder="Country/Region"
                 value="<?= p($payCountry) ?>" readonly
                 onclick="toggleCountryList()" oninput="filterCountries(this.value)">
          <input type="hidden" id="countryVal" value="<?= p($payCountry) ?>">
          <div class="country-list" id="countryList">
            <input type="text" class="country-search" id="countrySearch"
                   placeholder="Country/Region" oninput="filterCountries(this.value)">
            <div class="country-opts" id="countryOpts"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="merr" id="mandatoryErr">&#x2297; Please fill mandatory fields to continue</div>

    <!-- Billing Reference -->
    <div class="fg">
      <label class="fl" for="billingRef">Billing reference (optional)</label>
      <div class="sec-desc" style="margin-bottom:8px;font-size:12.5px">You may add here any additional information to be included in the invoice (e.g. VAT number or purchasing order). Please note that this field is not verified by our accounting team.</div>
      <textarea class="fi fi-ta" id="billingRef" placeholder="Organization VAT number, purchase order, etc"
                oninput="pay_dirty()"><?= p($billingRef) ?></textarea>
    </div>

    <hr class="sd">

    <!-- ── PAYER SELECTION ─────────────────────────────────── -->
    <div class="sec-title" style="margin-bottom:6px">Payer Selection</div>
    <div class="sec-desc">Please select the appropriate payer.</div>
    <?php foreach($authors as $a):
      $name = trim(($a['first_name']??'').' '.($a['middle_name']??'').' '.($a['last_name']??''));
      $val  = 'individual_'.$a['author_id'];
      $isSel = ($payerType === $val) || (empty($pay) && $a['is_corresponding'] && $invoiceType!=='other');
    ?>
    <div class="payer-card <?= $isSel?'selected':'' ?>"
         id="payerCard_author_<?= $a['author_id'] ?>"
         onclick="selectPayer('<?= $val ?>',this)">
      <input type="radio" name="payer" value="<?= $val ?>" <?= $isSel?'checked':'' ?>>
      <div>
        <div class="payer-name">Individual payer</div>
        <div class="payer-sub"><?= p($name) ?><?= $a['is_corresponding'] ? ' <span class="badge">CORRESPONDING AUTHOR</span>':'' ?></div>
      </div>
    </div>
    <?php endforeach; ?>
    <!-- Other payer card — shown when Invoice Recipient = Other -->
    <?php $otherPayerSel = ($payerType==='individual_other')||($invoiceType==='other'&&empty($pay)); ?>
    <div class="payer-card <?= $otherPayerSel?'selected':'' ?>"
         id="payerCardOther"
         style="<?= $invoiceType==='other'?'':'display:none' ?>"
         onclick="selectPayer('individual_other',this)">
      <input type="radio" name="payer" value="individual_other" <?= $otherPayerSel?'checked':'' ?>>
      <div>
        <div class="payer-name">Individual payer</div>
        <div class="payer-sub" id="payerOtherName"><?= p(trim(($otherFirst??'').' '.($otherLast??''))) ?: 'Other' ?></div>
      </div>
    </div>

    <hr class="sd">

    <!-- ── DISCOUNT CODE ──────────────────────────────────── -->
    <div class="sec-title" style="margin-bottom:6px">Discount code (optional)</div>
    <div class="sec-desc">If you have received a discount code from communeglobal, please enter it below. You can apply up to 12 discount codes. Once validated, discounts will be applied to the invoice upon submission.</div>
    <div class="discount-row">
      <input type="text" class="discount-inp" id="discountInp" placeholder=""
             onkeydown="if(event.key==='Enter'){event.preventDefault();addDiscount();}">
      <button type="button" class="discount-add" onclick="addDiscount()" title="Add">+</button>
    </div>
    <div class="dtags" id="dtags"></div>

    <hr class="sd">

    <!-- ── PRELIMINARY FEES ───────────────────────────────── -->
    <div class="sec-title" style="margin-bottom:4px">Preliminary fees</div>
    <div class="fee-table">
      <div class="fee-row"><span class="fee-lbl">Article Processing Fee</span><span><?= $feeFormatted ?> CHF</span></div>
      <div class="fee-row subtotal">
        <span class="fee-lbl">Sub total</span>
        <div style="text-align:right">
          <div><?= $feeFormatted ?> CHF</div>
          <div style="font-size:12px;color:var(--muted)">VAT rate 0.00% &nbsp;&nbsp;&nbsp; 0.00 CHF</div>
        </div>
      </div>
      <div class="fee-row total">
        <span>TOTAL DUE <span style="font-weight:400;font-size:12px">(after acceptance)</span></span>
        <span><?= $feeFormatted ?> CHF</span>
      </div>
    </div>

    <!-- Agreement checkbox -->
    <label class="agree-row">
      <input type="checkbox" id="feeAgree" <?= $feeAgreed?'checked':'' ?>
             onchange="pay_dirty();document.getElementById('agreeErr').classList.remove('show')">
      <span>I and my fellow co-authors are fully aware of and agree with the payment of the listed article processing fee should the manuscript be accepted for publication.</span>
    </label>
    <div class="agree-err" id="agreeErr">&#x2297; Please mark this checkbox to continue</div>
    <div class="fee-policy"><a href="#" style="font-size:12.5px">&#x2139; Fee policy</a></div>

  </div><!-- /pay-wrap -->

  <!-- Nav buttons -->
  
  </div>
  </div>
</div><!-- /tile -->

<div class="bottom-bar">
  <div class="btm-fee">Preliminary fees: <strong><?= $feeFormatted ?> CHF</strong><br><span style="font-size:11px">Payment after acceptance</span></div>
  <div class="btm-q">Submission quality: <strong>90%</strong> <span style="font-size:11.5px;color:var(--muted)">&#x2139; 1 suggested action</span></div>
  <div class="btm-acts"><button class="btn btn-outline">Preview</button><button class="btn btn-fill">Submit</button></div>
</div>

<script>
const SID = <?= $sid ?>;
let isDirty = false, autoTimer = null;
let discountCodes = <?= json_encode($discountCodes) ?>;
const ALL_COUNTRIES = <?= json_encode($countries) ?>;
let countryListOpen = false;

/* ── Tile ─── */
function toggleTile(){const c=document.getElementById('tileContent');const o=c.style.display!=='none';c.style.display=o?'none':'';document.getElementById('tileChev').textContent=o?'∨':'∧';}
function xe(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}

/* ── Invoice recipient change ─── */
function onRcptChange(sel){
  const opt = sel.options[sel.selectedIndex];
  const type = opt.getAttribute('data-type');
  const email = opt.getAttribute('data-email') || '';
  const affil = opt.getAttribute('data-affil') || '';
  const isOther = type === 'other';

  document.getElementById('otherFields').classList.toggle('show', isOther);
  document.getElementById('authorEmailFg').style.display = isOther ? 'none' : '';

  // Show/hide payer cards
  const otherCard = document.getElementById('payerCardOther');
  if (otherCard) otherCard.style.display = isOther ? '' : 'none';

  if (isOther) {
    // Auto-select the Other payer card
    document.querySelectorAll('.payer-card').forEach(c=>{c.classList.remove('selected');c.querySelector('input[type=radio]').checked=false;});
    otherCard?.classList.add('selected');
    if(otherCard) otherCard.querySelector('input[type=radio]').checked=true;
  } else {
    // Hide other card, auto-select author card matching selected author
    const authId = opt.getAttribute('data-id');
    const authCard = document.getElementById('payerCard_author_'+authId);
    if(authCard){
      document.querySelectorAll('.payer-card').forEach(c=>{c.classList.remove('selected');c.querySelector('input[type=radio]').checked=false;});
      authCard.classList.add('selected');
      authCard.querySelector('input[type=radio]').checked=true;
    }
    document.getElementById('billingEmail').value = email;
    if (affil) {
      document.getElementById('affilInp').value = affil;
      document.getElementById('affilClear').style.display = '';
    }
  }
  dirty();
}

/* ── Affil clear auto-show ─── */
document.getElementById('affilInp').addEventListener('input', function(){
  document.getElementById('affilClear').style.display = this.value ? '' : 'none';
});
// Live-update Other payer name in payer card
['otherFirst','otherLast'].forEach(id=>{
  document.getElementById(id)?.addEventListener('input', ()=>{
    const fn = document.getElementById('otherFirst').value.trim();
    const ln = document.getElementById('otherLast').value.trim();
    const nameEl = document.getElementById('payerOtherName');
    if(nameEl) nameEl.textContent = (fn+' '+ln).trim() || 'Other';
  });
});

/* ── Country searchable dropdown ─── */
function renderCountryOpts(filter){
  const opts = document.getElementById('countryOpts');
  const val  = document.getElementById('countryVal').value;
  const f    = (filter||'').trim().toLowerCase();
  const list = f ? ALL_COUNTRIES.filter(c=>c.toLowerCase().includes(f)) : ALL_COUNTRIES;
  opts.innerHTML = list.map(c =>
    `<div class="country-opt${c===val?' selected':''}" onclick="selectCountry('${pay_xe(c)}')">${xe(c)}</div>`
  ).join('');
}
function toggleCountryList(){
  const list = document.getElementById('countryList');
  countryListOpen = !countryListOpen;
  list.classList.toggle('open', countryListOpen);
  if(countryListOpen){
    document.getElementById('countrySearch').value='';
    renderCountryOpts('');
    document.getElementById('countrySearch').focus();
    // scroll to selected
    setTimeout(()=>{const sel=document.querySelector('.country-opt.selected');if(sel)sel.scrollIntoView({block:'nearest'});},50);
  }
}
function filterCountries(val){
  renderCountryOpts(val);
}
function selectCountry(name){
  document.getElementById('countryDisplay').value = name;
  document.getElementById('countryVal').value = name;
  document.getElementById('countryDisplay').classList.remove('err');
  document.getElementById('countryList').classList.remove('open');
  countryListOpen=false;
  dirty();
}
document.addEventListener('click', e=>{
  if(countryListOpen && !document.getElementById('countryDd').contains(e.target)){
    document.getElementById('countryList').classList.remove('open');
    countryListOpen=false;
  }
});

/* ── Payer selection ─── */
function selectPayer(val, card){
  document.querySelectorAll('.payer-card').forEach(c=>{c.classList.remove('selected');c.querySelector('input[type=radio]').checked=false;});
  card.classList.add('selected');
  card.querySelector('input[type=radio]').checked=true;
  dirty();
}

/* ── Discount codes ─── */
function renderDiscounts(){
  document.getElementById('dtags').innerHTML = discountCodes.map((d,i)=>
    `<span class="dtag">${xe(d)}<button type="button" class="dtag-rm" onclick="removeDiscount(${i})">&#x2715;</button></span>`
  ).join('');
}
function addDiscount(){
  const inp=document.getElementById('discountInp');
  const val=inp.value.trim().toUpperCase();
  if(!val||discountCodes.length>=12)return;
  if(!discountCodes.includes(val)){discountCodes.push(val);renderDiscounts();dirty();}
  inp.value='';
}
function removeDiscount(i){discountCodes.splice(i,1);renderDiscounts();dirty();}
renderDiscounts();

/* ── Validate ─── */
function validate(){
  let ok = true;
  const isOther = document.getElementById('invoiceRcpt').value === 'other';
  const reqIds  = isOther
    ? ['otherFirst','otherLast','otherEmail','phoneNum','address','city','zip']
    : ['billingEmail','phoneNum','address','city','zip'];
  let anyEmpty = false;
  reqIds.forEach(id=>{
    const el=document.getElementById(id);
    if(!el||!el.value.trim()){if(el)el.classList.add('err');anyEmpty=true;ok=false;}
    else el.classList.remove('err');
  });
  // Country
  if(!document.getElementById('countryVal').value){
    document.getElementById('countryDisplay').classList.add('err');
    anyEmpty=true;ok=false;
  } else document.getElementById('countryDisplay').classList.remove('err');
  document.getElementById('mandatoryErr').classList.toggle('show', anyEmpty);

  if(!document.getElementById('feeAgree').checked){
    document.getElementById('agreeErr').classList.add('show');ok=false;
  } else document.getElementById('agreeErr').classList.remove('show');
  return ok;
}
function clearErr(el){el.classList.remove('err');}

/* ── Collect ─── */
function collect(){
  const rcptSel = document.getElementById('invoiceRcpt');
  const rcptOpt = rcptSel.options[rcptSel.selectedIndex];
  const isOther = rcptSel.value === 'other';
  const payer   = document.querySelector('input[name="payer"]:checked')?.value || '';
  return {
    invoice_type:         isOther ? 'other' : 'author',
    invoice_author_id:    isOther ? '' : (rcptOpt.getAttribute('data-id')||''),
    other_first_name:     document.getElementById('otherFirst').value.trim(),
    other_middle_name:    document.getElementById('otherMiddle').value.trim(),
    other_last_name:      document.getElementById('otherLast').value.trim(),
    other_title:          document.getElementById('otherTitle').value,
    other_email:          document.getElementById('otherEmail').value.trim(),
    affiliation:          document.getElementById('affilInp').value.trim(),
    billing_email:        isOther ? document.getElementById('otherEmail').value.trim()
                                  : document.getElementById('billingEmail').value.trim(),
    phone_country_code:   document.getElementById('phoneCode').value,
    phone_number:         document.getElementById('phoneNum').value.trim(),
    address:              document.getElementById('address').value.trim(),
    city:                 document.getElementById('city').value.trim(),
    zip_code:             document.getElementById('zip').value.trim(),
    country_region:       document.getElementById('countryVal').value,
    billing_reference:    document.getElementById('billingRef').value.trim(),
    payer_type:           payer,
    discount_codes:       JSON.stringify(discountCodes),
    fee_agreed:           document.getElementById('feeAgree').checked ? 1 : 0,
  };
}

/* ── Save ─── */
function doSave(silent=false){
  if(!silent && !validate()){
    toast('Please fill all mandatory fields','e');
    document.querySelector('.fi.err')?.scrollIntoView({behavior:'smooth',block:'center'});
    return;
  }
  const btn=document.getElementById('saveBtn');
  if(!silent){btn.disabled=true;btn.innerHTML='<span class="spin"></span>';}
  const fd=new FormData(); fd.append('submission_id',SID); fd.append('data',JSON.stringify(collect()));
  fetch('ajax/save_payment.php',{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
      isDirty=false;
      if(!silent){btn.disabled=false;btn.textContent='Save';}
      if(d.success){
        if(!silent)toast('Saved successfully!','s');
        const data=collect();
        if(data.fee_agreed&&data.address&&data.city&&data.country_region){
          document.getElementById('tileStatus').textContent='✓ Complete';
          document.getElementById('tileStatus').style.color='var(--success)';
          document.getElementById('payTile').style.borderLeftColor='var(--success)';
        }
      } else if(!silent) toast(d.message||'Save failed','e');
    }).catch(()=>{
      if(!silent){btn.disabled=false;btn.textContent='Save';}
      if(!silent)toast('Network error','e');
    });
}
function dirty(){isDirty=true;clearTimeout(autoTimer);autoTimer=setTimeout(()=>doSave(true),2000);}
function toast(msg,t='i'){const w=document.getElementById('toastWrap');const d=document.createElement('div');d.className='toast t'+t;d.innerHTML=(t==='s'?'✅':t==='e'?'❌':'ℹ️')+' '+xe(msg);w.appendChild(d);setTimeout(()=>d.remove(),3500);}
window.addEventListener('beforeunload',e=>{if(isDirty){e.preventDefault();e.returnValue='';}});

// Init tile border color
<?php if($feeAgreed && $address && $city && $country): ?>
document.getElementById('payTile').style.borderLeftColor='var(--success)';
document.getElementById('tileStatus').style.color='var(--success)';
<?php endif; ?>
</script>
</div>