<!-- templates/core/system_settings.html -->
{% extends 'core/base.html' %}
{% load static %}

{% block title %}System Settings — SwiftPOS{% endblock %}
{% block topbar_title %}System Settings{% endblock %}

{% block extra_css %}
<style>
.settings-card {
  border: none;
  border-radius: 16px;
  box-shadow: 0 1px 8px rgba(0,0,0,0.07);
}
.settings-card .card-header {
  background: #fff;
  border-bottom: 1px solid #f1f5f9;
  border-radius: 16px 16px 0 0;
  padding: .85rem 1.2rem;
  font-size: .82rem;
  font-weight: 700;
  color: #374151;
}
.settings-card .card-header i { color: #7c3aed; }
.settings-card .card-body { padding: 1.25rem; }
.form-label { font-size: .78rem; font-weight: 600; color: #374151; margin-bottom: .3rem; }
.form-control, .form-select {
  border-radius: 10px;
  border-color: #e5e7eb;
  font-size: .83rem;
  padding: .45rem .75rem;
}
.form-control:focus, .form-select:focus {
  border-color: #7c3aed;
  box-shadow: 0 0 0 3px rgba(124,58,237,.12);
}
.form-text { font-size: .72rem; color: #9ca3af; }
.form-switch .form-check-input { width: 2.4em; height: 1.3em; }
.form-check-label { font-size: .82rem; font-weight: 600; color: #374151; }
.pos-mode-label {
  display: flex; align-items: center; gap: .75rem;
  border: 2px solid #e5e7eb; border-radius: 12px;
  padding: .75rem 1rem; cursor: pointer; transition: border-color .15s, background .15s;
}
.pos-mode-label:has(input:checked) {
  border-color: #7c3aed;
  background: #f5f3ff;
}
.pos-mode-label input { flex-shrink: 0; }
.save-bar {
  position: sticky; bottom: 0; background: #fff;
  border-top: 1px solid #f1f5f9;
  padding: .9rem 0;
  margin-top: 2rem;
  z-index: 10;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-0 pb-5">

  <!-- Header -->
  <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
    <div>
      <h5 class="mb-0 fw-bold">System Settings</h5>
      <div class="text-muted small">Configure your business information, POS mode, and currency.</div>
    </div>
  </div>

  <!-- Messages -->
  {% if messages %}
  {% for message in messages %}
  <div class="alert alert-{{ message.tags }} alert-dismissible fade show mb-3" style="border-radius:12px;" role="alert">
    {{ message }}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  {% endfor %}
  {% endif %}

  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}

    <div class="row g-4">

      <!-- ── LEFT: Business Info ── -->
      <div class="col-lg-6">
        <div class="settings-card card h-100">
          <div class="card-header"><i class="fas fa-building me-2"></i>Business Information</div>
          <div class="card-body d-flex flex-column gap-3">

            <div class="mb-2 p-3 rounded d-flex align-items-center justify-content-between" style="background-color: #f8fafc; border: 1px dashed #cbd5e1;">
              <div>
                <div class="form-label mb-1">Company Slug (Store ID)</div>
                <div class="fw-bold" style="color: #4f46e5; letter-spacing: 0.5px;" id="companySlugText">{{ request.company.slug }}</div>
                <div class="small text-muted" style="font-size: 0.75rem;">Staff need this identifier to log into the mobile app.</div>
              </div>
              <button type="button" class="btn btn-sm btn-outline-primary px-3" style="border-radius: 8px;" onclick="copySlug(this)">
                <i class="fas fa-copy me-1"></i> Copy
              </button>
            </div>

            <div>
              <label class="form-label" for="id_business_name">Business Name</label>
              <input type="text" id="id_business_name" name="business_name"
                     class="form-control" value="{{ cs.business_name|default:'' }}"
                     placeholder="e.g. Acme Store">
            </div>

            <div class="row g-2">
              <div class="col-md-6">
                <label class="form-label" for="id_business_phone">Phone</label>
                <input type="text" id="id_business_phone" name="business_phone"
                       class="form-control" value="{{ cs.business_phone|default:'' }}"
                       placeholder="+234 ...">
              </div>
              <div class="col-md-6">
                <label class="form-label" for="id_business_email">Email</label>
                <input type="email" id="id_business_email" name="business_email"
                       class="form-control" value="{{ cs.business_email|default:'' }}"
                       placeholder="info@store.com">
              </div>
            </div>

            <div>
              <label class="form-label" for="id_business_address">Address</label>
              <textarea id="id_business_address" name="business_address"
                        class="form-control" rows="2"
                        placeholder="Store address...">{{ cs.business_address|default:'' }}</textarea>
            </div>

            <div>
              <label class="form-label" for="id_receipt_footer">
                Receipt Footer Text
                <span class="fw-normal text-muted">(e.g. "Thank you for your business!")</span>
              </label>
              <input type="text" id="id_receipt_footer" name="receipt_footer"
                     class="form-control" value="{{ cs.receipt_footer|default:'' }}"
                     placeholder="Thank you for your business!">
            </div>

            <div>
              <label class="form-label" for="id_receipt_header">Receipt Header Text</label>
              <input type="text" id="id_receipt_header" name="receipt_header"
                     class="form-control" value="{{ cs.receipt_header|default:'' }}"
                     placeholder="Optional header line on receipts">
            </div>

            <div>
              <label class="form-label" for="id_logo">
                Logo <span class="fw-normal text-muted">(used on receipts)</span>
              </label>
              {% if cs.logo %}
              <div class="mb-2">
                <img src="{{ cs.logo.url }}" alt="Current logo" style="height:50px;border-radius:8px;border:1px solid #e5e7eb;">
                <div class="form-text">Upload a new image to replace it.</div>
              </div>
              {% endif %}
              <input type="file" id="id_logo" name="logo"
                     class="form-control" accept="image/*">
            </div>

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

      <!-- ── RIGHT: POS + Features + Currency ── -->
      <div class="col-lg-6 d-flex flex-column gap-4">

        <!-- POS Interface Mode -->
        <div class="settings-card card">
          <div class="card-header"><i class="fas fa-cash-register me-2"></i>POS Interface</div>
          <div class="card-body">
            <label class="form-label d-block mb-3">Default POS Terminal Mode</label>
            <div class="d-flex flex-column gap-2">

              <label class="pos-mode-label">
                <input type="radio" name="pos_interface_mode" value="classic"
                       class="form-check-input"
                       {% if cs.pos_interface_mode == 'classic' or not cs.pos_interface_mode %}checked{% endif %}>
                <div>
                  <div class="fw-semibold" style="font-size:.85rem;">Classic POS</div>
                  <div class="text-muted" style="font-size:.75rem;">Dropdown-based, works fully offline</div>
                </div>
              </label>

              <label class="pos-mode-label">
                <input type="radio" name="pos_interface_mode" value="grid"
                       class="form-check-input"
                       {% if cs.pos_interface_mode == 'grid' %}checked{% endif %}>
                <div>
                  <div class="fw-semibold" style="font-size:.85rem;">Smart Grid POS V2</div>
                  <div class="text-muted" style="font-size:.75rem;">Visual product grid with cards</div>
                </div>
              </label>

            </div>
            {% if cs.pos_interface_mode == 'grid' %}
            <div class="alert alert-info py-2 small mt-3 mb-0" style="border-radius:10px;">
              <i class="fas fa-info-circle me-1"></i>
              Grid POS V2 is active —
              <a href="{% url 'sales:pos_grid' %}" class="fw-bold">Open it here</a>.
            </div>
            {% endif %}
          </div>
        </div>

        <!-- Features -->
        <div class="settings-card card">
          <div class="card-header"><i class="fas fa-toggle-on me-2"></i>Features</div>
          <div class="card-body d-flex flex-column gap-3">

            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="id_enable_camera_scanner"
                     name="enable_camera_scanner"
                     {% if cs.enable_camera_scanner %}checked{% endif %}>
              <label class="form-check-label" for="id_enable_camera_scanner">
                Enable Camera Scanner inside Barcode POS
              </label>
              <div class="form-text">Uses your device camera to scan barcodes on the Barcode POS page.</div>
            </div>

            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="id_show_receipt_logo"
                     name="show_receipt_logo"
                     {% if cs.show_receipt_logo %}checked{% endif %}>
              <label class="form-check-label" for="id_show_receipt_logo">
                Show Logo on Receipts
              </label>
            </div>

            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="id_enable_unlimited_stock"
                     name="enable_unlimited_stock"
                     {% if cs.enable_unlimited_stock %}checked{% endif %}>
              <label class="form-check-label" for="id_enable_unlimited_stock">
                Enable Unlimited Stock (Allow selling even with 0 quantity)
              </label>
              <div class="form-text">If enabled, you can sell products even when they are out of stock. (Useful for restaurants/services).</div>
            </div>

          </div>
        </div>

        <!-- Currency & VAT -->
        <div class="settings-card card">
          <div class="card-header"><i class="fas fa-coins me-2"></i>Currency &amp; VAT</div>
          <div class="card-body">
            <div class="row g-3">

              <div class="col-sm-4">
                <label class="form-label" for="id_currency_symbol">Currency Symbol</label>
                <input type="text" id="id_currency_symbol" name="currency_symbol"
                       class="form-control" value="{{ cs.currency_symbol|default:'₦' }}"
                       placeholder="₦" maxlength="5">
                <div class="form-text">e.g. ₦ $ £ €</div>
              </div>

              <div class="col-sm-4">
                <label class="form-label" for="id_decimal_places">Decimal Places</label>
                <select id="id_decimal_places" name="decimal_places" class="form-select">
                  <option value="0" {% if cs.decimal_places == 0 %}selected{% endif %}>0 (e.g. 100)</option>
                  <option value="2" {% if cs.decimal_places == 2 or not cs.decimal_places %}selected{% endif %}>2 (e.g. 100.00)</option>
                </select>
              </div>

              <div class="col-sm-4">
                <label class="form-label" for="id_vat_rate">VAT Rate (%)</label>
                <input type="number" id="id_vat_rate" name="vat_rate"
                       class="form-control" value="{{ cs.vat_rate|default:'0' }}"
                       step="0.01" min="0" max="100" placeholder="0">
                <div class="form-text">0 = disabled</div>
              </div>

              <div class="col-12">
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" id="id_use_comma_separator"
                         name="use_comma_separator"
                         {% if cs.use_comma_separator %}checked{% endif %}>
                  <label class="form-check-label" for="id_use_comma_separator">
                    Use comma as thousands separator (e.g. 1,000.00)
                  </label>
                </div>
              </div>

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

      </div>
      <!-- /right column -->

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

    <!-- ── WhatsApp / SMS (plan-gated) ─────────────────────────────── -->
    {% if request.company.plan.feature_whatsapp_sms %}
    <div class="settings-card card mt-4">
      <div class="card-header"><i class="fab fa-whatsapp me-2" style="color:#25D366;"></i>WhatsApp &amp; SMS Notifications</div>
      <div class="card-body">
        <p class="text-muted small mb-3">
          Enter your <strong>Termii</strong> (or compatible) API credentials below.
          Notifications only send when the global WhatsApp switch is activated by SwiftPOS.
        </p>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">WhatsApp API URL</label>
            <input type="url" name="whatsapp_api_url" class="form-control"
                   value="{{ cs.whatsapp_api_url|default:'' }}"
                   placeholder="https://api.ng.termii.com/api/sms/send">
            <div class="form-text">Your provider's send endpoint</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">API Key</label>
            <input type="password" name="whatsapp_api_key" class="form-control"
                   value="{{ cs.whatsapp_api_key|default:'' }}"
                   placeholder="sk_xxxxxxxx" autocomplete="new-password">
          </div>
          <div class="col-md-6">
            <label class="form-label">SMS API Key</label>
            <input type="password" name="sms_api_key" class="form-control"
                   value="{{ cs.sms_api_key|default:'' }}"
                   placeholder="SMS provider key" autocomplete="new-password">
          </div>
          <div class="col-md-6">
            <label class="form-label">SMS Sender Name</label>
            <input type="text" name="sms_sender_id" class="form-control"
                   value="{{ cs.sms_sender_id|default:'' }}"
                   placeholder="e.g. MyStore" maxlength="11">
            <div class="form-text">Max 11 chars, no spaces</div>
          </div>
        </div>
        <hr class="my-3">
        <div class="d-flex flex-column gap-2">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_receipt_whatsapp"
                   name="send_receipt_via_whatsapp" {% if cs.send_receipt_via_whatsapp %}checked{% endif %}>
            <label class="form-check-label" for="id_receipt_whatsapp">Send receipt to customer via WhatsApp after each sale</label>
          </div>
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_credit_whatsapp"
                   name="send_credit_via_whatsapp" {% if cs.send_credit_via_whatsapp %}checked{% endif %}>
            <label class="form-check-label" for="id_credit_whatsapp">Send balance reminder for credit sales via WhatsApp</label>
          </div>
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_lowstock_whatsapp"
                   name="send_lowstock_via_whatsapp" {% if cs.send_lowstock_via_whatsapp %}checked{% endif %}>
            <label class="form-check-label" for="id_lowstock_whatsapp">Send low-stock alert to admin via WhatsApp</label>
          </div>
        </div>
      </div>
    </div>
    {% endif %}

    <!-- ── Thermal Printing ──────────────────────────────────────────── -->
    <div class="settings-card card mt-4">
      <div class="card-header"><i class="fas fa-print me-2"></i>Thermal Printer</div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-5">
            <label class="form-label">Printer Name <span class="fw-normal text-muted">(Windows only)</span></label>
            <input type="text" name="thermal_printer_name" class="form-control"
                   value="{{ cs.thermal_printer_name|default:'' }}"
                   placeholder="e.g. XP-58 or leave blank for default">
            <div class="form-text">Exact printer name from Windows Printers list</div>
          </div>
          <div class="col-md-3">
            <label class="form-label">Paper Width (mm)</label>
            <select name="thermal_paper_width" class="form-select">
              <option value="58" {% if cs.thermal_paper_width == 58 %}selected{% endif %}>58 mm</option>
              <option value="80" {% if cs.thermal_paper_width == 80 or not cs.thermal_paper_width %}selected{% endif %}>80 mm (most common)</option>
            </select>
          </div>
          <div class="col-md-4 d-flex align-items-end">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="id_auto_print"
                     name="auto_print_receipt" {% if cs.auto_print_receipt %}checked{% endif %}>
              <label class="form-check-label" for="id_auto_print">Auto-print receipt after each sale</label>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ── Security / 2FA (plan-gated) ──────────────────────────────── -->
    {% if request.company.plan.feature_2fa %}
    <div class="settings-card card mt-4">
      <div class="card-header"><i class="fas fa-shield-halved me-2" style="color:#ef4444;"></i>Two-Factor Authentication (2FA)</div>
      <div class="card-body">
        <div class="alert alert-info py-2 small mb-3" style="border-radius:10px;">
          <i class="fas fa-envelope me-1"></i>
          <strong>Email-based 2FA:</strong> When enabled, staff must enter a one-time code sent to their email address at every login.
          Make sure each staff account has a valid email address set.
        </div>
        <div class="d-flex flex-column gap-3">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_2fa_admin"
                   name="require_2fa_for_admin" {% if cs.require_2fa_for_admin %}checked{% endif %}>
            <label class="form-check-label" for="id_2fa_admin">
              Require 2FA for <strong>Admin</strong> accounts
            </label>
            <div class="form-text">Admins must verify via email code at every login.</div>
          </div>
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_2fa_manager"
                   name="require_2fa_for_manager" {% if cs.require_2fa_for_manager %}checked{% endif %}>
            <label class="form-check-label" for="id_2fa_manager">
              Require 2FA for <strong>Manager</strong> accounts
            </label>
            <div class="form-text">Managers must verify via email code at every login.</div>
          </div>
        </div>
      </div>
    </div>
    {% else %}
    <div class="settings-card card mt-4" style="opacity:0.6;">
      <div class="card-header"><i class="fas fa-shield-halved me-2" style="color:#94a3b8;"></i>Two-Factor Authentication (2FA)</div>
      <div class="card-body">
        <div class="alert alert-warning py-2 small mb-0" style="border-radius:10px;">
          <i class="fas fa-lock me-1"></i>
          Two-Factor Authentication is not available on your current plan.
          <a href="{% url 'subscriptions:choose_plan' %}" class="fw-bold">Upgrade your plan</a> to unlock 2FA for your team.
        </div>
      </div>
    </div>
    {% endif %}


    <div class="save-bar d-flex justify-content-end gap-2">
      <a href="{% url 'dashboard' %}" class="btn btn-light" style="border-radius:10px;">Cancel</a>
      <button type="submit" class="btn btn-primary d-flex align-items-center gap-2" style="border-radius:10px;">
        <i class="fas fa-save"></i> Save Settings
      </button>
    </div>

  </form>

</div>
{% endblock %}

{% block extra_js %}
<script>
function copySlug(btn) {
  const slug = document.getElementById('companySlugText').innerText;
  navigator.clipboard.writeText(slug).then(() => {
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-check me-1"></i> Copied!';
    btn.classList.remove('btn-outline-primary');
    btn.classList.add('btn-success');
    btn.style.color = '#fff';
    setTimeout(() => {
      btn.innerHTML = originalHTML;
      btn.classList.remove('btn-success');
      btn.classList.add('btn-outline-primary');
      btn.style.color = '';
    }, 2000);
  }).catch(err => {
    console.error('Failed to copy: ', err);
  });
}
</script>
{% endblock %}
