<?php use App\Helpers\Helper;

$tabIcons = [
  'general'  => ['icon'=>'bi-building','color'=>'blue','label'=>'General'],
  'content'  => ['icon'=>'bi-pencil-square','color'=>'green','label'=>'Site Content'],
  'email'    => ['icon'=>'bi-envelope','color'=>'purple','label'=>'Email / SMTP'],
  'sms'      => ['icon'=>'bi-chat-dots','color'=>'green','label'=>'SMS Gateway'],
  'payment'  => ['icon'=>'bi-credit-card','color'=>'orange','label'=>'Payments'],
  'social'   => ['icon'=>'bi-share','color'=>'teal','label'=>'Social Media'],
  'seo'      => ['icon'=>'bi-search','color'=>'indigo','label'=>'SEO'],
];
$firstGroup = array_key_first($grouped ?? []);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">System Settings</h1>
    <p class="text-muted small mb-0">Configure your application preferences and integrations</p>
  </div>
  <div class="d-flex gap-2">
    <span class="badge bg-success-subtle text-success px-3 py-2"><i class="bi bi-check-circle me-1"></i>System Active</span>
  </div>
</div>

<div class="row g-4">
  <!-- Left Tabs Nav -->
  <div class="col-lg-3">
    <div class="settings-nav-card">
      <div class="settings-nav-header">
        <i class="bi bi-gear-fill me-2"></i>Settings Menu
      </div>
      <nav class="settings-nav" id="settingsTabs" role="tablist">
        <?php foreach ($grouped as $group => $settings):
          $meta = $tabIcons[$group] ?? ['icon'=>'bi-sliders','color'=>'blue','label'=>ucfirst($group)];
        ?>
        <a class="settings-nav-link <?= $group===$firstGroup?'active':'' ?>"
           id="tab-<?= $group ?>-tab"
           data-bs-toggle="pill"
           href="#tab-<?= $group ?>"
           role="tab">
          <span class="settings-nav-icon stat-icon-wrap <?= $meta['color'] ?>">
            <i class="bi <?= $meta['icon'] ?>"></i>
          </span>
          <span><?= $meta['label'] ?></span>
          <span class="ms-auto badge bg-light text-muted"><?= count($settings) ?></span>
        </a>
        <?php endforeach; ?>
        <!-- Logo tab -->
        <a class="settings-nav-link"
           id="tab-logo-tab"
           data-bs-toggle="pill"
           href="#tab-logo"
           role="tab">
          <span class="settings-nav-icon stat-icon-wrap yellow">
            <i class="bi bi-image"></i>
          </span>
          <span>Logo & Branding</span>
        </a>
      </nav>
    </div>
  </div>

  <!-- Right Tab Content -->
  <div class="col-lg-9">
    <form method="POST" action="<?= APP_URL ?>/admin/settings" enctype="multipart/form-data">
      <?= Helper::csrf() ?>
      <div class="tab-content">
        <?php foreach ($grouped as $group => $settings):
          $meta = $tabIcons[$group] ?? ['icon'=>'bi-sliders','color'=>'blue','label'=>ucfirst($group)];
        ?>
        <div class="tab-pane fade <?= $group===$firstGroup?'show active':'' ?>" id="tab-<?= $group ?>" role="tabpanel">
          <div class="form-card">
            <!-- Section Header -->
            <div class="settings-section-header mb-4">
              <div class="d-flex align-items-center gap-3">
                <div class="settings-icon-lg stat-icon-wrap <?= $meta['color'] ?>">
                  <i class="bi <?= $meta['icon'] ?> fs-4"></i>
                </div>
                <div>
                  <h5 class="fw-700 mb-0"><?= $meta['label'] ?> Settings</h5>
                  <p class="text-muted small mb-0">Manage your <?= strtolower($meta['label']) ?> configuration</p>
                </div>
              </div>
              <hr class="mt-3 mb-4">
            </div>
            <!-- Fields -->
            <?php if ($group === 'content'): ?>
            <?php
              $ct = [];
              foreach ($settings as $k => $s) { $ct[$k] = $s['value'] ?? ''; }
              $contentSections = [
                'hero' => [
                  'label' => 'Hero Section',
                  'icon'  => 'bi-house-heart-fill',
                  'color' => '#2563eb',
                  'fields' => [
                    ['key'=>'hero_badge',         'label'=>'Badge / Pill Text',      'type'=>'text',     'hint'=>'Small pill above the title'],
                    ['key'=>'hero_title',         'label'=>'Hero Title (HTML ok)',   'type'=>'textarea', 'hint'=>'Wrap highlighted word in <span class="highlight">...</span>'],
                    ['key'=>'hero_subtitle',      'label'=>'Hero Subtitle',          'type'=>'textarea', 'hint'=>''],
                    ['key'=>'hero_cta_primary',   'label'=>'Primary Button Text',    'type'=>'text',     'hint'=>''],
                    ['key'=>'hero_cta_secondary', 'label'=>'Secondary Button Text',  'type'=>'text',     'hint'=>''],
                    ['key'=>'hero_floating_from', 'label'=>'Floating Card — Price',  'type'=>'text',     'hint'=>'e.g. From TZS 25,000 /day'],
                  ],
                ],
                'buildings' => [
                  'label' => 'Buildings Section',
                  'icon'  => 'bi-buildings-fill',
                  'color' => '#1a3c5e',
                  'fields' => [
                    ['key'=>'buildings_tag',      'label'=>'Section Tag',    'type'=>'text',     'hint'=>''],
                    ['key'=>'buildings_title',    'label'=>'Section Title',  'type'=>'text',     'hint'=>''],
                    ['key'=>'buildings_subtitle', 'label'=>'Subtitle',       'type'=>'textarea', 'hint'=>''],
                  ],
                ],
                'features' => [
                  'label' => 'Features / Why Us',
                  'icon'  => 'bi-stars',
                  'color' => '#7c3aed',
                  'fields' => [
                    ['key'=>'features_tag',      'label'=>'Section Tag',    'type'=>'text',     'hint'=>''],
                    ['key'=>'features_title',    'label'=>'Section Title',  'type'=>'text',     'hint'=>''],
                    ['key'=>'features_subtitle', 'label'=>'Subtitle',       'type'=>'textarea', 'hint'=>''],
                  ],
                ],
                'cta' => [
                  'label' => 'Bottom CTA Section',
                  'icon'  => 'bi-megaphone-fill',
                  'color' => '#d97706',
                  'fields' => [
                    ['key'=>'cta_title',    'label'=>'CTA Title',    'type'=>'text',     'hint'=>''],
                    ['key'=>'cta_subtitle', 'label'=>'CTA Subtitle', 'type'=>'textarea', 'hint'=>''],
                    ['key'=>'cta_bullet_1', 'label'=>'Bullet Point 1','type'=>'text',    'hint'=>''],
                    ['key'=>'cta_bullet_2', 'label'=>'Bullet Point 2','type'=>'text',    'hint'=>''],
                    ['key'=>'cta_bullet_3', 'label'=>'Bullet Point 3','type'=>'text',    'hint'=>''],
                  ],
                ],
                'about' => [
                  'label' => 'About Page',
                  'icon'  => 'bi-info-circle-fill',
                  'color' => '#0891b2',
                  'fields' => [
                    ['key'=>'about_title',    'label'=>'Page Title',   'type'=>'text',     'hint'=>''],
                    ['key'=>'about_subtitle', 'label'=>'Subtitle',     'type'=>'textarea', 'hint'=>''],
                    ['key'=>'about_body',     'label'=>'Body Text',    'type'=>'textarea', 'hint'=>''],
                  ],
                ],
                'contact' => [
                  'label' => 'Contact Page',
                  'icon'  => 'bi-telephone-fill',
                  'color' => '#16a34a',
                  'fields' => [
                    ['key'=>'contact_title',    'label'=>'Page Title', 'type'=>'text',     'hint'=>''],
                    ['key'=>'contact_subtitle', 'label'=>'Subtitle',   'type'=>'textarea', 'hint'=>''],
                  ],
                ],
              ];
            ?>
            <!-- Site Photos Upload -->
            <div class="mb-4">
              <div class="d-flex align-items-center gap-2 mb-3">
                <div class="rounded-2 d-flex align-items-center justify-content-center flex-shrink-0" style="width:32px;height:32px;background:#0891b218">
                  <i class="bi bi-images" style="color:#0891b2;font-size:1rem"></i>
                </div>
                <h6 class="fw-700 mb-0">Site Photos</h6>
              </div>
              <div class="row g-4 ps-2">
                <?php
                $siteImages = [
                  ['key'=>'hero_image',    'label'=>'Hero Right-Side Photo',   'hint'=>'Main photo shown on the right of the hero section (recommended: 700×500px)'],
                  ['key'=>'hero_bg_image', 'label'=>'Hero Background Texture', 'hint'=>'Full-width background image behind the hero (recommended: 1920×1080px)'],
                  ['key'=>'about_image',   'label'=>'About Page Photo',        'hint'=>'Photo shown on the about page beside the text (recommended: 600×500px)'],
                ];
                foreach ($siteImages as $img):
                  $currentVal = $ct[$img['key']] ?? '';
                  $currentSrc = $currentVal
                    ? APP_URL . '/assets/images/' . $currentVal
                    : '';
                ?>
                <div class="col-md-4">
                  <div class="border rounded-3 p-3 h-100" style="background:#f8fafc">
                    <div class="fw-600 small mb-2"><?= $img['label'] ?></div>
                    <div id="preview_wrap_<?= $img['key'] ?>" class="mb-2 position-relative">
                    <?php if ($currentSrc): ?>
                      <img src="<?= $currentSrc ?>?v=<?= time() ?>" id="preview_<?= $img['key'] ?>"
                           class="rounded-2 w-100" style="height:140px;object-fit:cover;border:1px solid #e2e8f0"
                           onerror="this.style.display='none'">
                      <span class="badge bg-success position-absolute top-0 end-0 m-1" style="font-size:.65rem">Active</span>
                    <?php else: ?>
                      <div id="placeholder_<?= $img['key'] ?>" class="d-flex align-items-center justify-content-center rounded-2 bg-light" style="height:140px;border:2px dashed #cbd5e1">
                        <div class="text-center text-muted small"><i class="bi bi-image fs-3 d-block mb-1"></i>No image set</div>
                      </div>
                    <?php endif; ?>
                    </div>
                    <?php if ($currentSrc): ?>
                    <button type="button" class="btn btn-sm btn-outline-danger w-100 mb-2"
                            onclick="removeSiteImg('<?= $img['key'] ?>')">
                      <i class="bi bi-trash me-1"></i>Remove Photo
                    </button>
                    <?php endif; ?>
                    <input type="file" id="file_<?= $img['key'] ?>" class="form-control form-control-sm mb-2"
                           accept="image/jpeg,image/png,image/webp"
                           onchange="previewSiteImg(this,'<?= $img['key'] ?>')">
                    <div class="form-text mb-2"><?= $img['hint'] ?></div>
                    <button type="button" class="btn btn-sm btn-primary w-100"
                            onclick="uploadSiteImg('<?= $img['key'] ?>')">
                      <i class="bi bi-cloud-upload me-1"></i>Upload
                    </button>
                    <div id="msg_<?= $img['key'] ?>" class="mt-2 small"></div>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
            </div>
            <hr class="my-3">

            <?php foreach ($contentSections as $sid => $sec): ?>
            <div class="mb-4">
              <div class="d-flex align-items-center gap-2 mb-3">
                <div class="rounded-2 d-flex align-items-center justify-content-center flex-shrink-0" style="width:32px;height:32px;background:<?= $sec['color'] ?>18">
                  <i class="bi <?= $sec['icon'] ?>" style="color:<?= $sec['color'] ?>;font-size:1rem"></i>
                </div>
                <h6 class="fw-700 mb-0"><?= $sec['label'] ?></h6>
              </div>
              <div class="row g-3 ps-2">
                <?php foreach ($sec['fields'] as $f): ?>
                <div class="col-md-<?= $f['type']==='textarea' ? '12' : '6' ?>">
                  <label class="form-label fw-600 small"><?= $f['label'] ?></label>
                  <?php if ($f['type']==='textarea'): ?>
                  <textarea name="settings[<?= $f['key'] ?>]" class="form-control" rows="3"><?= Helper::e($ct[$f['key']] ?? '') ?></textarea>
                  <?php else: ?>
                  <input type="text" name="settings[<?= $f['key'] ?>]" class="form-control" value="<?= Helper::e($ct[$f['key']] ?? '') ?>">
                  <?php endif; ?>
                  <?php if ($f['hint']): ?><div class="form-text"><?= $f['hint'] ?></div><?php endif; ?>
                </div>
                <?php endforeach; ?>
              </div>
            </div>
            <hr class="my-3">
            <?php endforeach; ?>

            <?php elseif ($group === 'integrations'): ?>
            <?php
              $ig = [];
              foreach ($settings as $k => $s) { $ig[$k] = $s['value'] ?? ''; }
            ?>

            <!-- Google Maps Section -->
            <div class="mb-4">
              <div class="d-flex align-items-center gap-2 mb-3">
                <span class="badge bg-danger px-3 py-2 fs-6"><i class="bi bi-geo-alt-fill me-1"></i>Google Maps</span>
                <span class="text-muted small">Show your business location on the website</span>
              </div>

              <!-- Method Selector -->
              <div class="mb-3">
                <label class="form-label fw-600">How would you like to embed the map?</label>
                <div class="d-flex gap-2 flex-wrap" id="mapMethodBtns">
                  <button type="button" class="btn btn-sm btn-outline-primary map-method-btn <?= empty($ig['google_maps_iframe']) && empty($ig['google_maps_embed_url']) ? 'active' : '' ?>" onclick="setMapMethod('api')">
                    <i class="bi bi-key me-1"></i>API Key
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-success map-method-btn <?= !empty($ig['google_maps_embed_url']) ? 'active' : '' ?>" onclick="setMapMethod('embed_url')">
                    <i class="bi bi-link-45deg me-1"></i>Embed URL
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-warning map-method-btn <?= !empty($ig['google_maps_iframe']) ? 'active' : '' ?>" onclick="setMapMethod('iframe')">
                    <i class="bi bi-code-slash me-1"></i>iFrame Code
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-info map-method-btn" onclick="setMapMethod('coordinates')">
                    <i class="bi bi-crosshair me-1"></i>Coordinates
                  </button>
                </div>
              </div>

              <!-- API Key Method -->
              <div id="map-method-api" class="map-method-panel row g-3">
                <div class="col-md-8">
                  <label class="form-label fw-600">Google Maps API Key</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-key"></i></span>
                    <input type="text" name="settings[google_maps_key]" class="form-control" value="<?= Helper::e($ig['google_maps_key']??'') ?>" placeholder="AIzaSy...">
                  </div>
                  <div class="form-text"><a href="https://console.cloud.google.com/apis/credentials" target="_blank">Get an API key from Google Cloud Console <i class="bi bi-box-arrow-up-right"></i></a></div>
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Google Place ID</label>
                  <input type="text" name="settings[google_maps_place_id]" class="form-control" value="<?= Helper::e($ig['google_maps_place_id']??'') ?>" placeholder="ChIJ...">
                  <div class="form-text"><a href="https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder" target="_blank">Find Place ID <i class="bi bi-box-arrow-up-right"></i></a></div>
                </div>
              </div>

              <!-- Embed URL Method -->
              <div id="map-method-embed_url" class="map-method-panel row g-3" style="display:none">
                <div class="col-12">
                  <label class="form-label fw-600">Google Maps Embed URL</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
                    <input type="url" name="settings[google_maps_embed_url]" id="embedUrlInput" class="form-control" value="<?= Helper::e($ig['google_maps_embed_url']??'') ?>" placeholder="https://www.google.com/maps/embed?pb=...">
                  </div>
                  <div class="form-text">Go to <strong>Google Maps</strong> → find your location → click Share → Embed a map → copy the <code>src</code> URL</div>
                </div>
                <?php if (!empty($ig['google_maps_embed_url'])): ?>
                <div class="col-12">
                  <div class="rounded overflow-hidden border" style="height:250px">
                    <iframe src="<?= Helper::e($ig['google_maps_embed_url']) ?>" width="100%" height="250" style="border:0" allowfullscreen loading="lazy"></iframe>
                  </div>
                </div>
                <?php endif; ?>
                <div class="col-md-3">
                  <label class="form-label fw-600">Zoom Level</label>
                  <input type="number" name="settings[google_maps_zoom]" class="form-control" value="<?= Helper::e($ig['google_maps_zoom']??'15') ?>" min="1" max="20">
                </div>
              </div>

              <!-- iFrame Code Method -->
              <div id="map-method-iframe" class="map-method-panel row g-3" style="display:none">
                <div class="col-12">
                  <label class="form-label fw-600">Paste Full iFrame Embed Code</label>
                  <textarea name="settings[google_maps_iframe]" id="iframeInput" class="form-control font-monospace" rows="4" placeholder='&lt;iframe src="https://www.google.com/maps/embed?pb=..." width="600" height="450"&gt;&lt;/iframe&gt;'><?= Helper::e($ig['google_maps_iframe']??'') ?></textarea>
                  <div class="form-text">Go to <strong>Google Maps</strong> → Share → Embed a map → copy the entire <code>&lt;iframe&gt;</code> tag</div>
                </div>
                <?php if (!empty($ig['google_maps_iframe'])): ?>
                <div class="col-12">
                  <label class="form-label fw-600 small">Preview</label>
                  <div class="rounded overflow-hidden border" style="height:250px">
                    <?= $ig['google_maps_iframe'] ?>
                  </div>
                </div>
                <?php endif; ?>
              </div>

              <!-- Coordinates Method -->
              <div id="map-method-coordinates" class="map-method-panel row g-3" style="display:none">
                <div class="col-md-4">
                  <label class="form-label fw-600">Latitude</label>
                  <input type="text" name="settings[google_maps_latitude]" class="form-control" value="<?= Helper::e($ig['google_maps_latitude']??'') ?>" placeholder="-6.7924">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Longitude</label>
                  <input type="text" name="settings[google_maps_longitude]" class="form-control" value="<?= Helper::e($ig['google_maps_longitude']??'') ?>" placeholder="39.2083">
                </div>
                <div class="col-md-4">
                  <label class="form-label fw-600">Zoom Level</label>
                  <input type="number" name="settings[google_maps_zoom]" class="form-control" value="<?= Helper::e($ig['google_maps_zoom']??'15') ?>" min="1" max="20">
                </div>
                <div class="col-12">
                  <div class="alert alert-info py-2 small"><i class="bi bi-info-circle me-1"></i>Coordinates require a valid <strong>Google Maps API Key</strong> to render the map.</div>
                </div>
              </div>
            </div>

            <hr class="my-4">

            <!-- Other Integrations -->
            <div class="mb-2">
              <div class="d-flex align-items-center gap-2 mb-3">
                <i class="bi bi-plug text-primary fs-5"></i>
                <h6 class="fw-700 mb-0">Other Integrations</h6>
              </div>
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label fw-600">Google Analytics ID (GA4)</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-graph-up"></i></span>
                    <input type="text" name="settings[google_analytics_id]" class="form-control" value="<?= Helper::e($ig['google_analytics_id']??'') ?>" placeholder="G-XXXXXXXXXX">
                  </div>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">Facebook Pixel ID</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-facebook"></i></span>
                    <input type="text" name="settings[facebook_pixel_id]" class="form-control" value="<?= Helper::e($ig['facebook_pixel_id']??'') ?>" placeholder="1234567890">
                  </div>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">WhatsApp Chat Button Number</label>
                  <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-whatsapp"></i></span>
                    <input type="text" name="settings[whatsapp_chat_number]" class="form-control" value="<?= Helper::e($ig['whatsapp_chat_number']??'') ?>" placeholder="+255784000001">
                  </div>
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">reCAPTCHA Site Key</label>
                  <input type="text" name="settings[recaptcha_site_key]" class="form-control" value="<?= Helper::e($ig['recaptcha_site_key']??'') ?>" placeholder="6Le...">
                </div>
                <div class="col-md-6">
                  <label class="form-label fw-600">reCAPTCHA Secret Key</label>
                  <div class="input-group">
                    <input type="password" name="settings[recaptcha_secret_key]" class="form-control" value="<?= Helper::e($ig['recaptcha_secret_key']??'') ?>" placeholder="••••••••">
                    <button class="btn btn-outline-secondary toggle-pass" type="button"><i class="bi bi-eye"></i></button>
                  </div>
                </div>
              </div>
            </div>

            <?php elseif ($group === 'payment'): ?>
            <?php
              $ps = [];
              foreach ($settings as $k => $s) { $ps[$k] = $s['value'] ?? ''; }
            ?>

            <!-- General & Bank -->
            <div class="mb-4">
              <div class="d-flex align-items-center gap-2 mb-3">
                <i class="bi bi-bank text-primary fs-5"></i>
                <h6 class="fw-700 mb-0">General &amp; Bank Transfer</h6>
              </div>
              <div class="row g-3 ps-2">
                <?php foreach (['payment_currency'=>'Currency Code','payment_bank_name'=>'Bank Name','payment_account_name'=>'Account Name','payment_account_number'=>'Account Number'] as $k=>$lbl): ?>
                <div class="col-md-6">
                  <label class="form-label fw-600"><?= $lbl ?></label>
                  <input type="text" name="settings[<?= $k ?>]" class="form-control" value="<?= Helper::e($ps[$k]??'') ?>">
                </div>
                <?php endforeach; ?>
              </div>
            </div>

            <hr class="my-3">

            <?php
            $vendors = [
              'mpesa' => [
                'label'   => 'M-Pesa (Safaricom Kenya)',
                'badge'   => 'success',
                'icon'    => 'bi-phone',
                'note'    => 'Safaricom M-Pesa STK Push',
                'fields'  => [
                  ['key'=>'mpesa_shortcode',       'label'=>'Business Shortcode',  'type'=>'text',     'ph'=>'e.g. 174379'],
                  ['key'=>'mpesa_environment',     'label'=>'Environment',         'type'=>'select',   'opts'=>['sandbox'=>'Sandbox (Testing)','production'=>'Production (Live)']],
                  ['key'=>'mpesa_consumer_key',    'label'=>'Consumer Key',        'type'=>'text',     'ph'=>'API consumer key'],
                  ['key'=>'mpesa_consumer_secret', 'label'=>'Consumer Secret',     'type'=>'password', 'ph'=>'••••••••'],
                  ['key'=>'mpesa_passkey',         'label'=>'Passkey',             'type'=>'password', 'ph'=>'••••••••'],
                  ['key'=>'mpesa_callback_url',    'label'=>'Callback URL',        'type'=>'url',      'ph'=>'https://yourdomain.com/mpesa/callback'],
                ],
              ],
              'vodacom_mpesa' => [
                'label'   => 'M-Pesa (Vodacom Tanzania)',
                'badge'   => 'success',
                'icon'    => 'bi-phone',
                'note'    => 'Vodacom M-Pesa Tanzania',
                'fields'  => [
                  ['key'=>'vodacom_mpesa_number',    'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'vodacom_mpesa_shortcode', 'label'=>'Business Shortcode', 'type'=>'text',     'ph'=>''],
                  ['key'=>'vodacom_mpesa_api_key',   'label'=>'API Key',            'type'=>'text',     'ph'=>''],
                  ['key'=>'vodacom_mpesa_secret',    'label'=>'API Secret',         'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'mixx' => [
                'label'   => 'Mixx by Yas (Tigo Pesa)',
                'badge'   => 'info',
                'icon'    => 'bi-phone-vibrate',
                'note'    => 'Formerly Tigo Pesa',
                'fields'  => [
                  ['key'=>'mixx_number',         'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'mixx_account_number', 'label'=>'Account Number', 'type'=>'text',     'ph'=>''],
                  ['key'=>'mixx_api_key',         'label'=>'API Key',       'type'=>'text',     'ph'=>''],
                  ['key'=>'mixx_secret',          'label'=>'API Secret',    'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'airtel' => [
                'label'   => 'Airtel Money',
                'badge'   => 'danger',
                'icon'    => 'bi-reception-4',
                'note'    => 'Airtel Tanzania mobile money',
                'fields'  => [
                  ['key'=>'airtel_number',         'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'airtel_shortcode',      'label'=>'Business Shortcode', 'type'=>'text',     'ph'=>''],
                  ['key'=>'airtel_client_id',      'label'=>'Client ID',          'type'=>'text',     'ph'=>''],
                  ['key'=>'airtel_client_secret',  'label'=>'Client Secret',      'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'halopesa' => [
                'label'   => 'HaloPesa',
                'badge'   => 'warning',
                'icon'    => 'bi-phone-fill',
                'note'    => 'Halotel Tanzania',
                'fields'  => [
                  ['key'=>'halopesa_number',  'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'halopesa_account', 'label'=>'Account Number', 'type'=>'text',     'ph'=>''],
                  ['key'=>'halopesa_api_key', 'label'=>'API Key',        'type'=>'text',     'ph'=>''],
                  ['key'=>'halopesa_secret',  'label'=>'API Secret',     'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'tpesa' => [
                'label'   => 'T-Pesa (TTCL)',
                'badge'   => 'secondary',
                'icon'    => 'bi-phone',
                'note'    => 'Tanzania Telecommunications',
                'fields'  => [
                  ['key'=>'tpesa_number',  'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'tpesa_account', 'label'=>'Account Number', 'type'=>'text',     'ph'=>''],
                  ['key'=>'tpesa_api_key', 'label'=>'API Key',        'type'=>'text',     'ph'=>''],
                  ['key'=>'tpesa_secret',  'label'=>'API Secret',     'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'azampesa' => [
                'label'   => 'Azam Pesa',
                'badge'   => 'dark',
                'icon'    => 'bi-wallet2',
                'note'    => 'Azam Media mobile wallet',
                'fields'  => [
                  ['key'=>'azampesa_number',  'label'=>'Payment Number (shown to customers)', 'type'=>'text', 'ph'=>'+255 7XX XXX XXX'],
                  ['key'=>'azampesa_account', 'label'=>'Account Number', 'type'=>'text',     'ph'=>''],
                  ['key'=>'azampesa_api_key', 'label'=>'API Key',        'type'=>'text',     'ph'=>''],
                  ['key'=>'azampesa_secret',  'label'=>'API Secret',     'type'=>'password', 'ph'=>'••••••••'],
                ],
              ],
              'stripe' => [
                'label'   => 'Stripe',
                'badge'   => 'primary',
                'icon'    => 'bi-credit-card',
                'note'    => 'International card payments',
                'fields'  => [
                  ['key'=>'stripe_publishable_key',  'label'=>'Publishable Key',   'type'=>'text',     'ph'=>'pk_live_...'],
                  ['key'=>'stripe_secret_key',       'label'=>'Secret Key',        'type'=>'password', 'ph'=>'sk_live_...'],
                  ['key'=>'stripe_webhook_secret',   'label'=>'Webhook Secret',    'type'=>'password', 'ph'=>'whsec_...'],
                ],
              ],
            ];
            ?>

            <?php foreach ($vendors as $vid => $vendor): ?>
            <?php $enabledKey = $vid . '_enabled'; ?>
            <div class="payment-vendor-card mb-3" id="vendor-<?= $vid ?>">
              <div class="vendor-header d-flex align-items-center justify-content-between p-3"
                   style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;cursor:pointer"
                   onclick="toggleVendor('<?= $vid ?>')">
                <div class="d-flex align-items-center gap-3">
                  <span class="badge bg-<?= $vendor['badge'] ?> px-3 py-2">
                    <i class="bi <?= $vendor['icon'] ?> me-1"></i><?= $vendor['label'] ?>
                  </span>
                  <span class="text-muted small"><?= $vendor['note'] ?></span>
                  <?php if (($ps[$enabledKey]??'0')==='1'): ?>
                  <span class="badge bg-success-subtle text-success"><i class="bi bi-check-circle me-1"></i>Active</span>
                  <?php endif; ?>
                </div>
                <div class="d-flex align-items-center gap-3">
                  <div class="form-check form-switch mb-0" onclick="event.stopPropagation()">
                    <input class="form-check-input" type="checkbox" name="settings[<?= $enabledKey ?>]"
                           id="toggle_<?= $vid ?>" value="1"
                           <?= ($ps[$enabledKey]??'0')==='1'?'checked':'' ?>>
                    <label class="form-check-label small fw-600" for="toggle_<?= $vid ?>">Enable</label>
                  </div>
                  <i class="bi bi-chevron-down text-muted vendor-chevron-<?= $vid ?>"></i>
                </div>
              </div>
              <div id="vendor-body-<?= $vid ?>" style="display:<?= ($ps[$enabledKey]??'0')==='1'?'block':'none' ?>">
                <div class="row g-3 p-3 pt-2 border border-top-0 rounded-bottom" style="border-color:#e2e8f0!important">
                  <?php foreach ($vendor['fields'] as $f): ?>
                  <div class="col-md-6">
                    <label class="form-label fw-600 small"><?= $f['label'] ?></label>
                    <?php if ($f['type']==='select'): ?>
                    <select name="settings[<?= $f['key'] ?>]" class="form-select form-select-sm">
                      <?php foreach ($f['opts'] as $ov=>$ol): ?>
                      <option value="<?= $ov ?>" <?= ($ps[$f['key']]??'')===$ov?'selected':'' ?>><?= $ol ?></option>
                      <?php endforeach; ?>
                    </select>
                    <?php elseif ($f['type']==='password'): ?>
                    <div class="input-group input-group-sm">
                      <input type="password" name="settings[<?= $f['key'] ?>]" class="form-control"
                             value="<?= Helper::e($ps[$f['key']]??'') ?>" placeholder="<?= $f['ph'] ?>">
                      <button class="btn btn-outline-secondary toggle-pass" type="button"><i class="bi bi-eye"></i></button>
                    </div>
                    <?php elseif ($f['type']==='url'): ?>
                    <div class="input-group input-group-sm">
                      <span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
                      <input type="url" name="settings[<?= $f['key'] ?>]" class="form-control"
                             value="<?= Helper::e($ps[$f['key']]??'') ?>" placeholder="<?= $f['ph'] ?>">
                    </div>
                    <?php else: ?>
                    <input type="text" name="settings[<?= $f['key'] ?>]" class="form-control form-control-sm"
                           value="<?= Helper::e($ps[$f['key']]??'') ?>" placeholder="<?= $f['ph'] ?>">
                    <?php endif; ?>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>
            <?php endforeach; ?>

            <?php else: ?>
            <div class="row g-3">
              <?php foreach ($settings as $key => $s):
                $label = Helper::e($s['label'] ?? ucwords(str_replace('_',' ',$key)));
                $value = Helper::e($s['value'] ?? '');
                $type  = $s['type'] ?? 'text';
              ?>
              <div class="col-md-6">
                <label class="form-label fw-600">
                  <?= $label ?>
                  <?php if (in_array($key,['company_name','company_email'])): ?>
                  <span class="text-danger ms-1">*</span>
                  <?php endif; ?>
                </label>
                <?php if ($type === 'password'): ?>
                <div class="input-group">
                  <input type="password" name="settings[<?= Helper::e($key) ?>]" class="form-control" value="<?= $value ?>" placeholder="••••••••">
                  <button class="btn btn-outline-secondary toggle-pass" type="button"><i class="bi bi-eye"></i></button>
                </div>
                <?php elseif ($type === 'number'): ?>
                <input type="number" name="settings[<?= Helper::e($key) ?>]" class="form-control" value="<?= $value ?>" step="0.01">
                <?php elseif ($type === 'url'): ?>
                <div class="input-group">
                  <span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
                  <input type="url" name="settings[<?= Helper::e($key) ?>]" class="form-control" value="<?= $value ?>" placeholder="https://">
                </div>
                <?php elseif ($type === 'email'): ?>
                <div class="input-group">
                  <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                  <input type="email" name="settings[<?= Helper::e($key) ?>]" class="form-control" value="<?= $value ?>">
                </div>
                <?php elseif ($type === 'textarea'): ?>
                <textarea name="settings[<?= Helper::e($key) ?>]" class="form-control" rows="3"><?= $value ?></textarea>
                <?php else: ?>
                <input type="text" name="settings[<?= Helper::e($key) ?>]" class="form-control" value="<?= $value ?>">
                <?php endif; ?>
              </div>
              <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <!-- Save Button -->
            <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
              <div>
                <?php if ($group === 'email'): ?>
                <button type="button" class="btn btn-outline-info" data-bs-toggle="modal" data-bs-target="#testMailModal">
                  <i class="bi bi-send-check me-2"></i>Send Test Email
                </button>
                <?php endif; ?>
              </div>
              <button type="submit" class="btn btn-primary px-4">
                <i class="bi bi-save me-2"></i>Save <?= $meta['label'] ?> Settings
              </button>
            </div>
          </div>
        </div>
        <?php endforeach; ?>

        <!-- Logo Tab -->
        <div class="tab-pane fade" id="tab-logo" role="tabpanel">
          <div class="form-card">
            <div class="settings-section-header mb-4">
              <div class="d-flex align-items-center gap-3">
                <div class="settings-icon-lg stat-icon-wrap yellow">
                  <i class="bi bi-image fs-4"></i>
                </div>
                <div>
                  <h5 class="fw-700 mb-0">Logo & Branding</h5>
                  <p class="text-muted small mb-0">Upload your company logo and branding assets</p>
                </div>
              </div>
              <hr class="mt-3 mb-4">
            </div>
            <form method="POST" action="<?= APP_URL ?>/admin/settings/logo" enctype="multipart/form-data">
              <?= Helper::csrf() ?>
              <div class="row g-4 align-items-center">
                <div class="col-md-3 text-center">
                  <div class="logo-preview-box">
                    <i class="bi bi-building-fill text-primary" style="font-size:3rem"></i>
                    <div class="small text-muted mt-2">Current Logo</div>
                  </div>
                </div>
                <div class="col-md-9">
                  <label class="form-label fw-600">Upload New Logo</label>
                  <input type="file" name="logo" class="form-control mb-2" accept="image/*" id="logoInput">
                  <div class="form-text mb-3"><i class="bi bi-info-circle me-1"></i>Recommended: PNG with transparent background, 300×80px, max 2MB</div>
                  <button type="submit" class="btn btn-primary">
                    <i class="bi bi-cloud-upload me-2"></i>Upload Logo
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Test Mail Modal -->
<div class="modal fade" id="testMailModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-send-check me-2"></i>Send Test Email</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4">
        <p class="text-muted small mb-3">Send a test email using your current SMTP configuration to verify it is working correctly.</p>
        <label class="form-label fw-600">Recipient Email Address <span class="text-danger">*</span></label>
        <input type="email" id="testEmailInput" class="form-control mb-3" placeholder="Enter recipient email address...">
        <div id="testMailResult" style="display:none"></div>
      </div>
      <div class="modal-footer bg-light">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-info text-white px-4" id="sendTestMailBtn">
          <span id="testMailBtnText"><i class="bi bi-send me-2"></i>Send Test</span>
          <span id="testMailSpinner" style="display:none"><span class="spinner-border spinner-border-sm me-2"></span>Sending...</span>
        </button>
      </div>
    </div>
  </div>
</div>

<style>
.settings-nav-card {
  background: #fff;
  border-radius: 16px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  position: sticky;
  top: 75px;
}
.settings-nav-header {
  background: linear-gradient(135deg, #1a3c5e, #2d6a9f);
  color: #fff;
  padding: 1rem 1.25rem;
  font-size: 0.85rem;
  font-weight: 700;
  letter-spacing: 0.04em;
  text-transform: uppercase;
}
.settings-nav { padding: 0.5rem; }
.settings-nav-link {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  border-radius: 10px;
  text-decoration: none;
  color: #475569;
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 3px;
  transition: all 0.2s;
  cursor: pointer;
}
.settings-nav-link:hover { background: #f1f5f9; color: #1a3c5e; }
.settings-nav-link.active { background: #eff6ff; color: #1a3c5e; font-weight: 700; }
.settings-nav-icon {
  width: 32px !important;
  height: 32px !important;
  border-radius: 8px !important;
  font-size: 0.85rem !important;
  flex-shrink: 0;
}
.settings-icon-lg {
  width: 52px !important;
  height: 52px !important;
  border-radius: 14px !important;
  font-size: 1.25rem !important;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.logo-preview-box {
  width: 120px;
  height: 80px;
  border: 2px dashed #e2e8f0;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  background: #f8fafc;
}
.toggle-pass { border-left: none; }
</style>

<script>
// Google Maps method switcher
function setMapMethod(method) {
  document.querySelectorAll('.map-method-panel').forEach(p => p.style.display = 'none');
  const panel = document.getElementById('map-method-' + method);
  if (panel) panel.style.display = '';
  document.querySelectorAll('.map-method-btn').forEach(b => b.classList.remove('active'));
  event.currentTarget.classList.add('active');
}
// Show active map method on load
(function() {
  const panels = document.querySelectorAll('.map-method-panel');
  let anyVisible = false;
  panels.forEach(p => { if (p.style.display !== 'none') anyVisible = true; });
  if (!anyVisible && panels.length) panels[0].style.display = '';
})();

// Payment vendor accordion toggle
function toggleVendor(vid) {
  const body    = document.getElementById('vendor-body-' + vid);
  const chevron = document.querySelector('.vendor-chevron-' + vid);
  const open    = body.style.display === 'block';
  body.style.display    = open ? 'none' : 'block';
  chevron.className     = open ? 'bi bi-chevron-down text-muted vendor-chevron-' + vid
                                : 'bi bi-chevron-up text-muted vendor-chevron-' + vid;
}

// Auto-expand vendor when its enable toggle is switched on
document.addEventListener('change', function(e) {
  if (e.target.type === 'checkbox' && e.target.name && e.target.name.includes('_enabled')) {
    const vid  = e.target.id.replace('toggle_', '');
    const body = document.getElementById('vendor-body-' + vid);
    if (body) body.style.display = e.target.checked ? 'block' : 'none';
  }
});

// Clear modal on open
document.getElementById('testMailModal').addEventListener('show.bs.modal', function() {
  document.getElementById('testEmailInput').value = '';
  const r = document.getElementById('testMailResult');
  r.style.display = 'none';
  r.innerHTML = '';
});

// Test Mail
document.getElementById('sendTestMailBtn').addEventListener('click', function() {
  const email = document.getElementById('testEmailInput').value.trim();
  const result = document.getElementById('testMailResult');
  if (!email) { result.style.display=''; result.innerHTML='<div class="alert alert-warning py-2 mb-0">Please enter an email address.</div>'; return; }

  document.getElementById('testMailBtnText').style.display = 'none';
  document.getElementById('testMailSpinner').style.display = '';
  result.style.display = 'none';
  this.disabled = true;

  const form = new FormData();
  form.append('test_email', email);
  form.append('<?= CSRF_TOKEN_NAME ?>', '<?= $_SESSION[CSRF_TOKEN_NAME] ?? '' ?>');

  fetch('<?= APP_URL ?>/admin/settings/test-mail', { method: 'POST', body: form })
    .then(r => r.json())
    .then(data => {
      result.style.display = '';
      result.innerHTML = '<div class="alert alert-' + (data.success ? 'success' : 'danger') + ' py-2 mb-0"><i class="bi bi-' + (data.success ? 'check-circle' : 'exclamation-triangle') + ' me-2"></i>' + data.message + '</div>';
    })
    .catch(() => {
      result.style.display = '';
      result.innerHTML = '<div class="alert alert-danger py-2 mb-0">Request failed. Please try again.</div>';
    })
    .finally(() => {
      document.getElementById('testMailBtnText').style.display = '';
      document.getElementById('testMailSpinner').style.display = 'none';
      document.getElementById('sendTestMailBtn').disabled = false;
    });
});

document.querySelectorAll('.toggle-pass').forEach(btn => {
  btn.addEventListener('click', function() {
    const input = this.previousElementSibling;
    const icon = this.querySelector('i');
    if (input.type === 'password') {
      input.type = 'text';
      icon.className = 'bi bi-eye-slash';
    } else {
      input.type = 'password';
      icon.className = 'bi bi-eye';
    }
  });
});

const CSRF_TOKEN = '<?= $_SESSION[CSRF_TOKEN_NAME] ?? '' ?>';
const UPLOAD_URL = '<?= APP_URL ?>/admin/settings/upload-image';
const REMOVE_URL = '<?= APP_URL ?>/admin/settings/remove-image';

function previewSiteImg(input, key) {
  if (!input.files || !input.files[0]) return;
  const reader = new FileReader();
  reader.onload = function(e) {
    const ph = document.getElementById('placeholder_' + key);
    if (ph) ph.style.display = 'none';
    let img = document.getElementById('preview_' + key);
    if (!img) {
      img = document.createElement('img');
      img.id = 'preview_' + key;
      img.className = 'rounded-2 w-100';
      img.style.cssText = 'height:140px;object-fit:cover;border:1px solid #e2e8f0';
      document.getElementById('preview_wrap_' + key).appendChild(img);
    }
    img.src = e.target.result;
  };
  reader.readAsDataURL(input.files[0]);
}

function uploadSiteImg(key) {
  const fileInput = document.getElementById('file_' + key);
  const msg = document.getElementById('msg_' + key);
  if (!fileInput.files || !fileInput.files[0]) {
    msg.innerHTML = '<span class="text-danger">Please select a file first.</span>';
    return;
  }
  const fd = new FormData();
  fd.append('<?= CSRF_TOKEN_NAME ?>', CSRF_TOKEN);
  fd.append('image_key', key);
  fd.append('image_file', fileInput.files[0]);
  msg.innerHTML = '<span class="text-muted"><i class="bi bi-hourglass-split me-1"></i>Uploading...</span>';
  fetch(UPLOAD_URL, { method: 'POST', body: fd })
    .then(r => r.redirected ? window.location.href = r.url : r.text())
    .then(() => { msg.innerHTML = '<span class="text-success"><i class="bi bi-check-circle me-1"></i>Uploaded!</span>'; setTimeout(() => location.reload(), 800); })
    .catch(() => { msg.innerHTML = '<span class="text-danger">Upload failed. Try again.</span>'; });
}

function removeSiteImg(key) {
  if (!confirm('Remove this photo? The site will fall back to the default image.')) return;
  const fd = new FormData();
  fd.append('<?= CSRF_TOKEN_NAME ?>', CSRF_TOKEN);
  fd.append('image_key', key);
  fetch(REMOVE_URL, { method: 'POST', body: fd })
    .then(() => location.reload())
    .catch(() => alert('Remove failed. Try again.'));
}
</script>
