<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>
<h5 class="mb-3">Platform Settings</h5>

<div class="li-card mb-3">
    <div class="li-card-header">General</div>
    <div class="li-card-body">
        <div class="mb-2"><label class="form-label">App Name</label><input type="text" id="s_app_name" class="form-control"></div>
        <div class="mb-2"><label class="form-label">Default Currency</label><input type="text" id="s_default_currency" class="form-control"></div>
        <button class="btn btn-li-primary btn-sm" onclick="saveGroup('general', ['app_name','default_currency'])">Save</button>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Payment</div>
    <div class="li-card-body">
        <div class="mb-2"><label class="form-label">Tax Percentage (%)</label><input type="number" id="s_tax_percentage" class="form-control"></div>
        <button class="btn btn-li-primary btn-sm" onclick="saveGroup('payment', ['tax_percentage'])">Save</button>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Public Profiles &amp; Registration</div>
    <div class="li-card-body">
        <div class="mb-2"><label class="form-label">Daily Contact View Limit (per account)</label><input type="number" id="s_daily_contact_view_limit" class="form-control"></div>
        <div class="mb-2"><label class="form-label">Username Changes Allowed</label><input type="number" id="s_username_change_limit" class="form-control"></div>
        <div class="mb-2"><label class="form-label">Per (days)</label><input type="number" id="s_username_change_period_days" class="form-control"></div>
        <div class="form-check mb-2">
            <input type="checkbox" class="form-check-input" id="s_require_otp_verification">
            <label class="form-check-label" for="s_require_otp_verification">Require email + mobile OTP verification at signup</label>
            <div class="form-text">Leave off until you've configured a working SMS gateway (Settings has no SMS section yet — set <code>sms.apiUrl</code>/<code>sms.apiKey</code> in .env) and confirmed outgoing email works, or new accounts may get stuck unable to verify.</div>
        </div>
        <button class="btn btn-li-primary btn-sm" onclick="saveGroup('profile', ['daily_contact_view_limit','username_change_limit','username_change_period_days'])">Save</button>
        <button class="btn btn-li-outline btn-sm" onclick="saveOtpToggle()">Save Verification Setting</button>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Credit Costs</div>
    <div class="li-card-body">
        <p class="text-muted small">How many credits each action costs an agency. Changes apply immediately platform-wide.</p>
        <div id="creditCostsList"></div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">SMTP (Outgoing Email)</div>
    <div class="li-card-body">
        <p class="text-muted small">Configure this to control outgoing email site-wide without touching server files. Leave blank to keep using the server's default mail configuration from installation.</p>
        <div class="row g-2">
            <div class="col-md-8"><label class="form-label">SMTP Host</label><input type="text" id="s_smtp_host" class="form-control" placeholder="smtp.mailgun.org"></div>
            <div class="col-md-4"><label class="form-label">Port</label><input type="text" id="s_smtp_port" class="form-control" placeholder="587"></div>
            <div class="col-md-6"><label class="form-label">Username</label><input type="text" id="s_smtp_username" class="form-control"></div>
            <div class="col-md-6"><label class="form-label">Password</label><input type="password" id="s_smtp_password" class="form-control" placeholder="Leave blank to keep current"></div>
            <div class="col-md-4">
                <label class="form-label">Encryption</label>
                <select id="s_smtp_encryption" class="form-select">
                    <option value="tls">TLS</option>
                    <option value="ssl">SSL</option>
                </select>
            </div>
            <div class="col-md-4"><label class="form-label">From Name</label><input type="text" id="s_smtp_from_name" class="form-control" placeholder="Job Portal"></div>
            <div class="col-md-4"><label class="form-label">From Email</label><input type="email" id="s_smtp_from_email" class="form-control"></div>
        </div>
        <div class="d-flex gap-2 mt-2">
            <button class="btn btn-li-primary btn-sm" onclick="saveSmtp()">Save</button>
            <button class="btn btn-li-outline btn-sm" onclick="testSmtp()">Send Test Email</button>
        </div>
        <div id="smtpTestResult" class="mt-2"></div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Notifications</div>
    <div class="li-card-body">
        <div class="form-check">
            <input type="checkbox" class="form-check-input" id="s_whatsapp_enabled">
            <label class="form-check-label" for="s_whatsapp_enabled">Enable WhatsApp notifications</label>
        </div>
        <button class="btn btn-li-primary btn-sm mt-2" onclick="saveWhatsapp()">Save</button>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">System Update</div>
    <div class="li-card-body">
        <p class="text-muted small">Upload a <code>.zip</code> containing an updated <code>app/</code> and/or <code>public/</code> folder to apply a new version — no FTP or hosting file manager needed. A full backup of the current files is taken automatically before anything is changed, and can be restored with one click from the history below if something goes wrong.</p>
        <div class="alert alert-warning small">
            <i class="bi bi-exclamation-triangle me-1"></i>
            Only <code>app/</code> and <code>public/</code> can be updated this way — the package is rejected if it contains anything else (this protects the framework core and your database credentials). Run any new database migrations separately via <code>php spark migrate</code> after applying.
        </div>

        <input type="file" id="updateFile" accept=".zip" class="form-control mb-2">
        <button class="btn btn-li-primary btn-sm" id="uploadUpdateBtn" onclick="uploadUpdate()"><i class="bi bi-cloud-upload me-1"></i>Upload &amp; Apply Update</button>
        <div id="updateProgress" class="text-muted small mt-2 d-none">Uploading and applying — this may take a moment for larger packages...</div>

        <hr>
        <h6 class="mb-2">Update History</h6>
        <div id="updateHistoryBody">Loading...</div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
async function loadSettings() {
    try {
        const res = await apiFetch('/settings');
        const s = res.data;
        if (s.general) {
            document.getElementById('s_app_name').value = s.general.app_name || '';
            document.getElementById('s_default_currency').value = s.general.default_currency || '';
        }
        if (s.payment) document.getElementById('s_tax_percentage').value = s.payment.tax_percentage || 0;
        if (s.notification) document.getElementById('s_whatsapp_enabled').checked = s.notification.whatsapp_enabled === '1';
        if (s.profile) {
            document.getElementById('s_daily_contact_view_limit').value = s.profile.daily_contact_view_limit || 10;
            document.getElementById('s_username_change_limit').value = s.profile.username_change_limit || 3;
            document.getElementById('s_username_change_period_days').value = s.profile.username_change_period_days || 30;
            document.getElementById('s_require_otp_verification').checked = s.profile.require_otp_verification === '1';
        }
        if (s.smtp) {
            document.getElementById('s_smtp_host').value = s.smtp.host || '';
            document.getElementById('s_smtp_port').value = s.smtp.port || '587';
            document.getElementById('s_smtp_username').value = s.smtp.username || '';
            // Password intentionally left blank on load — never re-display a
            // saved secret in the browser. The placeholder communicates
            // that leaving it blank on save keeps the existing value.
            document.getElementById('s_smtp_encryption').value = s.smtp.encryption || 'tls';
            document.getElementById('s_smtp_from_name').value = s.smtp.from_name || '';
            document.getElementById('s_smtp_from_email').value = s.smtp.from_email || '';
        }
    } catch (e) { showToast(e.message, true); }

    try {
        const cc = await apiFetch('/settings/credit-costs');
        document.getElementById('creditCostsList').innerHTML = (cc.data || []).map(c => `
            <div class="row g-2 align-items-center mb-2">
                <div class="col-6"><span class="text-muted small">${c.action.replace(/_/g,' ')}</span></div>
                <div class="col-4"><input type="number" min="0" class="form-control form-control-sm" id="cc_${c.action}" value="${c.credit_cost}"></div>
                <div class="col-2"><button class="btn btn-li-outline btn-sm" onclick="saveCreditCost('${c.action}')">Save</button></div>
            </div>
        `).join('');
    } catch (e) { showToast(e.message, true); }
}

async function saveSmtp() {
    const payload = {
        host: document.getElementById('s_smtp_host').value,
        port: document.getElementById('s_smtp_port').value,
        username: document.getElementById('s_smtp_username').value,
        encryption: document.getElementById('s_smtp_encryption').value,
        from_name: document.getElementById('s_smtp_from_name').value,
        from_email: document.getElementById('s_smtp_from_email').value,
    };
    // Only send the password if the admin actually typed a new one —
    // otherwise omit it entirely so the existing saved value is untouched.
    const pw = document.getElementById('s_smtp_password').value;
    if (pw) payload.password = pw;

    try {
        await apiFetch('/settings/smtp', { method: 'PUT', body: JSON.stringify(payload) });
        showToast('SMTP settings saved.');
        document.getElementById('s_smtp_password').value = '';
    } catch (e) { showToast(e.message, true); }
}

async function testSmtp() {
    const resultEl = document.getElementById('smtpTestResult');
    resultEl.innerHTML = '<span class="text-muted small">Sending...</span>';
    try {
        await saveSmtp(); // ensure the test uses whatever's currently in the form
        const to = document.getElementById('s_smtp_from_email').value;
        if (!to) { resultEl.innerHTML = '<span class="text-danger small">Set a From Email first.</span>'; return; }
        await apiFetch('/settings/smtp/test', { method: 'POST', body: JSON.stringify({ to }) });
        resultEl.innerHTML = '<span class="text-success small">Test email sent — check the inbox.</span>';
    } catch (e) {
        resultEl.innerHTML = `<span class="text-danger small">${escapeHtml(e.message)}</span>`;
    }
}

async function saveOtpToggle() {
    try {
        await apiFetch('/settings/profile', {
            method: 'PUT',
            body: JSON.stringify({ require_otp_verification: document.getElementById('s_require_otp_verification').checked ? '1' : '0' }),
        });
        showToast('Verification setting saved.');
    } catch (e) { showToast(e.message, true); }
}

async function saveCreditCost(action) {
    const value = document.getElementById('cc_' + action).value;
    try {
        await apiFetch(`/settings/credit-costs/${action}`, { method: 'PUT', body: JSON.stringify({ credit_cost: parseInt(value) }) });
        showToast('Credit cost updated.');
    } catch (e) { showToast(e.message, true); }
}

async function saveGroup(group, keys) {
    const payload = {};
    keys.forEach(k => payload[k] = document.getElementById('s_' + k).value);
    try {
        await apiFetch(`/settings/${group}`, { method: 'PUT', body: JSON.stringify(payload) });
        showToast('Settings saved.');
    } catch (e) { showToast(e.message, true); }
}

async function saveWhatsapp() {
    try {
        await apiFetch('/settings/notification', { method: 'PUT', body: JSON.stringify({ whatsapp_enabled: document.getElementById('s_whatsapp_enabled').checked ? '1' : '0' }) });
        showToast('Settings saved.');
    } catch (e) { showToast(e.message, true); }
}

async function uploadUpdate() {
    const fileInput = document.getElementById('updateFile');
    if (!fileInput.files.length) { showToast('Choose a .zip file first.', true); return; }

    if (!confirm('Apply this update now? A backup of the current app/public files will be taken automatically first, and this can be rolled back if something breaks.')) return;

    const btn = document.getElementById('uploadUpdateBtn');
    const progress = document.getElementById('updateProgress');
    btn.disabled = true;
    progress.classList.remove('d-none');

    const fd = new FormData();
    fd.append('package', fileInput.files[0]);

    try {
        const res = await fetch(`${API_BASE}/admin/system-update/upload`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Update failed.');
        showToast(json.data.message);
        fileInput.value = '';
        loadUpdateHistory();
    } catch (e) {
        showToast(e.message, true);
    } finally {
        btn.disabled = false;
        progress.classList.add('d-none');
    }
}

async function loadUpdateHistory() {
    try {
        const res = await apiFetch('/admin/system-update/history');
        const updates = res.data.updates || [];

        if (updates.length === 0) {
            document.getElementById('updateHistoryBody').innerHTML = '<p class="text-muted small mb-0">No updates applied yet.</p>';
            return;
        }

        const statusPill = (s) => {
            const map = { applied: 'green', rolled_back: 'gray', failed: 'red' };
            return `<span class="li-pill li-pill-${map[s] || 'gray'}">${s.replace('_', ' ')}</span>`;
        };

        document.getElementById('updateHistoryBody').innerHTML = updates.map(u => `
            <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                <div>
                    <span class="fw-semibold small">${escapeHtml(u.original_filename)}</span>
                    ${statusPill(u.status)}
                    <div class="text-muted small">${u.files_changed} file(s) · by ${escapeHtml(u.applied_by_name || 'Unknown')} · ${formatDateTime(u.created_at)}</div>
                    ${u.notes ? `<div class="text-danger small">${escapeHtml(u.notes)}</div>` : ''}
                </div>
                ${u.status === 'applied' && u.backup_path ? `<button class="btn btn-li-outline btn-sm" onclick="rollbackUpdate(${u.id})">Rollback</button>` : ''}
            </div>
        `).join('');
    } catch (e) {
        document.getElementById('updateHistoryBody').innerHTML = `<p class="text-danger small mb-0">${e.message}</p>`;
    }
}

async function rollbackUpdate(id) {
    if (!confirm('Roll back to the state before this update was applied? Any changes made after this update will be reverted.')) return;
    try {
        await apiFetch(`/admin/system-update/${id}/rollback`, { method: 'POST' });
        showToast('Rolled back successfully.');
        loadUpdateHistory();
    } catch (e) { showToast(e.message, true); }
}

loadUpdateHistory();
loadSettings();
</script>
<?= $this->endSection() ?>
