<section class="content-header" id="konfigurasi-sistem">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0"><?php echo $page_subtitle; ?></p>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></li>
          <li class="breadcrumb-item active">Konfigurasi Sistem</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <?php
      $ai_enabled = (string) ($config['ai_enabled'] ?? '0') === '1';
      $ai_api_key = (string) ($config['ai_api_key'] ?? '');
      $ai_connection_status = strtoupper((string) ($config['ai_connection_status'] ?? 'PENDING'));
      if (!in_array($ai_connection_status, ['CONNECTED', 'DISCONNECTED', 'PENDING'], true)) {
        $ai_connection_status = 'PENDING';
      }
      $ai_connection_checked_at = (string) ($config['ai_connection_checked_at'] ?? '');
      $ai_connection_message = (string) ($config['ai_connection_message'] ?? 'Belum ada pengecekan koneksi.');
      $status_badge_class = $ai_connection_status === 'CONNECTED'
        ? 'badge badge-success'
        : ($ai_connection_status === 'DISCONNECTED' ? 'badge badge-danger' : 'badge badge-secondary');
      $status_label = $ai_connection_status === 'CONNECTED'
        ? 'Connected'
        : ($ai_connection_status === 'DISCONNECTED' ? 'Disconnected' : 'Belum Dicek');
      $api_key_masked = $ai_api_key === '' ? '' : str_repeat('*', max(0, strlen($ai_api_key) - 4)) . substr($ai_api_key, -4);
    ?>

    <?php echo form_open_multipart('master/konfigurasi/simpan', ['id' => 'form-konfigurasi-sistem']); ?>

    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-cog mr-1"></i> Identitas Aplikasi</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Nama Aplikasi</label>
              <input type="text" name="nama_aplikasi" class="form-control"
                     value="<?php echo html_escape($config['nama_aplikasi'] ?? app_name()); ?>" maxlength="100" required>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label>Nama Perusahaan</label>
              <input type="text" name="nama_perusahaan" class="form-control"
                     value="<?php echo html_escape($config['nama_perusahaan'] ?? company_name()); ?>" maxlength="150" required>
            </div>
          </div>
          <div class="col-md-12">
            <div class="form-group mb-0">
              <label>Alamat Perusahaan</label>
              <textarea name="alamat_perusahaan" class="form-control" rows="2" required><?php echo html_escape($config['alamat_perusahaan'] ?? company_address()); ?></textarea>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-image mr-1"></i> Logo & Favicon</h3>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Logo Perusahaan</label>
              <input type="file" name="logo_perusahaan_file" class="form-control-file" accept=".jpg,.jpeg,.png,.webp,.svg">
              <small class="form-text text-muted">Format: JPG, PNG, WEBP, SVG. Maksimal 2 MB.</small>
            </div>
            <?php if (!empty($config['logo_perusahaan'])): ?>
            <div class="border rounded p-2 bg-light">
              <small class="text-muted d-block mb-1">Logo saat ini</small>
              <img src="<?php echo base_url($config['logo_perusahaan']); ?>" alt="Logo Perusahaan" style="max-height:80px; width:auto;">
            </div>
            <?php endif; ?>
          </div>

          <div class="col-md-6">
            <div class="form-group">
              <label>Favicon Aplikasi</label>
              <input type="file" name="favicon_aplikasi_file" class="form-control-file" accept=".ico,.png,.jpg,.jpeg,.webp,.svg">
              <small class="form-text text-muted">Format: ICO, PNG, JPG, WEBP, SVG. Maksimal 2 MB.</small>
            </div>
            <?php if (!empty($config['favicon_aplikasi'])): ?>
            <div class="border rounded p-2 bg-light">
              <small class="text-muted d-block mb-1">Favicon saat ini</small>
              <img src="<?php echo base_url($config['favicon_aplikasi']); ?>" alt="Favicon" style="max-height:48px; width:auto;">
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="card card-danger card-outline">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-calendar mr-1"></i> Periode Payroll</h3>
      </div>
      <div class="card-body">
        <?php
          $mode_periode = strtoupper((string) ($config['payroll_mode_periode'] ?? payroll_period_mode()));
          if (!in_array($mode_periode, ['CALENDAR', 'CUSTOM'], true)) {
            $mode_periode = 'CALENDAR';
          }
          $tanggal_gajian = (int) ($config['payroll_tanggal_gajian'] ?? payroll_payday());
          if ($tanggal_gajian < 1 || $tanggal_gajian > 31) {
            $tanggal_gajian = 1;
          }
        ?>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Mode Periode Payroll</label>
              <select name="payroll_mode_periode" class="form-control" required>
                <option value="CALENDAR" <?php echo $mode_periode === 'CALENDAR' ? 'selected' : ''; ?>>Kalender Bulanan (1 s/d akhir bulan)</option>
                <option value="CUSTOM" <?php echo $mode_periode === 'CUSTOM' ? 'selected' : ''; ?>>Custom Tanggal Gajian</option>
              </select>
              <small class="form-text text-muted">Mode ini dipakai untuk pembentukan periode payroll baru (REGULER dan THR).</small>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group mb-0">
              <label>Tanggal gajian</label>
              <input type="number" name="payroll_tanggal_gajian" class="form-control" min="1" max="31" value="<?php echo $tanggal_gajian; ?>" required>
              <small class="form-text text-muted">Jika diisi 1, sistem otomatis memakai periode 1 bulan penuh seperti perilaku lama.</small>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card card-danger card-outline position-relative" id="card-ai-konfigurasi">
      <span id="ai-status-badge" class="<?php echo $status_badge_class; ?> ai-status-floating"><?php echo $status_label; ?></span>
      <div class="card-header">
        <h3 class="card-title mb-0"><i class="fa fa-comments-o mr-1"></i> AI Asisten Admin</h3>
      </div>
      <div class="card-body">
        <div class="alert alert-light border mb-3">
          <div><strong>Status koneksi:</strong> <span id="ai-status-text"><?php echo html_escape($ai_connection_message); ?></span></div>
          <div class="text-muted small mt-1">Terakhir dicek: <span id="ai-status-checked-at"><?php echo $ai_connection_checked_at !== '' ? html_escape($ai_connection_checked_at) : '-'; ?></span></div>
        </div>

        <div class="row align-items-end">
          <div class="col-md-3 col-lg-2">
            <div class="form-group mb-0">
              <label class="d-block">Aktifkan AI</label>
              <div class="custom-control custom-switch mt-2">
                <input type="checkbox" class="custom-control-input" id="ai_enabled" name="ai_enabled" value="1" <?php echo $ai_enabled ? 'checked' : ''; ?>>
                <label class="custom-control-label" for="ai_enabled">Aktif</label>
              </div>
              <small class="form-text text-muted">Muncul jika connected.</small>
            </div>
          </div>
          <div class="col-md-9 col-lg-10">
            <div class="form-group mb-0">
              <label>API Key</label>
              <div class="input-group">
                <input type="password" name="ai_api_key" id="ai_api_key" class="form-control" value="<?php echo html_escape($ai_api_key); ?>" placeholder="Masukkan API key (Groq/OpenAI-compatible)" autocomplete="off">
                <div class="input-group-append">
                  <button type="button" class="btn btn-outline-secondary" id="btn-toggle-api-key" title="Tampilkan/Sembunyikan API key">
                    <i class="fa fa-eye"></i>
                  </button>
                </div>
              </div>
              <?php if ($api_key_masked !== ''): ?>
              <small class="form-text text-muted">Key tersimpan: <?php echo html_escape($api_key_masked); ?></small>
              <?php else: ?>
              <small class="form-text text-muted">Belum ada API key tersimpan.</small>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mb-4 d-flex justify-content-end align-items-center flex-wrap">
      <button type="button" class="btn btn-info mr-2 mb-2 mb-sm-0" id="btn-test-ai-connection">
        <i class="fa fa-plug mr-1"></i> Test Koneksi API
      </button>
      <button type="submit" class="btn btn-danger">
        <i class="fa fa-save mr-1"></i> Simpan Konfigurasi Sistem
      </button>
    </div>

    <?php echo form_close(); ?>
  </div>
</section>

<style>
#card-ai-konfigurasi .ai-status-floating {
  position: absolute;
  right: 12px;
  top: 10px;
  z-index: 2;
}

@media (max-width: 767.98px) {
  #card-ai-konfigurasi .ai-status-floating {
    top: 8px;
    right: 8px;
  }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo (string) $this->config->item('csrf_cookie_name'); ?>';
  var statusBadge = document.getElementById('ai-status-badge');
  var statusText = document.getElementById('ai-status-text');
  var statusCheckedAt = document.getElementById('ai-status-checked-at');
  var toggleBtn = document.getElementById('btn-toggle-api-key');
  var testBtn = document.getElementById('btn-test-ai-connection');
  var apiKeyInput = document.getElementById('ai_api_key');

  function updateAiStatus(status, message, checkedAt) {
    if (!statusBadge) return;

    statusBadge.className = 'badge';
    if (status === 'CONNECTED') {
      statusBadge.classList.add('badge-success');
      statusBadge.textContent = 'Connected';
    } else if (status === 'DISCONNECTED') {
      statusBadge.classList.add('badge-danger');
      statusBadge.textContent = 'Disconnected';
    } else {
      statusBadge.classList.add('badge-secondary');
      statusBadge.textContent = 'Belum Dicek';
    }

    if (statusText) statusText.textContent = message || '-';
    if (statusCheckedAt) statusCheckedAt.textContent = checkedAt || '-';
  }

  if (toggleBtn && apiKeyInput) {
    toggleBtn.addEventListener('click', function () {
      var icon = this.querySelector('i');
      var nextType = apiKeyInput.type === 'password' ? 'text' : 'password';
      apiKeyInput.type = nextType;
      if (icon) {
        icon.classList.toggle('fa-eye');
        icon.classList.toggle('fa-eye-slash');
      }
    });
  }

  if (!testBtn) {
    return;
  }

  function getCookieValue(name) {
    var cookie = document.cookie || '';
    var parts = cookie.split(';');
    for (var i = 0; i < parts.length; i++) {
      var item = parts[i].trim();
      if (item.indexOf(name + '=') === 0) {
        return decodeURIComponent(item.substring(name.length + 1));
      }
    }
    return '';
  }

  testBtn.addEventListener('click', function () {
    var enabledEl = document.getElementById('ai_enabled');

    var payload = new URLSearchParams();
    payload.append('ai_enabled', enabledEl && enabledEl.checked ? '1' : '0');
    payload.append('ai_api_key', apiKeyInput ? apiKeyInput.value : '');

    var csrfToken = getCookieValue(csrfCookieName);
    if (csrfToken !== '') {
      payload.append(csrfTokenName, csrfToken);
    }

    testBtn.disabled = true;
    testBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i>Menguji...';

    fetch('<?php echo site_url('master/konfigurasi/test_ai_connection'); ?>', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: payload.toString()
    }).then(function (res) {
      return res.text().then(function (rawText) {
        var parsed = null;
        try {
          parsed = rawText ? JSON.parse(rawText) : {};
        } catch (e) {
          parsed = null;
        }

        return {
          ok: res.ok,
          status: res.status,
          data: parsed,
          rawText: rawText
        };
      });
    }).then(function (result) {
      var data = result.data || {};
      if (!result.data) {
        throw new Error(result.rawText || ('HTTP ' + result.status));
      }

      updateAiStatus(data.status || 'PENDING', data.message || '-', data.checked_at || '-');

      if (window.Swal) {
        if (result.ok && data.success) {
          Swal.fire({
            icon: 'success',
            title: 'Koneksi Berhasil',
            text: data.message || 'Koneksi API berhasil.',
            confirmButtonColor: '#800000'
          });
        } else {
          Swal.fire({
            icon: result.ok ? 'warning' : 'error',
            title: result.ok ? 'Koneksi Belum Berhasil' : 'Error',
            text: data.message || 'Gagal melakukan test koneksi API.',
            confirmButtonColor: '#800000'
          });
        }
      }
    }).catch(function (err) {
      var msg = 'Gagal melakukan test koneksi API.';
      if (err && err.message) {
        if (err.message.toLowerCase().indexOf('requested is not allowed') !== -1) {
          msg = 'Request ditolak CSRF. Silakan refresh halaman lalu coba lagi.';
        } else if (err.message.toLowerCase().indexOf('<!doctype html') !== -1 || err.message.toLowerCase().indexOf('<html') !== -1) {
          msg = 'Server mengembalikan halaman HTML, bukan JSON. Cek log PHP/CI atau route endpoint test koneksi.';
        } else {
          msg = err.message;
        }
      }

      updateAiStatus('DISCONNECTED', msg, '-');
      if (window.Swal) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: msg,
          confirmButtonColor: '#800000'
        });
      }
    }).finally(function () {
      testBtn.disabled = false;
      testBtn.innerHTML = '<i class="fa fa-plug mr-1"></i> Test Koneksi API';
    });
  });
});
</script>
