<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('Settings')}"></head>
<body>
<nav th:replace="~{fragments/layout :: adminbar}"></nav>

<section class="dash">
    <div class="container">
        <div class="settings-page">

            <div class="page-head">
                <h1>Settings</h1>
                <p>Manage your organization profile, billing defaults and master data.</p>
            </div>

            <div class="settings-layout">
                <!-- Sidebar nav -->
                <aside class="settings-nav">
                    <button class="settings-nav-item active" data-sec="org" type="button" onclick="settingsTab('org')">
                        <span class="ic">&#127970;</span> Organization
                    </button>
                    <button class="settings-nav-item" data-sec="billing" type="button" onclick="settingsTab('billing')">
                        <span class="ic">&#128178;</span> Billing &amp; Tax
                    </button>
                    <button class="settings-nav-item" data-sec="notify" type="button" onclick="settingsTab('notify')">
                        <span class="ic">&#128231;</span> Notifications
                    </button>
                    <a class="settings-nav-item" th:href="@{/admin/settings/categories}">
                        <span class="ic">&#127991;</span> Categories
                    </a>
                </aside>

                <!-- Content -->
                <div class="settings-content">

            <!-- Organization -->
            <div class="settings-sec" id="sec-org">
            <div class="settings-card">
                <div class="settings-card-head">
                    <span class="ic">&#127970;</span>
                    <div>
                        <h2>Organization profile</h2>
                        <p>Company identity &amp; branding shown across the app and on documents.</p>
                    </div>
                </div>
                <form id="orgForm" onsubmit="return false">
                    <div class="settings-card-body">
                        <div class="form-grid2">
                            <div class="form-group field"><label>Name</label>
                                <input type="text" id="o_name" th:value="${organization.name}"/></div>
                            <div class="form-group field"><label>Legal Name</label>
                                <input type="text" id="o_legalName" th:value="${organization.legalName}"/></div>
                            <div class="form-group field"><label>GST Number</label>
                                <input type="text" id="o_gstNumber" th:value="${organization.gstNumber}"/></div>
                            <div class="form-group field"><label>Phone</label>
                                <input type="text" id="o_phone" th:value="${organization.phone}"/></div>
                            <div class="form-group field"><label>Contact Email</label>
                                <input type="email" id="o_contactEmail" th:value="${organization.contactEmail}"/></div>
                            <div class="form-group field"><label>Currency Code</label>
                                <input type="text" id="o_currencyCode" th:value="${organization.currencyCode}" maxlength="3"/></div>
                            <div class="form-group field" style="grid-column:1 / -1"><label>Address</label>
                                <input type="text" id="o_address" th:value="${organization.address}"/></div>
                            <div class="form-group field" style="grid-column:1 / -1"><label>Logo URL</label>
                                <input type="text" id="o_logoUrl" th:value="${organization.logoUrl}" placeholder="/images/logo.png"/></div>
                        </div>
                    </div>
                    <div class="settings-card-foot">
                        <span class="hint">Shown on invoices, settlement statements &amp; the public site.</span>
                        <button class="btn btn-primary btn-sm" id="orgBtn" type="button" onclick="saveOrg()">Save organization</button>
                    </div>
                </form>
            </div>
            </div><!-- /sec-org -->

            <!-- Billing & configuration -->
            <div class="settings-sec" id="sec-billing" style="display:none">
            <div class="settings-card">
                <div class="settings-card-head">
                    <span class="ic blue">&#128178;</span>
                    <div>
                        <h2>Billing &amp; tax defaults</h2>
                        <p>Currency, tax, commission, driver charges and the settlement cycle.</p>
                    </div>
                </div>
                <form id="cfgForm" onsubmit="return false">
                    <div class="settings-card-body">
                        <div class="form-grid2">
                            <div class="form-group field"><label>Currency Code</label>
                                <input type="text" id="c_currencyCode" th:value="${config.currencyCode}" maxlength="3"/></div>
                            <div class="form-group field"><label>Invoice Prefix</label>
                                <input type="text" id="c_invoicePrefix" th:value="${config.invoicePrefix}"/></div>
                            <div class="form-group field"><label>Default Tax %</label>
                                <input type="number" step="0.01" id="c_defaultTaxPercent" th:value="${config.defaultTaxPercent}"/></div>
                            <div class="form-group field"><label>Default Commission %</label>
                                <input type="number" step="0.01" id="c_defaultCommissionPercent" th:value="${config.defaultCommissionPercent}"/></div>
                            <div class="form-group field"><label>Default Driver Daily Charge</label>
                                <input type="number" step="0.01" id="c_defaultDriverDailyCharge" th:value="${config.defaultDriverDailyCharge}"/></div>
                            <div class="form-group field"><label>Settlement Cycle</label>
                                <select id="c_settlementCycle">
                                    <option th:each="cyc : ${T(com.mvrent.carrental.model.SettlementCycle).values()}"
                                            th:value="${cyc}" th:text="${cyc}" th:selected="${config.settlementCycle == cyc}"></option>
                                </select></div>
                        </div>
                    </div>
                    <div class="settings-card-foot">
                        <span class="hint">Applied to new bookings, invoices &amp; vendor settlements.</span>
                        <button class="btn btn-primary btn-sm" id="cfgBtn" type="button" onclick="saveCfg()">Save configuration</button>
                    </div>
                </form>
            </div>
            </div><!-- /sec-billing -->

            <!-- Notifications -->
            <div class="settings-sec" id="sec-notify" style="display:none">
            <div class="settings-card">
                <div class="settings-card-head">
                    <span class="ic blue">&#128231;</span>
                    <div>
                        <h2>Notifications</h2>
                        <p>Email &amp; SMS alerts for booking confirmations and status updates.</p>
                    </div>
                </div>
                <div class="settings-card-body">
                    <div class="info-row">
                        <span class="k">Email (SMTP)</span>
                        <span class="v">
                            <span class="badge" th:classappend="${mailReady} ? 'badge-confirmed' : 'badge-cancelled'"
                                  th:text="${mailReady} ? 'CONFIGURED' : 'NOT CONFIGURED'">NOT CONFIGURED</span>
                        </span>
                    </div>
                    <div class="info-row">
                        <span class="k">SMS gateway</span>
                        <span class="v">
                            <span class="badge" th:classappend="${smsEnabled} ? 'badge-confirmed' : 'badge-cancelled'"
                                  th:text="${smsEnabled} ? 'ENABLED' : 'DISABLED (logs only)'">DISABLED</span>
                        </span>
                    </div>
                    <p class="hint" style="margin:12px 0 4px" th:unless="${mailReady}">
                        Set <code>MAIL_HOST</code>, <code>MAIL_USERNAME</code>, <code>MAIL_PASSWORD</code> and
                        <code>MAIL_ENABLED=true</code> (env vars) to enable email. Until then, messages are logged only.
                    </p>

                    <div class="media-add" style="margin-top:14px">
                        <h5>Send a test email</h5>
                        <div style="display:flex;gap:10px;align-items:end;flex-wrap:wrap">
                            <div class="form-group field" style="flex:1;min-width:220px;margin:0">
                                <label>Recipient</label>
                                <input type="email" id="testEmail" th:value="${adminEmail}" placeholder="you@example.com"/>
                            </div>
                            <button class="btn btn-primary btn-sm" id="testBtn" type="button" onclick="sendTest()">Send test</button>
                        </div>
                    </div>
                </div>
            </div>
            </div><!-- /sec-notify -->

                </div><!-- /settings-content -->
            </div><!-- /settings-layout -->

        </div>
    </div>
</section>

<div class="toast-wrap" id="toasts"></div>

<script th:inline="javascript">
/*<![CDATA[*/
const CSRF_TOKEN  = /*[[${_csrf.token}]]*/ '';
const CSRF_HEADER = /*[[${_csrf.headerName}]]*/ 'X-CSRF-TOKEN';
/*]]>*/
</script>
<script>
function settingsTab(sec){
  document.getElementById('sec-org').style.display     = sec==='org'     ? '' : 'none';
  document.getElementById('sec-billing').style.display = sec==='billing' ? '' : 'none';
  document.getElementById('sec-notify').style.display  = sec==='notify'  ? '' : 'none';
  document.querySelectorAll('.settings-nav-item[data-sec]').forEach(b=>b.classList.toggle('active', b.dataset.sec===sec));
}
function sendTest(){
  const to=document.getElementById('testEmail').value.trim();
  if(!to) return toast('Enter a recipient email','err');
  const b=document.getElementById('testBtn'); b.disabled=true; b.textContent='Sending…';
  const h={}; h[CSRF_HEADER]=CSRF_TOKEN;
  fetch('/admin/settings/test-email?to='+encodeURIComponent(to),{method:'POST',headers:h})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok) toast('Test email sent','ok'); else toast((res.body&&res.body.message)||'Send failed','err'); })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{ b.disabled=false; b.textContent='Send test'; });
}
function val(id){ const v=document.getElementById(id).value.trim(); return v===''?null:v; }
function num(id){ const v=document.getElementById(id).value; return v===''?null:Number(v); }
function headers(){ const h={'Content-Type':'application/json'}; h[CSRF_HEADER]=CSRF_TOKEN; return h; }

function post(url, payload, btn, okMsg){
  const b=document.getElementById(btn); const txt=b.textContent; b.disabled=true; b.textContent='Saving…';
  fetch(url,{method:'POST',headers:headers(),body:JSON.stringify(payload)})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok) toast(okMsg,'ok'); else toast((res.body&&res.body.message)||'Could not save','err'); })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{ b.disabled=false; b.textContent=txt; });
}
function saveOrg(){
  post('/admin/api/settings/organization', {
    name:val('o_name'), legalName:val('o_legalName'), gstNumber:val('o_gstNumber'),
    address:val('o_address'), contactEmail:val('o_contactEmail'), phone:val('o_phone'),
    logoUrl:val('o_logoUrl'), currencyCode:val('o_currencyCode')
  }, 'orgBtn', 'Organization saved');
}
function saveCfg(){
  post('/admin/api/settings/config', {
    currencyCode:val('c_currencyCode'), defaultTaxPercent:num('c_defaultTaxPercent'),
    defaultCommissionPercent:num('c_defaultCommissionPercent'), defaultDriverDailyCharge:num('c_defaultDriverDailyCharge'),
    invoicePrefix:val('c_invoicePrefix'), settlementCycle:document.getElementById('c_settlementCycle').value
  }, 'cfgBtn', 'Configuration saved');
}
function toast(msg,kind){ const t=document.createElement('div'); t.className='toast '+(kind||'ok'); t.textContent=msg;
  document.getElementById('toasts').appendChild(t);
  setTimeout(()=>{t.style.opacity='0';t.style.transition='opacity .3s';setTimeout(()=>t.remove(),300);},2600); }
</script>

<footer th:replace="~{fragments/layout :: footer}"></footer>
</body>
</html>
