<?php /* settings/index.php — Advanced Full UI */
$isEdit      = Auth::can('settings.edit');
$retention   = (int)($s['activity_log_retention_days'] ?? 90);
$onlineUsers = $onlineNow ?? [];
$onlineCount = count(array_filter($onlineUsers, fn($u) => $u['status'] === 'online'));
$awayCount   = count(array_filter($onlineUsers, fn($u) => $u['status'] === 'away'));
$sym         = setting('currency_symbol','Rs.');
$finAccounts = Database::fetchAll(
    "SELECT id, account_name, account_type FROM finance_accounts WHERE status='active' ORDER BY account_type, account_name"
);
?>
<style>
/* ── Hero ─────────────────────────────────────────────── */
.set-hero{
  background:#0f172a;border-radius:14px;padding:20px 26px;color:#fff;
  margin-bottom:18px;border:1px solid #1e293b;box-shadow:0 4px 20px rgba(0,0,0,.15);
  display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap
}
.set-hero .sh-title{font-size:1.2rem;font-weight:800;display:flex;align-items:center;gap:10px;margin-bottom:4px}
.set-hero .sh-sub{font-size:.78rem;color:#94a3b8}
.set-hero .save-btn{
  background:#3b82f6;color:#fff;border:none;border-radius:10px;
  font-weight:700;font-size:.88rem;padding:10px 22px;cursor:pointer;
  display:inline-flex;align-items:center;gap:8px;transition:background .15s;white-space:nowrap
}
.set-hero .save-btn:hover{background:#2563eb}

/* ── Tab nav ──────────────────────────────────────────── */
.set-nav{
  display:flex;gap:3px;background:#f1f5f9;border-radius:12px;
  padding:4px;margin-bottom:20px;flex-wrap:wrap
}
.s-tab{
  flex:1;min-width:90px;display:flex;align-items:center;justify-content:center;
  gap:6px;padding:9px 12px;border-radius:8px;border:none;background:transparent;
  color:#64748b;font-size:.8rem;font-weight:600;cursor:pointer;transition:all .15s;white-space:nowrap
}
.s-tab:hover{background:#e2e8f0;color:#334155}
.s-tab.active{background:#fff;color:#1d4ed8;box-shadow:0 1px 6px rgba(0,0,0,.1);font-weight:700}
.s-tab i{font-size:.9rem}

/* ── Panes ────────────────────────────────────────────── */
.s-pane{display:none}.s-pane.active{display:block}

/* ── Cards ────────────────────────────────────────────── */
.set-card{
  background:#fff;border-radius:12px;border:1px solid #e8ecf0;
  margin-bottom:16px;overflow:hidden;box-shadow:0 1px 4px rgba(0,0,0,.04)
}
.set-card-head{
  padding:11px 16px;background:#f8fafc;border-bottom:1px solid #f1f5f9;
  font-size:.78rem;font-weight:700;color:#1e293b;
  display:flex;align-items:center;gap:8px
}
.set-card-head .badge{margin-left:auto;font-size:.6rem}
.set-card-body{padding:16px}

/* ── Form elements ────────────────────────────────────── */
.form-label{font-size:.77rem;font-weight:600;color:#374151;margin-bottom:4px}
.form-control,.form-select{font-size:.84rem;border-color:#d1d5db;border-radius:8px}
.form-control:focus,.form-select:focus{border-color:#3b82f6;box-shadow:0 0 0 3px rgba(59,130,246,.12)}
.form-text{font-size:.7rem;color:#9ca3af;margin-top:3px}
.input-group-text{font-size:.8rem;background:#f8fafc;border-color:#d1d5db}

/* ── Toggle switch ────────────────────────────────────── */
.sw-row{
  display:flex;justify-content:space-between;align-items:center;
  padding:10px 0;border-bottom:1px solid #f1f5f9
}
.sw-row:last-child{border:none}
.sw-label{font-size:.82rem;font-weight:600;color:#374151}
.sw-desc{font-size:.71rem;color:#9ca3af;margin-top:2px}
.tog{position:relative;width:44px;height:24px;flex-shrink:0}
.tog input{opacity:0;width:0;height:0;position:absolute}
.tog-slider{
  position:absolute;inset:0;background:#d1d5db;border-radius:24px;
  cursor:pointer;transition:.2s
}
.tog-slider::after{
  content:'';position:absolute;left:3px;bottom:3px;
  width:18px;height:18px;background:#fff;border-radius:50%;transition:.2s
}
.tog input:checked+.tog-slider{background:#3b82f6}
.tog input:checked+.tog-slider::after{transform:translateX(20px)}
.tog input:disabled+.tog-slider{opacity:.5;cursor:not-allowed}

/* ── Stat row ─────────────────────────────────────────── */
.st-row{display:flex;justify-content:space-between;padding:8px 0;
  border-bottom:1px solid #f1f5f9;font-size:.82rem}
.st-row:last-child{border:none}
.st-val{font-weight:700;color:#1e293b}

/* ── Section divider ──────────────────────────────────── */
.sec-divider{
  display:flex;align-items:center;gap:8px;margin:14px 0 10px;
  font-size:.68rem;font-weight:700;text-transform:uppercase;
  letter-spacing:.07em;color:#94a3b8
}
.sec-divider::after{content:'';flex:1;height:1px;background:#f1f5f9}

/* ── Payment method row ───────────────────────────────── */
.pmt-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid #f8fafc}
.pmt-row:last-child{border:none}
.pmt-label{width:110px;flex-shrink:0;font-size:.78rem;font-weight:600}

/* ── Danger zone ──────────────────────────────────────── */
.danger-zone{background:#fef2f2;border:1px solid #fecaca;border-radius:10px;padding:14px 16px}

/* ── KPI pill in hero ─────────────────────────────────── */
.hero-pill{
  display:inline-flex;align-items:center;gap:6px;
  background:rgba(255,255,255,.12);border-radius:20px;
  padding:4px 12px;font-size:.75rem;font-weight:600;color:#e2e8f0
}
</style>

<!-- ── Hero ───────────────────────────────────────────── -->
<div class="set-hero">
  <div>
    <div class="sh-title">
      <i class="bi bi-gear-fill" style="color:#60a5fa"></i>
      System Settings
    </div>
    <div class="sh-sub">
      <?= e(setting('shop_name','MJPOS')) ?>
      &nbsp;·&nbsp; Configure your shop, POS, stock and system preferences
    </div>
  </div>
  <?php if($isEdit):?>
  <button type="submit" form="settingsForm" class="save-btn">
    <i class="bi bi-check-circle"></i>Save All Settings
  </button>
  <?php endif;?>
</div>

<?= flashMessages() ?>

<form method="POST" action="<?=APP_URL?>/settings"
      enctype="multipart/form-data" id="settingsForm">
  <?= Auth::csrfField() ?>

  <!-- ── Tab nav ────────────────────────────────────────── -->
  <div class="set-nav">
    <?php foreach([
      ['shop',     'bi-shop',        'Shop Info',    'primary'],
      ['pos',      'bi-receipt',     'POS & Tax',    'warning'],
      ['stock',    'bi-boxes',       'Stock',        'success'],
      ['branch',   'bi-building',    'Branches',     'primary'],
      ['activity', 'bi-journal-text','Activity Log', 'info'],
      ['online',   'bi-people-fill', 'Online Users', 'success'],
      ['sms',      'bi-chat-dots',   'SMS',          'success'],
    ] as[$id,$ico,$lbl,$clr]):?>
    <button type="button" class="s-tab <?=$id==='shop'?'active':''?>"
            onclick="switchTab('<?=$id?>',this)">
      <i class="bi <?=$ico?> text-<?=$clr?>"></i><?=$lbl?>
    </button>
    <?php endforeach;?>
  </div>

  <!-- ════════════════════════════════════════════════════
       TAB: SHOP
       ════════════════════════════════════════════════════ -->
  <div class="s-pane active" id="pane-shop">
    <div class="row g-3">

      <!-- Left -->
      <div class="col-lg-6">

        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-shop text-primary"></i>Shop Information</div>
          <div class="set-card-body">
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">Shop Name *</label>
                <input type="text" name="shop_name" class="form-control"
                       value="<?=e($s['shop_name']??'')?>"
                       placeholder="KUSSIYA (කුස්සිය)"
                       <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-12">
                <label class="form-label">Tagline <small class="text-muted">(login page)</small></label>
                <textarea name="shop_tagline" class="form-control" rows="2"
                          placeholder="Your business tagline..."
                          <?=!$isEdit?'readonly':''?>><?=e($s['shop_tagline']??'')?></textarea>
              </div>
              <div class="col-12">
                <label class="form-label">Address</label>
                <textarea name="shop_address" class="form-control" rows="2"
                          <?=!$isEdit?'readonly':''?>><?=e($s['shop_address']??'')?></textarea>
              </div>
              <div class="col-md-6">
                <label class="form-label">Phone</label>
                <input type="text" name="shop_phone" class="form-control"
                       value="<?=e($s['shop_phone']??'')?>" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-md-6">
                <label class="form-label">Email</label>
                <input type="email" name="shop_email" class="form-control"
                       value="<?=e($s['shop_email']??'')?>" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-md-6">
                <label class="form-label">Currency Symbol</label>
                <input type="text" name="currency_symbol" class="form-control"
                       value="<?=e($s['currency_symbol']??'Rs.')?>"
                       style="max-width:100px" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-md-6">
                <label class="form-label">Timezone</label>
                <select name="timezone" class="form-select" <?=!$isEdit?'disabled':''?>>
                  <?php foreach(['Asia/Colombo','Asia/Kolkata','Asia/Dubai','Asia/Singapore',
                                 'Asia/Tokyo','Europe/London','America/New_York','UTC'] as $tz):
                    $sel = $tz===($s['timezone']??'Asia/Colombo')?'selected':'';?>
                  <option value="<?=$tz?>" <?=$sel?>><?=$tz?></option>
                  <?php endforeach;?>
                </select>
                <div class="form-text">Now: <?=date('d M Y H:i')?></div>
              </div>
            </div>
          </div>
        </div>

        <!-- Shop Logo -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-image text-info"></i>Shop Logo</div>
          <div class="set-card-body">
            <?php $logo=$s['shop_logo']??'';?>
            <?php if($logo):?>
            <div class="mb-3 p-3 text-center rounded" style="background:#f8fafc;border:1px dashed #cbd5e1">
              <img src="<?=APP_URL?>/uploads/<?=e($logo)?>" style="max-height:60px">
              <div class="text-muted" style="font-size:.7rem;margin-top:4px"><?=e($logo)?></div>
            </div>
            <?php endif;?>
            <?php if($isEdit):?>
            <input type="file" name="shop_logo" class="form-control" accept="image/png,image/jpeg,image/gif">
            <div class="form-text">PNG, JPG, GIF · Max 2 MB</div>
            <?php else:?>
            <div class="text-muted small">No permission to change logo.</div>
            <?php endif;?>
          </div>
        </div>

        <!-- Site Icon / Favicon -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-browser-chrome text-warning"></i>Site Icon (Favicon)</div>
          <div class="set-card-body">
            <?php $favicon = $s['site_icon'] ?? ''; ?>
            <div class="d-flex align-items-center gap-3 mb-3">
              <div style="width:48px;height:48px;border:1px solid #e2e8f0;border-radius:8px;
                          display:flex;align-items:center;justify-content:center;background:#f8fafc;flex-shrink:0">
                <?php if($favicon):?>
                <img src="<?=UPLOAD_URL?>/<?=e($favicon)?>" style="width:32px;height:32px;object-fit:contain">
                <?php else:?>
                <i class="bi bi-image text-muted fs-5"></i>
                <?php endif;?>
              </div>
              <div>
                <div class="fw-semibold small">Browser Tab Icon</div>
                <div class="text-muted" style="font-size:.7rem">
                  Shows in browser tab, bookmarks &amp; home screen.
                  <?php if(!$favicon):?><br><span class="text-warning">Using default "M" icon</span><?php endif;?>
                </div>
              </div>
            </div>
            <?php if($isEdit):?>
            <input type="file" name="site_icon" class="form-control" accept="image/png,image/jpeg,image/x-icon,image/svg+xml,image/webp">
            <div class="form-text">
              PNG, ICO, SVG, WebP · Max 1 MB · <strong>Best size: 32×32 or 64×64 px</strong>
            </div>
            <?php if($favicon):?>
            <label class="d-inline-flex align-items-center gap-1 mt-2 small text-danger" style="cursor:pointer">
              <input type="checkbox" name="remove_site_icon" value="1">Remove site icon (revert to default)
            </label>
            <?php endif;?>
            <?php else:?>
            <div class="text-muted small">No permission to change this.</div>
            <?php endif;?>
          </div>
        </div>

      </div>

      <!-- Right -->
      <div class="col-lg-6">

        <!-- Login Background -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-card-image text-primary"></i>Login Page Background</div>
          <div class="set-card-body">
            <?php $loginBg=$s['login_bg_image']??'';?>
            <?php if($loginBg):?>
            <div class="mb-3 text-center p-2 rounded" style="background:#f8fafc;border:1px dashed #cbd5e1">
              <img src="<?=UPLOAD_URL?>/<?=e($loginBg)?>" style="max-height:100px;border-radius:6px">
              <div class="text-muted" style="font-size:.7rem;margin-top:4px"><?=e($loginBg)?></div>
              <?php if($isEdit):?>
              <label class="d-inline-flex align-items-center gap-1 mt-2 small text-danger" style="cursor:pointer">
                <input type="checkbox" name="remove_login_bg" value="1">Remove background
              </label>
              <?php endif;?>
            </div>
            <?php endif;?>
            <?php if($isEdit):?>
            <input type="file" name="login_bg" class="form-control" accept="image/png,image/jpeg,image/webp">
            <div class="form-text">PNG, JPG, WebP · Max 2 MB · 1200×1600px recommended</div>
            <?php else:?>
            <div class="text-muted small">No permission to change this.</div>
            <?php endif;?>
          </div>
        </div>

        <!-- Invoice -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-receipt text-warning"></i>Invoice Numbering</div>
          <div class="set-card-body">
            <div class="row g-3">
              <?php foreach([
                ['invoice_prefix','Invoice Prefix','INV-'],
                ['purchase_prefix','Purchase Prefix','PUR-'],
                ['return_prefix','Return Prefix','RET-'],
              ] as[$k,$l,$ph]):?>
              <div class="col-md-4">
                <label class="form-label"><?=$l?></label>
                <input type="text" name="<?=$k?>" class="form-control"
                       value="<?=e($s[$k]??'')?>" placeholder="<?=$ph?>"
                       <?=!$isEdit?'readonly':''?>>
              </div>
              <?php endforeach;?>
            </div>
          </div>
        </div>

        <!-- Receipt -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-printer text-success"></i>Receipt Options</div>
          <div class="set-card-body">
            <?php foreach([
              ['receipt_show_tax', 'Show Tax on Receipt','Display tax breakdown line'],
              ['receipt_show_logo','Show Logo on Receipt','Print shop logo at top'],
            ] as[$key,$lbl,$desc]):?>
            <div class="sw-row">
              <div><div class="sw-label"><?=$lbl?></div><div class="sw-desc"><?=$desc?></div></div>
              <label class="tog ms-3">
                <input type="hidden" name="<?=$key?>" value="0">
                <input type="checkbox" name="<?=$key?>" value="1"
                       <?=($s[$key]??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <?php endforeach;?>
            <div class="mt-3">
              <label class="form-label">Receipt Footer Note</label>
              <textarea name="receipt_footer" class="form-control" rows="2"
                        placeholder="Thank you for shopping with us!"
                        <?=!$isEdit?'readonly':''?>><?=e($s['receipt_footer']??'')?></textarea>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div><!-- /pane-shop -->

  <!-- ════════════════════════════════════════════════════
       TAB: POS & TAX
       ════════════════════════════════════════════════════ -->
  <div class="s-pane" id="pane-pos">
    <div class="row g-3">

      <div class="col-lg-5">

        <!-- Tax -->
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-percent text-warning"></i>Tax Configuration</div>
          <div class="set-card-body">
            <div class="row g-3">
              <div class="col-6">
                <label class="form-label">Tax Name</label>
                <input type="text" name="tax_name" class="form-control"
                       value="<?=e($s['tax_name']??'VAT')?>" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-6">
                <label class="form-label">Tax Rate (%)</label>
                <div class="input-group">
                  <input type="number" name="tax_percent" class="form-control"
                         step="0.01" min="0" max="100"
                         value="<?=e($s['tax_percent']??'0')?>" <?=!$isEdit?'readonly':''?>>
                  <span class="input-group-text">%</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Daily Target -->
        <div class="set-card" style="border-color:#fde68a">
          <div class="set-card-head" style="background:#fffbeb;color:#92400e">
            <i class="bi bi-bullseye"></i>Daily Sales Target
          </div>
          <div class="set-card-body">
            <div class="sw-row">
              <div><div class="sw-label">Enable Daily Target</div>
                <div class="sw-desc">Show progress bar + congratulations popup on POS</div></div>
              <label class="tog ms-3">
                <input type="hidden" name="daily_target_enabled" value="0">
                <input type="checkbox" name="daily_target_enabled" value="1"
                       <?=($s['daily_target_enabled']??'0')==='1'?'checked':''?>
                       <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <div class="mt-3">
              <label class="form-label">Daily Sales Target Amount</label>
              <div class="input-group">
                <span class="input-group-text"><?=e($sym)?></span>
                <input type="number" name="daily_sales_target" class="form-control"
                       min="0" step="100"
                       value="<?=e($s['daily_sales_target']??'0')?>"
                       placeholder="e.g. 50000" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="form-text">
                When a cashier reaches this amount, a 🏆 congratulations popup appears!
              </div>
            </div>
          </div>
        </div>
        <div class="set-card" style="border-color:#fde68a">
          <div class="set-card-head" style="background:#fffbeb;color:#92400e">
            <i class="bi bi-credit-card-fill"></i>Card Payment Fee
          </div>
          <div class="set-card-body">
            <div class="mb-3">
              <label class="form-label">Card Processing Fee (%)</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-credit-card"></i></span>
                <input type="number" name="card_fee_percent" class="form-control"
                       step="0.01" min="0" max="10"
                       value="<?=e($s['card_fee_percent']??'2.5')?>"
                       placeholder="2.5" <?=!$isEdit?'readonly':''?>>
                <span class="input-group-text">%</span>
              </div>
              <div class="form-text">
                Automatically deducted from card payments before crediting the bank account.<br>
                e.g. Rs.1,960 card payment → Bank receives Rs.1,911.00 (−Rs.49.00 fee)
              </div>
            </div>
            <div class="p-2 rounded" style="background:#fffbeb;font-size:.72rem;color:#92400e">
              <i class="bi bi-info-circle me-1"></i>
              Each card payment records <strong>2 ledger entries</strong>:
              deposit (net amount) + fee withdrawal — both visible in the account ledger.
            </div>
          </div>
        </div>

        <!-- Silent Printer Setup -->
        <div class="set-card" style="border-color:#bbf7d0">
          <div class="set-card-head" style="background:#f0fdf4;color:#166534">
            <i class="bi bi-printer-fill"></i>Silent Printer Setup
            <span class="badge ms-auto" style="background:#16a34a;color:#fff;font-size:.6rem">Windows</span>
          </div>
          <div class="set-card-body">
            <p class="small text-muted mb-3">
              Remove the print dialog popup — send directly to the printer with one click.
            </p>

            <div class="d-flex gap-2 mb-3">
              <a href="<?=APP_URL?>/settings/test-print" target="_blank"
                 class="btn btn-success btn-sm fw-semibold">
                <i class="bi bi-printer me-1"></i>Test Print
              </a>
              <a href="<?=APP_URL?>/settings/kiosk-bat"
                 class="btn btn-primary btn-sm fw-semibold">
                <i class="bi bi-download me-1"></i>Download Silent Print Shortcut (.bat)
              </a>
            </div>

            <div class="p-3 rounded" style="background:#f0fdf4;border:1px solid #bbf7d0;font-size:.76rem">
              <div class="fw-bold mb-2" style="color:#166534">
                <i class="bi bi-check-circle me-1"></i>How to setup silent printing:
              </div>
              <ol class="mb-0" style="padding-left:16px;line-height:2">
                <li>Click <strong>"Download Silent Print Shortcut (.bat)"</strong> above</li>
                <li>Save the file to your Desktop</li>
                <li>Double-click the <strong>MJPOS_Silent_Print.bat</strong> file to open POS</li>
                <li>Chrome opens in App mode — receipts print <strong>silently with no dialog</strong></li>
                <li>Optional: Right-click the .bat → <em>Send to → Desktop (create shortcut)</em></li>
              </ol>
            </div>

            <div class="mt-2 p-2 rounded" style="background:#eff6ff;font-size:.7rem;color:#1d4ed8">
              <i class="bi bi-info-circle me-1"></i>
              <strong>How it works:</strong> The .bat file opens Chrome with <code>--kiosk-printing</code>
              flag which sends print jobs directly to the Windows default printer — no dialog shown.
              Set your thermal printer as <em>Windows Default Printer</em> first.
            </div>
          </div>
        </div>

        <!-- Background Printing -->
        <div class="set-card" style="border-color:#bfdbfe">
          <div class="set-card-head" style="background:#eff6ff;color:#1d4ed8">
            <i class="bi bi-printer-fill"></i>Background Printing System
          </div>
          <div class="set-card-body">
            <div class="sw-row">
              <div>
                <div class="sw-label">Enable Auto / Silent Printing</div>
                <div class="sw-desc">Automatically print receipt after a sale</div>
              </div>
              <label class="tog ms-3">
                <input type="hidden" name="print_auto_enabled" value="0">
                <input type="checkbox" name="print_auto_enabled" value="1"
                       <?=($s['print_auto_enabled']??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <div class="sw-row">
              <div>
                <div class="sw-label">Auto-close Print Window</div>
                <div class="sw-desc">Close receipt tab automatically after printing</div>
              </div>
              <label class="tog ms-3">
                <input type="hidden" name="print_auto_close" value="0">
                <input type="checkbox" name="print_auto_close" value="1"
                       <?=($s['print_auto_close']??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <div class="row g-3 mt-2">
              <div class="col-6">
                <label class="form-label">Paper Width</label>
                <select name="print_paper_width" class="form-select" <?=!$isEdit?'disabled':''?>>
                  <?php foreach(['58mm'=>'58mm (small thermal)','80mm'=>'80mm (standard)','a4'=>'A4'] as $v=>$l):?>
                  <option value="<?=$v?>" <?=($s['print_paper_width']??'80mm')===$v?'selected':''?>><?=$l?></option>
                  <?php endforeach;?>
                </select>
              </div>
              <div class="col-6">
                <label class="form-label">Copies per Sale</label>
                <select name="print_copies" class="form-select" <?=!$isEdit?'disabled':''?>>
                  <?php for($n=1;$n<=3;$n++):?>
                  <option value="<?=$n?>" <?=(int)($s['print_copies']??1)===$n?'selected':''?>><?=$n?> cop<?=$n>1?'ies':'y'?></option>
                  <?php endfor;?>
                </select>
              </div>
            </div>
            <div class="mt-3 p-2 rounded" style="background:#fffbeb;font-size:.72rem;color:#92400e">
              <i class="bi bi-lightbulb-fill me-1"></i>
              <strong>Silent print tip:</strong> Launch Chrome with <code>--kiosk-printing</code> for no dialog.
            </div>
          </div>
        </div>

      </div>

      <div class="col-lg-7">

        <!-- Payment → Account Mapping -->
        <div class="set-card" style="border-color:#a5b4fc">
          <div class="set-card-head" style="background:#eef2ff;color:#4338ca">
            <i class="bi bi-bank"></i>Payment → Account Mapping
            <span class="badge bg-indigo text-white ms-auto" style="background:#6366f1;font-size:.6rem">Finance</span>
          </div>
          <div class="set-card-body">
            <p class="text-muted small mb-3">
              When a sale is processed, the collected amount is automatically deposited
              into the linked finance account.
            </p>
            <?php foreach([
              ['cash',          'bi-cash-stack',       '#16a34a', 'Cash'],
              ['card',          'bi-credit-card-fill', '#1d4ed8', 'Card'],
              ['bank_transfer', 'bi-bank2',            '#0891b2', 'Bank Transfer'],
              ['mobile',        'bi-phone-fill',       '#7c3aed', 'Mobile Pay'],
            ] as[$key,$ico,$clr,$lbl]):
              $settingKey = 'pmt_account_'.$key;
              $current    = $s[$settingKey] ?? '';
            ?>
            <div class="pmt-row">
              <div class="pmt-label">
                <span style="color:<?=$clr?>;font-weight:700;font-size:.78rem">
                  <i class="bi <?=$ico?> me-1"></i><?=$lbl?>
                </span>
              </div>
              <select name="<?=$settingKey?>" class="form-select form-select-sm flex-grow-1"
                      <?=!$isEdit?'disabled':''?>>
                <option value="">— No account linked —</option>
                <?php foreach($finAccounts as $acc):
                  $ico2 = $acc['account_type']==='cash'?'[Cash]':'[Bank]';
                  $sel  = (string)$acc['id']===(string)$current?'selected':'';
                ?>
                <option value="<?=$acc['id']?>" <?=$sel?>><?=$ico2?> <?=e($acc['account_name'])?></option>
                <?php endforeach;?>
              </select>
              <?php if($current && $isEdit):?>
              <span style="color:#16a34a;font-size:.72rem;white-space:nowrap;margin-left:6px">Linked</span>
              <?php endif;?>
            </div>
            <?php endforeach;?>

            <div class="mt-3 p-2 rounded" style="background:#eef2ff;font-size:.72rem;color:#3730a3">
              <i class="bi bi-info-circle-fill me-1"></i>
              Card payment Rs.1,960 → auto-deposits to linked bank account + records in ledger.
            </div>
          </div>
        </div>

      </div>
    </div>
  </div><!-- /pane-pos -->

  <!-- ════════════════════════════════════════════════════
       TAB: STOCK
       ════════════════════════════════════════════════════ -->
  <div class="s-pane" id="pane-stock">
    <div class="row g-3">
      <div class="col-lg-5">
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-exclamation-triangle text-warning"></i>Stock Alerts</div>
          <div class="set-card-body">
            <div class="mb-4">
              <label class="form-label">Low Stock Alert Threshold</label>
              <div class="input-group">
                <input type="number" name="low_stock_alert" class="form-control"
                       min="0" value="<?=e($s['low_stock_alert']??'10')?>"
                       <?=!$isEdit?'readonly':''?>>
                <span class="input-group-text">units</span>
              </div>
              <div class="form-text">Products at or below this qty are flagged as Low Stock</div>
            </div>
            <div class="mb-4">
              <label class="form-label">Expiry Alert Days</label>
              <div class="input-group">
                <input type="number" name="expiry_alert_days" class="form-control"
                       min="0" value="<?=e($s['expiry_alert_days']??'30')?>"
                       <?=!$isEdit?'readonly':''?>>
                <span class="input-group-text">days before</span>
              </div>
              <div class="form-text">Warn when products expire within this many days</div>
            </div>
            <div class="danger-zone">
              <div class="sw-row" style="border:none;padding:0">
                <div>
                  <div class="sw-label text-danger">Allow Negative Stock</div>
                  <div class="sw-desc text-danger">Allow sales even when stock reaches zero</div>
                </div>
                <label class="tog ms-3">
                  <input type="hidden" name="allow_negative_stock" value="0">
                  <input type="checkbox" name="allow_negative_stock" value="1"
                         <?=($s['allow_negative_stock']??'0')=='1'?'checked':''?>
                         <?=!$isEdit?'disabled':''?>>
                  <span class="tog-slider" style="<?=($s['allow_negative_stock']??'0')=='1'?'background:#ef4444':''?>"></span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div><!-- /pane-stock -->

  <!-- ════════════════════════════════════════════════════
       TAB: BRANCHES
       ════════════════════════════════════════════════════ -->
  <div class="s-pane" id="pane-branch">
    <?php
    $branches = Database::fetchAll(
        "SELECT b.id, b.name, b.address, b.phone, b.email, b.is_main,
                COALESCE(b.status,'active') AS status,
                COUNT(u.id) AS user_count
         FROM branches b
         LEFT JOIN users u ON u.branch_id = b.id AND u.status='active'
         GROUP BY b.id ORDER BY b.is_main DESC, b.id ASC"
    );
    ?>
    <div class="row g-3">
      <!-- Branch List -->
      <div class="col-lg-7">
        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-building text-primary"></i>All Branches
            <span class="badge bg-primary ms-2" style="font-size:.6rem"><?= count($branches) ?></span>
            <a href="<?= APP_URL ?>/branches" class="btn btn-sm btn-outline-primary py-0 px-2 ms-auto">
              <i class="bi bi-arrow-up-right me-1"></i>Full Management
            </a>
          </div>
          <div class="set-card-body p-0">
            <?php if(empty($branches)): ?>
            <div class="text-center text-muted py-4 small">No branches yet</div>
            <?php else: ?>
            <table class="table table-sm mb-0" style="font-size:.8rem">
              <thead style="background:#f8fafc;font-size:.68rem;text-transform:uppercase;color:#6b7280">
                <tr>
                  <th class="ps-3 py-2">Branch</th>
                  <th>Location</th>
                  <th class="text-center">Users</th>
                  <th class="text-center">Status</th>
                  <?php if($isEdit): ?><th class="pe-3"></th><?php endif; ?>
                </tr>
              </thead>
              <tbody>
                <?php foreach($branches as $br): ?>
                <tr>
                  <td class="ps-3 py-2">
                    <div class="fw-semibold">
                      <?= e($br['name']) ?>
                      <?php if($br['is_main']): ?>
                      <span class="badge bg-warning text-dark ms-1" style="font-size:.55rem">MAIN</span>
                      <?php endif; ?>
                    </div>
                    <div class="text-muted" style="font-size:.68rem"><?= e($br['phone'] ?? '') ?></div>
                  </td>
                  <td class="small text-muted"><?= e($br['address'] ?? '—') ?></td>
                  <td class="text-center">
                    <span class="badge bg-primary" style="font-size:.65rem"><?= $br['user_count'] ?></span>
                  </td>
                  <td class="text-center">
                    <span class="badge <?= ($br['status']??'active')==='active' ? 'bg-success' : 'bg-secondary' ?>"
                          style="font-size:.65rem">
                      <?= $br['status'] ?? 'active' ?>
                    </span>
                  </td>
                  <?php if($isEdit): ?>
                  <td class="pe-3">
                    <a href="<?= APP_URL ?>/branches/edit/<?= $br['id'] ?>"
                       class="btn btn-sm btn-outline-secondary py-0 px-2" style="font-size:.68rem">
                      <i class="bi bi-pencil"></i>
                    </a>
                  </td>
                  <?php endif; ?>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <!-- Add Branch -->
      <?php if($isEdit): ?>
      <div class="col-lg-5">
        <div class="set-card" style="border-color:#bfdbfe">
          <div class="set-card-head" style="background:#eff6ff;color:#1e40af">
            <i class="bi bi-plus-circle-fill"></i>Add New Branch
          </div>
          <div class="set-card-body">
            <div id="branchAddFields">
              <input type="hidden" id="branchCsrfToken" value="<?= e(Auth::csrfToken()) ?>">
              <div class="mb-3">
                <label class="form-label">Branch Name <span class="text-danger">*</span></label>
                <input type="text" name="name" class="form-control"
                       placeholder="e.g. Main Branch, Colombo Branch"
                       autocomplete="organization">
              </div>
              <div class="mb-3">
                <label class="form-label">Address / Location</label>
                <textarea name="address" class="form-control" rows="2"
                          placeholder="Branch address..."></textarea>
              </div>
              <div class="row g-2 mb-3">
                <div class="col-6">
                  <label class="form-label">Phone</label>
                  <input type="text" name="phone" class="form-control" placeholder="0771234567">
                </div>
                <div class="col-6">
                  <label class="form-label">Email</label>
                  <input type="email" name="email" class="form-control" placeholder="branch@email.com">
                </div>
              </div>
              <div class="mb-3">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" name="is_main" value="1" id="isMainBranch">
                  <label class="form-check-label fw-semibold" for="isMainBranch">
                    Set as Main Branch
                  </label>
                </div>
                <div class="form-text">Main branch eke all existing main flags clear wenawa</div>
              </div>
              <button type="button" class="btn btn-primary fw-semibold w-100" onclick="submitBranchForm(this)">
                <i class="bi bi-plus-circle me-1"></i>Add Branch
              </button>
            </div>
          </div>
        </div>
      </div>
      <?php endif; ?>

    </div>
  </div><!-- /pane-branch -->
  <div class="s-pane" id="pane-activity">
    <div class="row g-3">

      <div class="col-lg-6">

        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-journal-text text-info"></i>Activity Log Settings
            <a href="<?=APP_URL?>/logs/activity" class="btn btn-sm btn-outline-info py-0 px-2 ms-auto">
              <i class="bi bi-eye me-1"></i>View Logs
            </a>
          </div>
          <div class="set-card-body">
            <div class="sw-row">
              <div><div class="sw-label">Enable Activity Logging</div><div class="sw-desc">Track all user actions in the system</div></div>
              <label class="tog ms-3">
                <input type="hidden" name="activity_log_enabled" value="0">
                <input type="checkbox" name="activity_log_enabled" value="1"
                       <?=($s['activity_log_enabled']??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <div class="mt-3">
              <label class="form-label">Log Retention Period</label>
              <div class="input-group">
                <input type="number" name="activity_log_retention_days"
                       class="form-control" min="7" max="730"
                       value="<?=e($s['activity_log_retention_days']??'90')?>"
                       <?=!$isEdit?'readonly':''?>>
                <span class="input-group-text">days</span>
              </div>
              <div class="form-text">Logs older than this are automatically deleted</div>
            </div>
          </div>
        </div>

        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-funnel text-primary"></i>What to Log</div>
          <div class="set-card-body">
            <?php foreach([
              ['log_sales',    'bi-receipt',    'text-success', 'Sales & Invoices',   'Record sale create, update, cancel'],
              ['log_purchases','bi-truck',      'text-info',    'Purchases',           'Record purchase orders & receipts'],
              ['log_expenses', 'bi-wallet2',    'text-danger',  'Expenses',            'Record expense entries'],
              ['log_auth',     'bi-key',        'text-warning', 'Logins & Logouts',    'Track authentication events'],
              ['log_stock',    'bi-boxes',      'text-warning', 'Stock Adjustments',   'Record stock in/out adjustments'],
              ['log_settings', 'bi-gear',       'text-secondary','Settings Changes',   'Record all settings updates'],
            ] as[$key,$ico,$cls,$lbl,$desc]):?>
            <div class="sw-row">
              <div class="d-flex align-items-center gap-2">
                <i class="bi <?=$ico?> <?=$cls?> fs-5 flex-shrink-0"></i>
                <div><div class="sw-label"><?=$lbl?></div><div class="sw-desc"><?=$desc?></div></div>
              </div>
              <label class="tog ms-3">
                <input type="hidden" name="<?=$key?>" value="0">
                <input type="checkbox" name="<?=$key?>" value="1"
                       <?=($s[$key]??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>
            <?php endforeach;?>
          </div>
        </div>

      </div>

      <div class="col-lg-4">
        <div class="set-card">
          <div class="set-card-head"><i class="bi bi-bar-chart text-info"></i>Log Statistics</div>
          <div class="set-card-body p-0 px-3">
            <?php foreach([
              ['Total Log Entries',    number_format($logStats['total']),     ''],
              ['Last 24 Hours',        number_format($logStats['today']),     'text-success'],
              ['Logins Today',         (string)$logStats['logins_today'],     ''],
              ['Failed Attempts',      (string)$logStats['failed_today'],     $logStats['failed_today']>0?'text-danger':''],
              ['Retention Period',     $retention.' days',                    ''],
              ['Last Entry',           $logStats['last_entry']?fDate($logStats['last_entry'],'d M Y H:i'):'—','text-muted'],
            ] as[$lbl,$val,$cls]):?>
            <div class="st-row">
              <span class="text-muted small"><?=$lbl?></span>
              <span class="st-val <?=$cls?>"><?=$val?></span>
            </div>
            <?php endforeach;?>
          </div>
          <div class="p-3 border-top">
            <a href="<?=APP_URL?>/logs/activity" class="btn btn-outline-info btn-sm w-100 fw-semibold">
              <i class="bi bi-journal-text me-1"></i>Open Activity Log
            </a>
          </div>
        </div>
      </div>

    </div>
  </div><!-- /pane-activity -->

  <!-- ════════════════════════════════════════════════════
       TAB: ONLINE USERS
       ════════════════════════════════════════════════════ -->
  <div class="s-pane" id="pane-online">
    <div class="row g-3">

      <div class="col-lg-5">
        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-people-fill text-success"></i>Online User Settings
            <a href="<?=APP_URL?>/logs/online" class="btn btn-sm btn-outline-success py-0 px-2 ms-auto">
              <i class="bi bi-eye me-1"></i>View
            </a>
          </div>
          <div class="set-card-body">
            <div class="sw-row">
              <div><div class="sw-label">Enable Online Tracking</div><div class="sw-desc">Show which users are currently active</div></div>
              <label class="tog ms-3">
                <input type="hidden" name="show_online_users" value="0">
                <input type="checkbox" name="show_online_users" value="1"
                       <?=($s['show_online_users']??'1')=='1'?'checked':''?> <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>

            <div class="mt-3 p-3 rounded" style="background:#f8fafc;border:1px solid #e2e8f0">
              <div class="fw-bold small mb-3 text-muted text-uppercase" style="font-size:.68rem;letter-spacing:.06em">
                Status Thresholds
              </div>
              <div class="mb-3">
                <label class="form-label d-flex align-items-center gap-2">
                  <span class="rounded-circle d-inline-block" style="width:10px;height:10px;background:#198754;flex-shrink:0"></span>
                  Online threshold
                </label>
                <div class="input-group input-group-sm">
                  <input type="number" name="online_timeout_online" class="form-control" min="1" max="30"
                         value="<?=e($s['online_timeout_online']??'2')?>" <?=!$isEdit?'readonly':''?>>
                  <span class="input-group-text">min</span>
                </div>
                <div class="form-text">Active within this → <strong>Online</strong></div>
              </div>
              <div class="mb-3">
                <label class="form-label d-flex align-items-center gap-2">
                  <span class="rounded-circle d-inline-block" style="width:10px;height:10px;background:#fd7e14;flex-shrink:0"></span>
                  Away threshold
                </label>
                <div class="input-group input-group-sm">
                  <input type="number" name="online_timeout_away" class="form-control" min="2" max="60"
                         value="<?=e($s['online_timeout_away']??'15')?>" <?=!$isEdit?'readonly':''?>>
                  <span class="input-group-text">min</span>
                </div>
                <div class="form-text">Active within this → <strong>Away</strong></div>
              </div>
              <div>
                <label class="form-label d-flex align-items-center gap-2">
                  <i class="bi bi-arrow-repeat text-primary" style="font-size:.85rem"></i>
                  Refresh interval
                </label>
                <div class="input-group input-group-sm">
                  <input type="number" name="online_poll_interval" class="form-control" min="3" max="60"
                         value="<?=e($s['online_poll_interval']??'5')?>" <?=!$isEdit?'readonly':''?>>
                  <span class="input-group-text">sec</span>
                </div>
                <div class="form-text">How often the Online page auto-refreshes</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-5">
        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-activity text-success"></i>Live Status
            <span class="badge bg-success ms-1" style="font-size:.65rem"><?=$onlineCount?> Online</span>
            <?php if($awayCount):?>
            <span class="badge bg-warning text-dark ms-1" style="font-size:.65rem"><?=$awayCount?> Away</span>
            <?php endif;?>
          </div>
          <?php if(!empty($onlineUsers)):?>
          <table class="table table-sm mb-0">
            <thead style="background:#f8fafc;font-size:.68rem;color:#9ca3af;text-transform:uppercase">
              <tr>
                <th class="ps-3 py-2">User</th>
                <th>Branch</th>
                <th>Status</th>
                <th class="pe-3">Since</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($onlineUsers as $u):
                $sec=$u['sec_ago'];
                $ago=$sec<60?"{$sec}s":floor($sec/60)."m";
                $dotColor=['online'=>'#198754','away'=>'#fd7e14','offline'=>'#adb5bd'][$u['status']]??'#adb5bd';
                $stLabel=['online'=>'Online','away'=>'Away','offline'=>'Offline'][$u['status']]??'Offline';
              ?>
              <tr>
                <td class="ps-3 py-2">
                  <div class="small fw-semibold"><?=e($u['name'])?></div>
                  <div class="text-muted" style="font-size:.65rem"><?=e(str_replace('_',' ',$u['role_name']))?></div>
                </td>
                <td class="small text-muted"><?=e($u['branch_name'])?></td>
                <td>
                  <div class="d-flex align-items-center gap-1 small">
                    <span class="rounded-circle" style="width:8px;height:8px;background:<?=$dotColor?>;display:inline-block"></span>
                    <span style="color:<?=$dotColor?>;font-weight:600"><?=$stLabel?></span>
                  </div>
                </td>
                <td class="small text-muted pe-3"><?=$ago?></td>
              </tr>
              <?php endforeach;?>
            </tbody>
          </table>
          <?php else:?>
          <div class="text-center py-5 text-muted">
            <i class="bi bi-moon d-block fs-2 mb-2 opacity-25"></i>
            <div class="small">No active sessions in the last 15 min</div>
          </div>
          <?php endif;?>
          <div class="p-3 border-top">
            <a href="<?=APP_URL?>/logs/online" class="btn btn-outline-success btn-sm w-100 fw-semibold">
              <i class="bi bi-people me-1"></i>Open Online Users Page
            </a>
          </div>
        </div>
      </div>

    </div>
  </div><!-- /pane-online -->

  <!-- ════════════════════════════════════════════════════
       TAB: SMS
       ════════════════════════════════════════════════════ -->
  <div class="s-pane" id="pane-sms">
    <div class="row g-3">

      <!-- Left: Config -->
      <div class="col-lg-6">

        <div class="set-card" style="border-color:#86efac">
          <div class="set-card-head" style="background:#f0fdf4;color:#166534">
            <i class="bi bi-chat-dots-fill"></i>SMSlenz Gateway
            <span class="badge ms-auto" style="background:#16a34a;color:#fff;font-size:.6rem">Active</span>
          </div>
          <div class="set-card-body">

            <!-- Enable toggle -->
            <div class="sw-row">
              <div>
                <div class="sw-label">Enable SMS Notifications</div>
                <div class="sw-desc">Auto-send bill SMS to customer after every sale</div>
              </div>
              <label class="tog ms-3">
                <input type="hidden" name="sms_enabled" value="0">
                <input type="checkbox" name="sms_enabled" value="1"
                       <?=($s['sms_enabled']??'0')==='1'?'checked':''?>
                       <?=!$isEdit?'disabled':''?>>
                <span class="tog-slider"></span>
              </label>
            </div>

            <div class="sec-divider mt-3">API Credentials</div>

            <div class="row g-3 mb-3">
              <div class="col-5">
                <label class="form-label">User ID</label>
                <input type="text" name="sms_user_id" class="form-control"
                       value="<?=e($s['sms_user_id']??'2141')?>"
                       <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="col-7">
                <label class="form-label">Sender ID</label>
                <input type="text" name="sms_sender_id" class="form-control"
                       value="<?=e($s['sms_sender_id']??'SMSlenzDEMO')?>"
                       placeholder="SMSlenzDEMO" <?=!$isEdit?'readonly':''?>>
                <div class="form-text">Use approved sender ID in production</div>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">API Key</label>
              <input type="text" name="sms_api_key" class="form-control"
                     value="<?=e($s['sms_api_key']??'')?>"
                     placeholder="191e976c-e539-4571-991b-adde535493d3"
                     <?=!$isEdit?'readonly':''?>>
            </div>

            <div class="mb-3">
              <label class="form-label">API Base URL</label>
              <input type="text" name="sms_api_url" class="form-control"
                     value="<?=e($s['sms_api_url']??'https://smslenz.lk/api')?>"
                     <?=!$isEdit?'readonly':''?>>
            </div>

            <div class="sec-divider mt-3">Password Reset</div>
            <div class="mb-3">
              <label class="form-label">Admin Reset Phone Number</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-phone"></i></span>
                <input type="text" name="admin_reset_phone" class="form-control"
                       value="<?=e($s['admin_reset_phone']??'')?>"
                       placeholder="0771234567" <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="form-text">OTP sent to this number when users reset password</div>
            </div>

            <div class="sec-divider mt-1">Daily Report SMS</div>
            <div class="mb-3">
              <label class="form-label">Admin Report Phone Number</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-phone-fill"></i></span>
                <input type="text" name="admin_report_phone" class="form-control"
                       value="<?=e($s['admin_report_phone']??'')?>"
                       placeholder="0771234567 (same as reset or different)"
                       <?=!$isEdit?'readonly':''?>>
              </div>
              <div class="form-text">
                Daily summary SMS sent to this number. Leave blank to use Reset Phone above.
              </div>
            </div>
            <div class="p-2 rounded" style="background:#f0fdf4;border:1px solid #bbf7d0;font-size:.72rem;color:#166534">
              <i class="bi bi-clock me-1"></i>
              <strong>Auto-send daily report:</strong> Setup cPanel cron job to run daily at 9 PM:
              <br><code style="font-size:.68rem">0 21 * * * php /home3/mjposliv/public_html/kussiya.mjpos.live/mjpos/public/cron/daily_report.php</code>
            </div>

          </div>
        </div>
        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-chat-text text-info"></i>Message Template
          </div>
          <div class="set-card-body">
            <textarea name="sms_template" class="form-control" rows="4"
                      <?=!$isEdit?'readonly':''?>><?=e($s['sms_template']??'Hi {customer}, Invoice {invoice_no} | Total: Rs.{total} | Paid: Rs.{paid} | Thank you! - {shop_name}')?></textarea>
            <div class="form-text mt-2">
              <strong>Available placeholders:</strong><br>
              <code>{invoice_no}</code> <code>{customer}</code>
              <code>{total}</code> <code>{paid}</code>
              <code>{change}</code> <code>{balance}</code>
              <code>{shop_name}</code> <code>{date}</code>
              <code>{currency}</code>
            </div>
            <div class="mt-2 p-2 rounded" style="background:#f8fafc;border:1px solid #e2e8f0;font-size:.72rem;color:#374151">
              <strong>Preview:</strong><br>
              Hi Kamal, Invoice INV-20260714-0007 | Total: Rs.695.00 | Paid: Rs.1,000.00 | Thank you! - KUSSIYA
            </div>
          </div>
        </div>

      </div><!-- /col -->

      <!-- Right: Status + Test -->
      <div class="col-lg-5">

        <!-- Account Status -->
        <div class="set-card mb-3">
          <div class="set-card-head">
            <i class="bi bi-activity text-success"></i>Account Status
            <button type="button" onclick="checkSmsStatus()"
                    class="btn btn-sm btn-outline-success py-0 px-2 ms-auto">
              <i class="bi bi-arrow-repeat me-1"></i>Check
            </button>
          </div>
          <div class="set-card-body" id="smsStatusBox">
            <div class="text-muted small text-center py-3">
              Click "Check" to fetch live account status
            </div>
          </div>
        </div>

        <!-- Test SMS -->
        <div class="set-card">
          <div class="set-card-head">
            <i class="bi bi-send text-primary"></i>Send Test SMS
          </div>
          <div class="set-card-body">
            <div class="mb-3">
              <label class="form-label small fw-semibold">Test Phone Number</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-phone"></i></span>
                <input type="text" id="testSmsPhone" class="form-control"
                       placeholder="0771234567 or +94771234567">
              </div>
            </div>
            <button type="button" onclick="sendTestSms()"
                    class="btn btn-primary btn-sm fw-semibold w-100">
              <i class="bi bi-send me-1"></i>Send Test SMS
            </button>
            <div id="testSmsResult" class="mt-2"></div>
          </div>
        </div>

        <!-- How it works -->
        <div class="mt-3 p-3 rounded" style="background:#eff6ff;border:1px solid #bfdbfe;font-size:.75rem;color:#1e40af">
          <div class="fw-bold mb-2"><i class="bi bi-info-circle me-1"></i>How SMS works:</div>
          <ul class="mb-0" style="padding-left:14px;line-height:2">
            <li><strong>Registered customer</strong> with phone → SMS auto-sent</li>
            <li><strong>Walk-in</strong> with phone entered in POS → SMS auto-sent</li>
            <li><strong>Walk-in</strong> no phone → skipped (no SMS)</li>
            <li>Print receipt works <strong>independently</strong> — SMS is additional</li>
          </ul>
        </div>

      </div><!-- /col -->
    </div>
  </div><!-- /pane-sms -->

  <!-- Save bottom -->
  <?php if($isEdit):?>
  <div class="d-flex justify-content-end gap-2 mt-4 pt-3 border-top">
    <a href="<?=APP_URL?>/settings" class="btn btn-outline-secondary">
      <i class="bi bi-arrow-counterclockwise me-1"></i>Discard
    </a>
    <button type="submit" class="btn btn-primary fw-semibold px-5">
      <i class="bi bi-check-circle me-1"></i>Save All Settings
    </button>
  </div>
  <?php endif;?>

</form>

<script>
function switchTab(id, btn) {
  document.querySelectorAll('.s-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.s-tab').forEach(b => b.classList.remove('active'));
  document.getElementById('pane-'+id).classList.add('active');
  btn.classList.add('active');
}

// SMS check account status
function checkSmsStatus() {
  const box = document.getElementById('smsStatusBox');
  box.innerHTML = '<div class="text-center text-muted small py-2"><i class="bi bi-arrow-repeat"></i> Checking...</div>';
  fetch('<?=APP_URL?>/settings/sms-status')
    .then(r => r.json())
    .then(d => {
      if (d.success && d.data) {
        const data = d.data;
        box.innerHTML = `
          <div class="st-row"><span class="text-muted small">Status</span>
            <span class="st-val" style="color:${data.status==='active'?'#16a34a':'#dc2626'}">${data.status}</span></div>
          <div class="st-row"><span class="text-muted small">SMS Balance</span>
            <span class="st-val text-success">${data.sms_credit_balance}</span></div>
          <div class="st-row"><span class="text-muted small">Plan</span>
            <span class="st-val">${data.active_plan || '—'}</span></div>
          <div class="st-row"><span class="text-muted small">Total Contacts</span>
            <span class="st-val">${(data.total_contacts||0).toLocaleString()}</span></div>
        `;
      } else {
        box.innerHTML = '<div class="alert alert-danger small py-2 mb-0">'+( d.message || 'Failed to connect')+'</div>';
      }
    })
    .catch(() => {
      box.innerHTML = '<div class="alert alert-danger small py-2 mb-0">Network error — check API URL</div>';
    });
}

// Send test SMS
function sendTestSms() {
  const phone  = document.getElementById('testSmsPhone').value.trim();
  const result = document.getElementById('testSmsResult');
  if (!phone) { result.innerHTML='<div class="alert alert-warning small py-2 mb-0">Enter a phone number</div>'; return; }
  result.innerHTML = '<div class="text-muted small"><i class="bi bi-send"></i> Sending...</div>';
  fetch('<?=APP_URL?>/settings/sms-test?phone='+encodeURIComponent(phone))
    .then(r => r.json())
    .then(d => {
      result.innerHTML = `<div class="alert alert-${d.success?'success':'danger'} small py-2 mb-0">
        ${d.message}${d.balance?' | Balance: Rs.'+d.balance:''}
      </div>`;
    })
    .catch(() => result.innerHTML='<div class="alert alert-danger small py-2 mb-0">Request failed</div>');
}
// Toggle slider colour
document.querySelectorAll('.tog-slider').forEach(slider => {
  const cb = slider.previousElementSibling;
  if (cb && cb.type === 'checkbox') {
    slider.style.background = cb.checked ? '#3b82f6' : '';
    cb.addEventListener('change', function() {
      slider.style.background = this.checked ? '#3b82f6' : '';
    });
  }
});

function submitBranchForm(button) {
  const box = document.getElementById('branchAddFields');
  if (!box) return;

  const required = box.querySelector('input[name="name"]');
  if (!required || !required.value.trim()) {
    required?.focus();
    required?.reportValidity();
    return;
  }

  const data = new FormData();
  box.querySelectorAll('input, textarea, select').forEach(el => {
    if (!el.name || el.disabled) return;
    if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) return;
    data.append(el.name, el.value);
  });

  const csrf = document.querySelector('#settingsForm input[name="csrf_token"], #settingsForm input[name="_token"]');
  if (csrf) data.append(csrf.name, csrf.value);

  const oldHtml = button.innerHTML;
  button.disabled = true;
  button.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Adding...';

  fetch('<?= APP_URL ?>/branches/create', {
    method: 'POST',
    body: data,
    credentials: 'same-origin'
  }).then(response => {
    if (response.redirected) {
      window.location.href = response.url;
      return;
    }
    if (!response.ok) throw new Error('Branch save failed');
    window.location.reload();
  }).catch(error => {
    alert(error.message || 'Unable to add branch');
    button.disabled = false;
    button.innerHTML = oldHtml;
  });
}

function toggleBankFields(v) {
  document.getElementById('bankFields').style.display = v==='bank' ? 'block' : 'none';
}
</script>