{% extends 'companies/superadmin/base.html' %}

{% block content %}
<div class="content-header">
    <h2 class="mb-0"><i class="fas fa-plug text-primary me-2"></i> Server Setup &amp; Integrations</h2>
    <p class="text-muted mt-1 mb-0">Configure Monnify webhook and the daily subscription automation task.</p>
</div>

<div class="row g-4">

    <!-- ① Monnify Webhook URL -->
    <div class="col-12">
        <div class="card border-0 shadow-sm" style="border-radius:16px;border-left:4px solid #7c3aed !important;">
            <div class="card-header bg-white py-3" style="border-radius:16px 16px 0 0;">
                <h5 class="mb-0 fw-bold">
                    <i class="fas fa-link me-2" style="color:#7c3aed;"></i>
                    ① Monnify Webhook URL
                    <span class="badge bg-warning text-dark ms-2" style="font-size:.7rem;vertical-align:middle;">Required</span>
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted small mb-3">
                    Monnify must call this URL after every payment to automatically activate or renew a company's subscription.
                    Without this, payments will NOT activate subscriptions automatically.
                </p>
                <label class="form-label fw-semibold small">Your Webhook URL:</label>
                <div class="input-group mb-2">
                    <input type="text" class="form-control font-monospace" id="webhookUrlInput"
                           value="{{ webhook_url }}" readonly
                           style="font-size:.85rem;background:#f8fafc;color:#1e293b;">
                    <button class="btn btn-outline-secondary" type="button" onclick="copyVal('webhookUrlInput','copyIcon1')" title="Copy">
                        <i class="fas fa-copy" id="copyIcon1"></i> Copy
                    </button>
                </div>
                <div class="alert alert-info py-2 small mb-0" style="border-radius:10px;">
                    <strong>Steps:</strong>
                    Log in to <a href="https://app.monnify.com" target="_blank">app.monnify.com</a>
                    → <strong>Settings</strong> → <strong>Webhook</strong>
                    → paste the URL above → <strong>Save</strong>.
                    Monnify will POST to this URL after every successful payment.
                </div>
            </div>
        </div>
    </div>

    <!-- ① Paystack Webhook URL -->
    <div class="col-12">
        <div class="card border-0 shadow-sm" style="border-radius:16px;border-left:4px solid #10b981 !important;">
            <div class="card-header bg-white py-3" style="border-radius:16px 16px 0 0;">
                <h5 class="mb-0 fw-bold">
                    <i class="fas fa-link me-2" style="color:#10b981;"></i>
                    ① Paystack Webhook URL
                    <span class="badge ms-2" style="font-size:.7rem;vertical-align:middle;background:#d1fae5;color:#065f46;">Required if using Paystack</span>
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted small mb-3">
                    Paystack must call this URL after every successful payment to automatically activate or renew a company's subscription.
                    Without this, payments may not activate subscriptions if the customer closes their browser.
                </p>
                <label class="form-label fw-semibold small">Your Paystack Webhook URL:</label>
                <div class="input-group mb-2">
                    <input type="text" class="form-control font-monospace" id="paystackWebhookInput"
                           value="{{ paystack_webhook_url }}" readonly
                           style="font-size:.85rem;background:#f0fdf4;color:#1e293b;">
                    <button class="btn btn-outline-secondary" type="button" onclick="copyVal('paystackWebhookInput','copyIconPS')" title="Copy">
                        <i class="fas fa-copy" id="copyIconPS"></i> Copy
                    </button>
                </div>
                <div class="alert alert-info py-2 small mb-0" style="border-radius:10px;">
                    <strong>Steps:</strong>
                    Log in to <a href="https://dashboard.paystack.com/#/settings/developer" target="_blank">dashboard.paystack.com</a>
                    → <strong>Settings</strong> → <strong>API Keys & Webhooks</strong>
                    → paste the URL above in the <strong>Webhook URL</strong> field → <strong>Save Changes</strong>.
                    Paystack will POST to this URL after every successful <code>charge.success</code> event.
                </div>
            </div>
        </div>
    </div>

    <!-- ② Daily Cron Job -->
    <div class="col-12">
        <div class="card border-0 shadow-sm" style="border-radius:16px;border-left:4px solid #0ea5e9 !important;">
            <div class="card-header bg-white py-3" style="border-radius:16px 16px 0 0;">
                <h5 class="mb-0 fw-bold">
                    <i class="fas fa-calendar-check me-2" style="color:#0ea5e9;"></i>
                    ② Daily Subscription Task (cPanel Cron Job)
                </h5>
            </div>
            <div class="card-body">

                <!-- What it does -->
                <div class="p-3 mb-4" style="background:#f0f9ff;border-radius:12px;border:1px solid #bae6fd;">
                    <p class="fw-bold mb-2 small"><i class="fas fa-info-circle text-info me-1"></i> This task must run <u>once every day</u>. It does 3 things:</p>
                    <div class="d-flex flex-column gap-1 small">
                        <div>
                            <span class="badge bg-danger me-2">1</span>
                            <strong>Suspends expired companies</strong> — companies whose subscription ran out lose access automatically.
                        </div>
                        <div>
                            <span class="badge bg-warning text-dark me-2">2</span>
                            <strong>Applies plan downgrades</strong> — switches plan at end of billing cycle if downgrade was requested.
                        </div>
                        <div>
                            <span class="badge bg-info text-white me-2">3</span>
                            <strong>Sends warning emails</strong> — notifies companies 3 days and 1 day before expiry.
                        </div>
                    </div>
                    <div class="mt-2 small text-danger fw-semibold">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        If this is not set up, expired companies stay active forever and no one gets renewal reminders.
                    </div>
                </div>

                <!-- Command -->
                <label class="form-label fw-semibold small">Command to paste into cPanel Cron Jobs:</label>
                <div class="input-group mb-2">
                    <input type="text" class="form-control font-monospace" id="cronCmdInput"
                           value="{{ cpanel_cron_command }}" readonly
                           style="font-size:.82rem;background:#f8fafc;">
                    <button class="btn btn-outline-secondary" type="button" onclick="copyVal('cronCmdInput','copyIcon2')" title="Copy">
                        <i class="fas fa-copy" id="copyIcon2"></i> Copy
                    </button>
                </div>
                <div class="text-muted small mb-4">
                    <i class="fas fa-lightbulb text-warning me-1"></i>
                    On a live cPanel server, the python path may differ. Try
                    <code>/usr/bin/python3</code> or
                    <code>/home/yourusername/virtualenv/swone/3.x/bin/python</code>.
                    Ask your host if unsure.
                </div>

                <!-- Step by step -->
                <div class="p-3 mb-4" style="background:#fafafa;border-radius:12px;border:1px solid #e2e8f0;">
                    <p class="fw-bold small mb-3"><i class="fas fa-server me-1 text-primary"></i> How to set this up on cPanel (step by step):</p>
                    <ol class="small" style="line-height:2.1;padding-left:1.2rem;">
                        <li>Log in to your <strong>cPanel</strong> hosting account.</li>
                        <li>Search for <strong>"Cron Jobs"</strong> in the cPanel search bar and open it.</li>
                        <li>Scroll down to <strong>"Add New Cron Job"</strong>.</li>
                        <li>In the <strong>Common Settings</strong> dropdown, choose <code>Once Per Day</code> (runs at 1:00 AM).</li>
                        <li>In the <strong>Command</strong> field, paste the command shown above.</li>
                        <li>Click <strong>"Add New Cron Job"</strong>. Done! ✅</li>
                    </ol>
                </div>

                <!-- Schedule reference table -->
                <div class="p-3" style="background:#f8fafc;border-radius:12px;border:1px dashed #cbd5e1;">
                    <p class="fw-semibold small mb-2">Cron Schedule Reference <span class="text-muted fw-normal">(if setting time fields manually)</span>:</p>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mb-0" style="font-size:.8rem;">
                            <thead class="table-light">
                                <tr>
                                    <th>Minute</th>
                                    <th>Hour</th>
                                    <th>Day</th>
                                    <th>Month</th>
                                    <th>Weekday</th>
                                    <th>Meaning</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="table-success">
                                    <td><code>0</code></td>
                                    <td><code>1</code></td>
                                    <td><code>*</code></td>
                                    <td><code>*</code></td>
                                    <td><code>*</code></td>
                                    <td><strong>Every day at 1:00 AM</strong> ✅ Recommended</td>
                                </tr>
                                <tr>
                                    <td><code>0</code></td>
                                    <td><code>0</code></td>
                                    <td><code>*</code></td>
                                    <td><code>*</code></td>
                                    <td><code>*</code></td>
                                    <td>Every day at midnight</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3 p-2 small" style="background:#f0fdf4;border-radius:8px;color:#065f46;">
                        <i class="fas fa-check-circle me-1"></i>
                        <strong>To test manually:</strong> Go to cPanel → Terminal (or SSH), paste the command, and press Enter.
                        It should print <em>"Subscription processing complete"</em> with no errors.
                    </div>
                </div>

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

    <!-- ③ Analytics & Insights Cron Job -->
    <div class="col-12">
        <div class="card border-0 shadow-sm" style="border-radius:16px;border-left:4px solid #10b981 !important;">
            <div class="card-header bg-white py-3" style="border-radius:16px 16px 0 0;">
                <h5 class="mb-0 fw-bold">
                    <i class="fas fa-lightbulb me-2" style="color:#10b981;"></i>
                    ③ Daily Analytics &amp; Insights (Midnight WAT)
                </h5>
            </div>
            <div class="card-body">

                <!-- What it does -->
                <div class="p-3 mb-4" style="background:#f0fdf4;border-radius:12px;border:1px solid #6ee7b7;">
                    <p class="fw-bold mb-2 small"><i class="fas fa-info-circle text-success me-1"></i> This task runs <u>once every day at midnight WAT</u>. It does 4 things:</p>
                    <div class="d-flex flex-column gap-1 small">
                        <div>
                            <span class="badge bg-primary me-2">1</span>
                            <strong>Generates Business Insights</strong> — sales trends, low-stock alerts, top products, staff performance, and more (15+ auto insights per company).
                        </div>
                        <div>
                            <span class="badge bg-warning text-dark me-2">2</span>
                            <strong>Stock Forecasting</strong> — calculates how many days until each product runs out and recommends restock quantities.
                        </div>
                        <div>
                            <span class="badge bg-info text-white me-2">3</span>
                            <strong>Sends Daily Email Reports</strong> — sends a business summary email to each company admin.
                        </div>
                        <div>
                            <span class="badge bg-secondary me-2">4</span>
                            <strong>Cleans Old Notifications</strong> — removes notifications older than 30 days automatically.
                        </div>
                    </div>
                    <div class="mt-2 small text-danger fw-semibold">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        Without this, the Analytics dashboard will show no insights and no email reports will be sent.
                    </div>
                </div>

                <!-- Command -->
                <label class="form-label fw-semibold small">Command to paste into cPanel Cron Jobs:</label>
                <div class="input-group mb-2">
                    <input type="text" class="form-control font-monospace" id="insightsCronInput"
                           value="{{ insights_cron_command }}" readonly
                           style="font-size:.82rem;background:#f8fafc;">
                    <button class="btn btn-outline-secondary" type="button" onclick="copyVal('insightsCronInput','copyIcon3')" title="Copy">
                        <i class="fas fa-copy" id="copyIcon3"></i> Copy
                    </button>
                </div>
                <div class="text-muted small mb-4">
                    <i class="fas fa-clock text-warning me-1"></i>
                    Set the schedule to <code>0 23 * * *</code> (11 PM UTC = midnight WAT) or use <strong>Once Per Day</strong> in cPanel.
                </div>

                <!-- Step by step -->
                <div class="p-3 mb-4" style="background:#fafafa;border-radius:12px;border:1px solid #e2e8f0;">
                    <p class="fw-bold small mb-3"><i class="fas fa-server me-1 text-success"></i> How to set up on cPanel (step by step):</p>
                    <ol class="small" style="line-height:2.1;padding-left:1.2rem;">
                        <li>Log in to your <strong>cPanel</strong> hosting account.</li>
                        <li>Search for <strong>"Cron Jobs"</strong> and open it.</li>
                        <li>Scroll to <strong>"Add New Cron Job"</strong>.</li>
                        <li>Set <strong>Minute</strong> = <code>0</code>, <strong>Hour</strong> = <code>23</code>, Day/Month/Weekday = <code>*</code>.</li>
                        <li>Paste the command above into the <strong>Command</strong> field.</li>
                        <li>Click <strong>"Add New Cron Job"</strong>. ✅</li>
                    </ol>
                </div>

                <!-- Schedule reference -->
                <div class="p-3" style="background:#f8fafc;border-radius:12px;border:1px dashed #cbd5e1;">
                    <p class="fw-semibold small mb-2">Cron Schedule (midnight WAT = 23:00 UTC):</p>
                    <table class="table table-sm table-bordered mb-0" style="font-size:.8rem;">
                        <thead class="table-light">
                            <tr><th>Minute</th><th>Hour</th><th>Day</th><th>Month</th><th>Weekday</th><th>Meaning</th></tr>
                        </thead>
                        <tbody>
                            <tr class="table-success">
                                <td><code>0</code></td><td><code>23</code></td><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td>
                                <td><strong>Every day at 11 PM UTC (= midnight WAT)</strong> ✅ Recommended</td>
                            </tr>
                            <tr>
                                <td><code>0</code></td><td><code>0</code></td><td><code>*</code></td><td><code>*</code></td><td><code>*</code></td>
                                <td>Every day at midnight UTC (= 1 AM WAT)</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="mt-3 p-2 small" style="background:#f0fdf4;border-radius:8px;color:#065f46;">
                        <i class="fas fa-check-circle me-1"></i>
                        <strong>To test manually:</strong> In cPanel Terminal or SSH, run the command. It should print <em>"Successfully generated insights for X companies"</em>.
                    </div>
                </div>

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

    <!-- ④ reCAPTCHA — Login Protection -->
    <div class="col-12">
        <div class="card border-0 shadow-sm" style="border-radius:16px;border-left:4px solid #dc2626 !important;">
            <div class="card-header bg-white py-3" style="border-radius:16px 16px 0 0;">
                <h5 class="mb-0 fw-bold">
                    <i class="fas fa-shield-halved me-2" style="color:#dc2626;"></i>
                    ④ reCAPTCHA v2 — Login Bot Protection
                    <span class="badge ms-2" style="font-size:.7rem;vertical-align:middle;background:#fee2e2;color:#991b1b;">Recommended</span>
                </h5>
            </div>
            <div class="card-body">

                <!-- What it does -->
                <div class="p-3 mb-4" style="background:#fef2f2;border-radius:12px;border:1px solid #fca5a5;">
                    <p class="fw-bold mb-2 small"><i class="fas fa-robot text-danger me-1"></i> What reCAPTCHA does:</p>
                    <div class="d-flex flex-column gap-1 small">
                        <div>
                            <span class="badge bg-danger me-2">🤖</span>
                            <strong>Blocks automated bots</strong> — prevents credential-stuffing and brute-force scripts from hammering the login page.
                        </div>
                        <div>
                            <span class="badge bg-warning text-dark me-2">🔐</span>
                            <strong>Gate before credentials</strong> — the reCAPTCHA token is verified <em>before</em> the username/password are even checked.
                        </div>
                        <div>
                            <span class="badge bg-info text-white me-2">⚙️</span>
                            <strong>Zero code needed</strong> — fully configurable from Django Admin. Toggle on/off at any time with no restart required.
                        </div>
                    </div>
                    <div class="mt-2 small" style="color:#065f46;">
                        <i class="fas fa-info-circle me-1"></i>
                        <strong>Note:</strong> Even with reCAPTCHA disabled, SwiftPOS still enforces IP-based rate limiting
                        (5 failures → 15-minute block) as a server-side backstop.
                    </div>
                </div>

                <!-- Step by step -->
                <div class="p-3 mb-4" style="background:#fafafa;border-radius:12px;border:1px solid #e2e8f0;">
                    <p class="fw-bold small mb-3"><i class="fas fa-list-ol me-1 text-danger"></i> Setup steps (takes ~3 minutes):</p>
                    <ol class="small" style="line-height:2.2;padding-left:1.2rem;">
                        <li>
                            Go to <a href="https://www.google.com/recaptcha/admin/create" target="_blank" class="fw-semibold text-danger">google.com/recaptcha/admin/create</a>
                            and sign in with your Google account.
                        </li>
                        <li>
                            Fill in a <strong>Label</strong> (e.g. <code>SwiftPOS Login</code>).
                        </li>
                        <li>
                            Under <strong>reCAPTCHA type</strong>, choose
                            <span class="badge bg-dark">reCAPTCHA v2</span> →
                            <strong>"I'm not a robot" Checkbox</strong>.
                        </li>
                        <li>
                            Under <strong>Domains</strong>, add your production domain (e.g. <code>app.swiftpos.ng</code>).
                            For local testing also add <code>127.0.0.1</code> and <code>localhost</code>.
                        </li>
                        <li>Click <strong>Submit</strong>. Google will show you two keys:</li>
                    </ol>

                    <!-- Key display boxes -->
                    <div class="row g-3 mt-1 mb-3">
                        <div class="col-md-6">
                            <div class="p-3 rounded" style="background:#f0fdf4;border:1px solid #86efac;">
                                <div class="small fw-bold mb-1" style="color:#166534;">
                                    <i class="fas fa-eye me-1"></i> Site Key (PUBLIC)
                                </div>
                                <div class="small text-muted">
                                    Paste into <strong>recaptcha_site_key</strong> in Django Admin.<br>
                                    This is embedded in the HTML — it's safe to be public.
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="p-3 rounded" style="background:#fff7ed;border:1px solid #fdba74;">
                                <div class="small fw-bold mb-1" style="color:#9a3412;">
                                    <i class="fas fa-eye-slash me-1"></i> Secret Key (PRIVATE)
                                </div>
                                <div class="small text-muted">
                                    Paste into <strong>recaptcha_secret_key</strong> in Django Admin.<br>
                                    <strong>Never share this.</strong> It verifies tokens server-side.
                                </div>
                            </div>
                        </div>
                    </div>

                    <ol class="small" style="line-height:2.2;padding-left:1.2rem;" start="6">
                        <li>
                            In Django Admin, go to
                            <strong>Site Configuration</strong>
                            (under the Core section) → scroll to
                            <strong>"reCAPTCHA — Login Protection"</strong>.
                        </li>
                        <li>Paste the <strong>Site Key</strong> and <strong>Secret Key</strong> into the respective fields.</li>
                        <li>Check <strong>Recaptcha enabled</strong> → <strong>Save</strong>. Done! ✅</li>
                    </ol>
                </div>

                <!-- Django Admin shortcut -->
                <div class="alert alert-secondary py-2 small mb-3" style="border-radius:10px;">
                    <i class="fas fa-external-link-alt me-1"></i>
                    <strong>Direct link to configure:</strong>
                    <a href="/{{ admin_url }}core/siteconfiguration/1/change/#id_recaptcha_enabled"
                       target="_blank" class="ms-1 fw-semibold">
                        Django Admin → Site Configuration → reCAPTCHA section
                    </a>
                </div>

                <!-- Troubleshooting -->
                <div class="p-3" style="background:#f8fafc;border-radius:12px;border:1px dashed #cbd5e1;">
                    <p class="fw-semibold small mb-2"><i class="fas fa-wrench me-1 text-secondary"></i> Troubleshooting:</p>
                    <ul class="small mb-0" style="line-height:2;">
                        <li><strong>Widget not appearing?</strong> Check that <code>recaptcha_enabled</code> is ✅ ON and <code>recaptcha_site_key</code> is not blank.</li>
                        <li><strong>Always passing even when unchecked?</strong> Verify <code>recaptcha_secret_key</code> is correct. An empty secret key causes fail-open (graceful bypass).</li>
                        <li><strong>"ERROR for site owner: Invalid domain"?</strong> Your domain is not registered in the Google reCAPTCHA console. Add it there.</li>
                        <li><strong>Testing locally?</strong> Add <code>localhost</code> and <code>127.0.0.1</code> to allowed domains in Google console, then use those special test keys for dev.</li>
                    </ul>
                </div>

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

</div><!-- /row -->


<script>
function copyVal(inputId, iconId) {
    var input = document.getElementById(inputId);
    input.select();
    input.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(input.value).then(function() {
        var icon = document.getElementById(iconId);
        icon.className = 'fas fa-check text-success';
        setTimeout(function() { icon.className = 'fas fa-copy'; }, 2000);
    }).catch(function() {
        document.execCommand('copy');
    });
}
</script>
{% endblock %}
