// ─── Services / Hosting Module ──────────────────────────────────────

const Services = {
  async render(app) {
    const res = await app.api('services');
    const services = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>My Services</h1>
        <a href="#hosting" data-nav="hosting" class="btn btn-sm btn-primary"><i class="fas fa-plus"></i> Order New</a>
      </div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead>
              <tr><th>#</th><th>Domain</th><th>Package</th><th>Status</th><th>Date</th><th></th></tr>
            </thead>
            <tbody>
              ${services.length ? services.map(s => `
                <tr>
                  <td>#${s.id}</td>
                  <td>${app.escape(s.domain) || '-'}</td>
                  <td>${app.escape(s.package)}</td>
                  <td><span class="${app.statusClass(s.status)}">${app.statusLabel(s.status)}</span></td>
                  <td>${s.date ? s.date.slice(0,10) : '-'}</td>
                  <td><a href="#service-${s.id}" class="btn btn-sm btn-primary" onclick="Services.detail('${s.id}')">Manage</a></td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No services found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async detail(oid) {
    window.location.hash = `service-${oid}`;
    const app = App;
    app.showLoading();
    const [res, nsRes] = await Promise.all([
      app.api(`services/detail&oid=${oid}`),
      app.api(`domains/info&oid=${oid}`)
    ]);
    if (!res.success) { app.$content.innerHTML = '<div class="empty"><i class="fas fa-server"></i><p>Service not found</p></div>'; return; }
    const s = res.data;
    const ns = nsRes.success ? nsRes.data : { ns1: '', ns2: '' };
    const isAdmin = app.state.user?.role === 'admin';

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>Service #${s.id} — ${app.escape(s.domain)}</h1>
        <a href="#services" data-nav="services" class="btn btn-sm btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
      </div>
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header"><h3>Service Details</h3></div>
            <div class="card-body">
              <p><strong>Package:</strong> ${app.escape(s.package)}</p>
              <p><strong>Domain:</strong> ${app.escape(s.domain) || '-'}</p>
              <p><strong>Status:</strong> <span class="${app.statusClass(s.status)}">${app.statusLabel(s.status)}</span></p>
              <p><strong>Created:</strong> ${s.date ? s.date.slice(0,10) : '-'}</p>
              ${s.username ? `<p><strong>cPanel User:</strong> ${app.escape(s.username)}</p>` : ''}
              ${s.password ? `<p><strong>Password:</strong> <span onclick="this.textContent='${app.escape(s.password)}'" style="cursor:pointer;color:var(--primary)">Click to reveal</span></p>` : ''}
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card">
            <div class="card-header"><h3>Actions</h3></div>
            <div class="card-body" style="display:flex;flex-direction:column;gap:.5rem">
              ${s.status === 1 ? `
                <button class="btn btn-primary btn-block" onclick="Services.ssoLogin(${oid},'cpaneld')"><i class="fas fa-external-link-alt"></i> Login to cPanel</button>
                <button class="btn btn-secondary btn-block" onclick="Services.ssoLogin(${oid},'webmaild')"><i class="fas fa-envelope"></i> Login to Webmail</button>
              ` : ''}
              <a href="#renew-${s.id}" class="btn btn-secondary btn-block" onclick="Services.renew('${s.id}')"><i class="fas fa-sync"></i> Renew</a>
              <a href="#upgrade-${s.id}" class="btn btn-secondary btn-block" onclick="Services.upgrade('${s.id}')"><i class="fas fa-arrow-up"></i> Upgrade</a>
            </div>
          </div>
        </div>
      </div>
      <div class="row mt-4">
        <div class="col-6">
          <div class="card card-flat">
            <div class="card-header"><h3>Billing</h3></div>
            <div class="card-body">
              <p><strong>Amount:</strong> $${s.inv_price}</p>
              <p><strong>Due:</strong> ${s.inv_exdate ? s.inv_exdate.slice(0,10) : '-'}</p>
              <p><strong>Status:</strong> <span class="${app.invClass(s.inv_status)}">${app.invLabel(s.inv_status)}</span></p>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card card-flat">
            <div class="card-header"><h3>Nameservers</h3></div>
            <div class="card-body">
              <p>${app.escape(ns.ns1) || 'ns11.webshineglobal.xyz'}</p>
              <p>${app.escape(ns.ns2) || 'ns12.webshineglobal.xyz'}</p>
              <a href="#domains" data-nav="domains" class="btn btn-sm btn-secondary mt-4">Manage Nameservers</a>
            </div>
          </div>
        </div>
      </div>
      ${isAdmin ? `
      <div class="card">
        <div class="card-header"><h3>Admin Controls</h3></div>
        <div class="card-body">
          <div class="btn-group">
            <button class="btn btn-success btn-sm" onclick="Services.adminAction(${oid},'unsuspend')">Unsuspend</button>
            <button class="btn btn-danger btn-sm" onclick="Services.adminAction(${oid},'suspend')">Suspend</button>
            <button class="btn btn-secondary btn-sm" onclick="Services.adminAction(${oid},'provision')">Provision Account</button>
            <button class="btn btn-secondary btn-sm" onclick="Services.adminAction(${oid},'sendDetails')">Send Details Email</button>
            <button class="btn btn-warning btn-sm" onclick="Services.deleteService(${oid},'${s.iid}')">Delete</button>
          </div>
        </div>
      </div>` : ''}
      <div class="card card-flat mt-4">
        <div class="card-header"><h3>Renew Service #${oid}</h3></div>
        <div class="card-body">
          <form id="renew-form" class="flex-center gap-2">
            <select name="pk" class="form-control" style="max-width:220px">
              <option value="m${s.package?.slice(1)}">${s.fmonth ? `${s.fmonth} Month${s.fmonth > 1 ? 's' : ''} — $${Number(s.fprice).toFixed(2)}` : `Renew — $${s.inv_price}`}</option>
              <option value="y${s.package?.slice(1)}">${s.yprice ? `12 Months (1 Year) — $${Number(s.yprice).toFixed(2)}` : '12 Months (1 Year)'}</option>
            </select>
            <button type="submit" class="btn btn-primary btn-sm">Generate Invoice</button>
          </form>
        </div>
      </div>
    `;
    document.getElementById('renew-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const r = await app.api('services/renew', 'POST', { oid, pk: fd.get('pk') });
      if (r.success) { app.showMessage('Renewal invoice created!', 'success'); app.navigate(`invoice-${r.data.iid}`); }
      else app.showMessage(r.message || 'Could not create renewal invoice.', 'danger');
    };
  },

  async renew(oid) { Services.detail(oid); },

  async ssoLogin(oid, target) {
    const app = App;
    const r = await app.api(`hosting/sso&oid=${oid}&target=${target}`);
    if (r.success && r.data.url) window.open(r.data.url, '_blank');
    else app.showMessage(r.message || 'Could not start SSO session.', 'danger');
  },

  async adminAction(oid, action) {
    const app = App;
    const labels = { suspend: 'Suspend this account?', unsuspend: 'Unsuspend this account?', provision: 'Provision the hosting account now?', sendDetails: 'Email account details to the customer?' };
    const routes = { suspend: 'hosting/suspend', unsuspend: 'hosting/unsuspend', provision: 'hosting/provision', sendDetails: 'hosting/send-details' };
    if (labels[action] && !confirm(labels[action])) return;
    const method = (action === 'provision' || action === 'sendDetails') ? 'POST' : 'GET';
    const r = await app.api(`${routes[action]}&oid=${oid}`, method, method === 'POST' ? { oid } : null);
    app.showMessage(r.message || (r.success ? 'Done.' : 'Failed.'), r.success ? 'success' : 'danger');
    if (r.success) Services.detail(oid);
  },

  async deleteService(oid, iid) {
    const app = App;
    if (!confirm('Delete this service and its invoice? This can be restored later from the Delete View.')) return;
    const r = await app.api('services/delete', 'POST', { oid, iid, sta: '' });
    app.showMessage(r.message || 'Done.', r.success ? 'success' : 'danger');
    if (r.success) app.navigate('services');
  },

  async upgrade(oid) {
    const app = App;
    app.showLoading();
    const detailRes = await app.api(`services/detail&oid=${oid}`);
    if (!detailRes.success) { app.$content.innerHTML = '<div class="empty"><p>Service not found</p></div>'; return; }
    const s = detailRes.data;

    const prodRes = await app.api('products');
    const products = prodRes.success && prodRes.data ? prodRes.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>Upgrade Service #${oid}</h1>
        <a href="#service-${oid}" class="btn btn-sm btn-secondary" onclick="Services.detail(${oid}); return false;">Back</a>
      </div>
      <div class="card">
        <div class="card-body">
          <p style="color:var(--gray-500);margin-bottom:1rem">Current plan: <strong>${app.escape(s.package)}</strong> — an invoice for the price difference will be generated.</p>
          <form id="upgrade-form">
            <div class="form-group">
              <label>New Plan</label>
              <select name="ph" class="form-control" required>
                ${products.map(p => `<option value="m${p.id}">${app.escape(p.name)} — ${p.fmonth} Month${p.fmonth > 1 ? 's' : ''} ($${Number(p.fprice).toFixed(2)})</option><option value="y${p.id}">${app.escape(p.name)} — 12 Months / 1 Year ($${Number(p.yprice).toFixed(2)})</option>`).join('')}
              </select>
            </div>
            <button type="submit" class="btn btn-primary">Request Upgrade</button>
          </form>
        </div>
      </div>
    `;

    document.getElementById('upgrade-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const r = await app.api('services/upgrade', 'POST', { oid, opk: s.package, ph: fd.get('ph') });
      if (r.success) { app.showMessage(r.message, 'success'); app.navigate(`invoice-${r.data.iid}`); }
      else app.showMessage(r.message || 'Upgrade failed.', 'danger');
    };
  }
};

// ─── Checkout ────────────────────────────────────────────────────────
// Hash format: checkout-<pid>, e.g. checkout-7 — billing cycle is chosen ON
// this page (every plan has exactly two real options: its own minimum cycle
// at fmonth months for fprice, or annual at 12 months for yprice; fmonth is
// NOT always 1 — e.g. a plan can require a minimum 3- or 6-month term).

const Checkout = {
  tlds: [],
  plan: null,
  available: null, // tri-state: null = not checked yet, true/false = last check result
  buyPrice: 0,      // resolved price for the 'buy' (any-TLD) option, set by checkAvailability()

  async render(pid) {
    const app = App;
    app.showLoading();

    const [res, tldRes] = await Promise.all([
      app.api(`orders/cart&pid=${pid}`),
      app.api('domains/tlds')
    ]);
    if (!res.success) { app.$content.innerHTML = '<div class="empty"><i class="fas fa-exclamation-triangle"></i><p>Plan not found.</p></div>'; return; }
    const p = res.data;
    Checkout.plan = p;
    Checkout.tlds = tldRes.success && tldRes.data ? tldRes.data.items || [] : [];

    const cycleLabel = `${p.fmonth} Month${p.fmonth > 1 ? 's' : ''} — $${p.fprice.toFixed(2)}`;
    const yearLabel = `12 Months (1 Year) — $${p.yprice.toFixed(2)}`;

    app.$content.innerHTML = `
      <div class="page-header"><h1>Order — ${app.escape(p.name)}</h1></div>
      <div class="card mb-4">
        <div class="card-header"><h3>Billing Cycle</h3></div>
        <div class="card-body">
          <select id="term-select" class="form-control" style="max-width:320px">
            <option value="m">${cycleLabel}</option>
            <option value="y">${yearLabel}</option>
          </select>
        </div>
      </div>
      <div class="row">
        <div class="col-6">
          <div class="card">
            <div class="card-header"><h3>Domain & Coupon</h3></div>
            <div class="card-body">
              <form id="checkout-form">
                <div class="form-group">
                  <label>Domain</label>
                  <div style="display:flex;flex-direction:column;gap:.5rem;margin-bottom:.75rem">
                    <label style="display:flex;align-items:center;gap:.5rem;font-weight:400">
                      <input type="radio" name="domain_action" value="own" checked> I'll use my own domain (already registered)
                    </label>
                    <label style="display:flex;align-items:center;gap:.5rem;font-weight:400">
                      <input type="radio" name="domain_action" value="free"> Get a free domain with this plan
                    </label>
                    <label style="display:flex;align-items:center;gap:.5rem;font-weight:400">
                      <input type="radio" name="domain_action" value="buy"> Register a new domain
                    </label>
                  </div>
                  <div id="domain-fields"></div>
                </div>
                <div class="form-group">
                  <label>Coupon Code (optional)</label>
                  <div style="display:flex;gap:.5rem">
                    <input type="text" name="coupon" id="coupon-input" class="form-control">
                    <button type="button" class="btn btn-secondary" onclick="Checkout.applyCoupon(${pid})">Apply</button>
                  </div>
                  <small id="coupon-msg"></small>
                </div>
                <button type="submit" class="btn btn-primary btn-block" id="place-order-btn">Place Order</button>
              </form>
            </div>
          </div>
        </div>
        <div class="col-6">
          <div class="card card-flat">
            <div class="card-header"><h3>Order Summary</h3></div>
            <div class="card-body">
              <p><strong>Plan:</strong> ${app.escape(p.name)}</p>
              <p><strong>Billing Term:</strong> <span id="term-label">${cycleLabel}</span></p>
              <p><strong>Plan Price:</strong> <span id="plan-price" data-base="${p.fprice}">$${p.fprice.toFixed(2)}</span></p>
              <p><strong>Domain:</strong> <span id="domain-price">$0.00</span></p>
              <p style="border-top:1px solid var(--gray-200);padding-top:.5rem;margin-top:.5rem"><strong>Total:</strong> <span id="checkout-total">$${p.fprice.toFixed(2)}</span></p>
            </div>
          </div>
        </div>
      </div>
    `;

    Checkout.renderDomainFields('own');

    document.getElementById('term-select').addEventListener('change', () => {
      document.getElementById('coupon-input').value = '';
      document.getElementById('coupon-msg').textContent = '';
      Checkout.updatePlanPrice();
    });

    document.querySelectorAll('input[name="domain_action"]').forEach(radio => {
      radio.addEventListener('change', (e) => Checkout.renderDomainFields(e.target.value));
    });

    document.getElementById('checkout-form').onsubmit = async (e) => {
      e.preventDefault();
      const term = document.getElementById('term-select').value;
      const action = document.querySelector('input[name="domain_action"]:checked').value;
      const data = { pid, term, coupon: document.getElementById('coupon-input')?.value || '', domain_action: action };
      if (action === 'own') {
        data.domain = document.querySelector('[name="domain"]')?.value || '';
      } else if (action === 'buy') {
        if (Checkout.available !== true) { app.showMessage('Please check domain availability first.', 'danger'); return; }
        data.domain = document.getElementById('buy-domain')?.value || '';
      } else {
        if (Checkout.available !== true) { app.showMessage('Please check domain availability first.', 'danger'); return; }
        data.domain_name = document.getElementById('domain-name')?.value || '';
        data.tld_id = document.getElementById('tld-select')?.value || '';
      }
      const r = await app.api('orders/checkout', 'POST', data);
      if (r.success) { app.showMessage(r.message, 'success'); app.navigate(`invoice-${r.data.iid}`); }
      else app.showMessage(r.message || 'Could not place order.', 'danger');
    };
  },

  updatePlanPrice() {
    const term = document.getElementById('term-select')?.value || 'm';
    const p = Checkout.plan;
    const price = term === 'y' ? p.yprice : p.fprice;
    const label = term === 'y'
      ? `12 Months (1 Year) — $${p.yprice.toFixed(2)}`
      : `${p.fmonth} Month${p.fmonth > 1 ? 's' : ''} — $${p.fprice.toFixed(2)}`;

    document.getElementById('term-label').textContent = label;
    const priceEl = document.getElementById('plan-price');
    priceEl.dataset.base = price;
    priceEl.textContent = '$' + price.toFixed(2);
    Checkout.updateDomainPricing();
  },

  renderDomainFields(action) {
    const app = App;
    const box = document.getElementById('domain-fields');
    if (!box) return;
    Checkout.available = null;
    Checkout.buyPrice = 0;

    if (action === 'own') {
      box.innerHTML = `
        <input type="text" name="domain" class="form-control" placeholder="yourdomain.com" required>
        <small style="color:var(--gray-500)">You'll point its nameservers to us after checkout.</small>
      `;
    } else if (action === 'buy') {
      // Any TLD is allowed here — priced by the registrar's rate for that TLD (or the
      // admin's default rate), resolved server-side when you check availability.
      box.innerHTML = `
        <div style="display:flex;gap:.5rem">
          <input type="text" id="buy-domain" class="form-control" placeholder="yourdomain.com" required>
          <button type="button" class="btn btn-secondary" onclick="Checkout.checkAvailability()">Check</button>
        </div>
        <small id="availability-msg" style="color:var(--gray-500)">Any extension — check availability to see the price and place your order.</small>
      `;
      document.getElementById('buy-domain')?.addEventListener('input', () => Checkout.resetAvailability());
    } else {
      // 'free' — name+TLD from the admin-curated allow-list. Whether it actually comes
      // out free depends on its live shopped price vs. the threshold, checked below.
      const list = Checkout.tlds;
      box.innerHTML = `
        <div style="display:flex;gap:.5rem">
          <input type="text" id="domain-name" class="form-control" placeholder="yourdomain" required>
          <select id="tld-select" class="form-control" style="max-width:150px">
            ${list.length ? list.map(t => `<option value="${t.id}">.${app.escape(t.tld)}</option>`).join('')
                          : '<option value="">No extensions available</option>'}
          </select>
          <button type="button" class="btn btn-secondary" onclick="Checkout.checkAvailability()">Check</button>
        </div>
        <small id="availability-msg" style="color:var(--gray-500)">Only extensions on our free-domain allow-list are shown.</small>
      `;
      document.getElementById('domain-name')?.addEventListener('input', () => Checkout.resetAvailability());
      document.getElementById('tld-select')?.addEventListener('change', () => Checkout.resetAvailability());
    }
    Checkout.updateDomainPricing();
    Checkout.updatePlaceOrderState();
  },

  resetAvailability() {
    Checkout.available = null;
    Checkout.buyPrice = 0;
    const msg = document.getElementById('availability-msg');
    if (msg) msg.textContent = 'Check availability, then place your order.';
    Checkout.updateDomainPricing();
    Checkout.updatePlaceOrderState();
  },

  async checkAvailability() {
    const app = App;
    const action = document.querySelector('input[name="domain_action"]:checked')?.value;
    const msg = document.getElementById('availability-msg');

    let domain = '';
    if (action === 'buy') {
      domain = document.getElementById('buy-domain')?.value.trim().toLowerCase();
    } else {
      const name = document.getElementById('domain-name')?.value.trim();
      const tld = Checkout.tlds.find(t => String(t.id) === document.getElementById('tld-select')?.value);
      if (name && tld) domain = `${name}.${tld.tld}`;
    }
    if (!domain) {
      if (msg) { msg.textContent = 'Enter a domain name first.'; msg.style.color = 'var(--danger)'; }
      return;
    }

    if (msg) { msg.textContent = 'Checking availability...'; msg.style.color = 'var(--gray-500)'; }

    const r = await app.api(`domains/check&domain=${encodeURIComponent(domain)}`);
    Checkout.available = r.success ? r.data.available : null;
    Checkout.buyPrice = r.success ? (r.data.price || 0) : 0;
    if (msg) {
      msg.textContent = r.message || '';
      msg.style.color = Checkout.available === false ? 'var(--danger)' : (Checkout.available === true ? 'var(--success)' : 'var(--gray-500)');
    }
    Checkout.updateDomainPricing();
    Checkout.updatePlaceOrderState();
  },

  updatePlaceOrderState() {
    const action = document.querySelector('input[name="domain_action"]:checked')?.value || 'own';
    const btn = document.getElementById('place-order-btn');
    if (!btn) return;
    if (action === 'own') { btn.disabled = false; btn.title = ''; return; }
    btn.disabled = Checkout.available !== true;
    btn.title = btn.disabled ? 'Check domain availability first' : '';
  },

  updateDomainPricing() {
    const selected = document.querySelector('input[name="domain_action"]:checked')?.value || 'own';
    const domainPrice = selected === 'buy' ? (Checkout.buyPrice || 0) : 0;
    document.getElementById('domain-price').textContent = '$' + domainPrice.toFixed(2);

    const planPrice = parseFloat(document.getElementById('plan-price').textContent.replace('$', '')) || 0;
    document.getElementById('checkout-total').textContent = '$' + (planPrice + domainPrice).toFixed(2);
  },

  async applyCoupon(pid) {
    const app = App;
    const term = document.getElementById('term-select')?.value || 'm';
    const code = document.getElementById('coupon-input').value.trim();
    const msg = document.getElementById('coupon-msg');
    if (!code) return;
    const r = await app.api(`orders/coupon&code=${encodeURIComponent(code)}&pid=${pid}&term=${term}`);
    msg.textContent = r.message || '';
    msg.style.color = r.success ? 'var(--success)' : 'var(--danger)';
    if (r.success) {
      document.getElementById('plan-price').textContent = '$' + Number(r.data.discounted_price).toFixed(2);
      Checkout.updateDomainPricing();
    }
  },

  start(pid) {
    App.navigate(`checkout-${pid}`);
  }
};