<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<style>
:root {
  --teal-800: #0b5a52; --teal-700: #0b7a6e; --teal-600: #0d9488;
  --teal-500: #14b8a6; --teal-400: #2dd4bf; --teal-100: #ccfbf1; --teal-50: #f0fdfa;
  --red-500: #ef4444; --amber-50: #fffbeb; --amber-100: #fef3c7; --amber-600: #d97706;
  --slate-50:#f8fafc; --slate-100:#f1f5f9; --slate-200:#e2e8f0;
  --slate-400:#94a3b8; --slate-500:#64748b; --slate-700:#334155; --slate-900:#0f172a;
  --radius: 14px; --radius-sm: 9px; --radius-xs: 6px;
  --shadow: 0 4px 24px rgba(13,148,136,0.10), 0 1px 4px rgba(0,0,0,0.05);
}

.pt-wrapper { max-width: 720px; margin: 0 auto; }

/* Header */
.pt-header {
  display: flex; justify-content: space-between;
  align-items: flex-start; flex-wrap: wrap;
  gap: 14px; margin-bottom: 24px;
}
.pt-header-left h4 {
  font-size: 1.2rem; font-weight: 800; color: var(--teal-800);
  margin: 0 0 5px; display: flex; align-items: center; gap: 11px; letter-spacing: -.3px;
}
.pt-header-left h4 .hi {
  width: 40px; height: 40px; border-radius: 11px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1rem;
  box-shadow: 0 4px 12px rgba(13,148,136,0.32); flex-shrink: 0;
}
.pt-breadcrumb {
  display: flex; align-items: center; gap: 6px;
  font-size: 0.77rem; color: var(--slate-400); padding-left: 51px;
}
.pt-breadcrumb a { color: var(--teal-600); text-decoration: none; font-weight: 600; }
.pt-breadcrumb .sep { color: var(--slate-200); }

.btn-back {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 8px 18px; border-radius: 50px;
  border: 1.5px solid var(--slate-200); background: #fff;
  color: var(--slate-700); font-size: 0.83rem; font-weight: 600;
  text-decoration: none; transition: all .2s;
}
.btn-back:hover { border-color: var(--teal-400); color: var(--teal-700); background: var(--teal-50); }

/* Card */
.pt-card {
  background: #fff; border-radius: var(--radius);
  box-shadow: var(--shadow); border: 1.5px solid var(--slate-100);
  overflow: hidden; margin-bottom: 0;
  border-top: 3px solid var(--teal-500);
}
.pt-card-header {
  padding: 18px 26px; border-bottom: 1.5px solid var(--slate-100);
  background: var(--slate-50); font-size: 0.92rem; font-weight: 700;
  color: var(--teal-800); display: flex; align-items: center; gap: 8px;
}
.pt-card-header i { color: var(--teal-500); }
.pt-card-body { padding: 26px; }

/* Flash */
.val-error {
  background: #fef2f2; border-left: 4px solid var(--red-500);
  border-radius: var(--radius-sm); padding: 12px 16px;
  font-size: 0.83rem; color: #7f1d1d; margin-bottom: 18px;
  display: flex; gap: 10px; align-items: flex-start;
}

/* Form */
.form-section-title {
  font-size: 0.7rem; font-weight: 800; text-transform: uppercase;
  letter-spacing: .6px; color: var(--slate-400);
  margin: 24px 0 14px; padding-bottom: 8px;
  border-bottom: 1.5px solid var(--slate-100);
}
.form-section-title:first-child { margin-top: 0; }

.form-group-c { margin-bottom: 18px; }
.form-label-c {
  display: block; font-size: 0.78rem; font-weight: 700;
  color: var(--slate-500); margin-bottom: 7px;
}
.form-label-c span.req { color: var(--red-500); }
.form-label-c .hint { font-weight: 400; color: var(--slate-400); font-size: 0.73rem; margin-left: 4px; }

.form-control-c, .form-select-c, .form-textarea-c {
  width: 100%; padding: 10px 14px; border: 1.5px solid var(--slate-200);
  border-radius: var(--radius-sm); font-size: 0.87rem; color: var(--slate-900);
  background: #fff; box-sizing: border-box; font-family: inherit;
  transition: border-color .2s, box-shadow .2s;
}
.form-control-c:focus, .form-select-c:focus, .form-textarea-c:focus {
  border-color: var(--teal-600); box-shadow: 0 0 0 3px rgba(13,148,136,0.12);
  outline: none;
}
.form-textarea-c { resize: vertical; min-height: 90px; line-height: 1.6; }

/* Date row */
.date-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }

/* Opsi polling */
.opsi-list { display: flex; flex-direction: column; gap: 10px; margin-bottom: 12px; }
.opsi-item {
  display: flex; align-items: center; gap: 8px;
  background: var(--slate-50); border: 1.5px solid var(--slate-200);
  border-radius: var(--radius-sm); padding: 8px 12px;
  transition: border-color .18s;
}
.opsi-item:focus-within { border-color: var(--teal-400); background: var(--teal-50); }
.opsi-drag {
  color: var(--slate-300); cursor: grab; font-size: 1.1rem; flex-shrink: 0;
  touch-action: none;
}
.opsi-num {
  width: 24px; height: 24px; border-radius: 50%;
  background: var(--teal-600); color: #fff;
  font-size: 0.7rem; font-weight: 800;
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}
.opsi-input {
  flex: 1; border: none; background: transparent;
  font-size: 0.87rem; color: var(--slate-900); outline: none;
  font-family: inherit;
}
.opsi-del {
  color: var(--slate-300); cursor: pointer; font-size: 1rem;
  background: none; border: none; padding: 0; line-height: 1;
  flex-shrink: 0; transition: color .15s;
}
.opsi-del:hover { color: var(--red-500); }

.btn-add-opsi {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 8px 16px; border-radius: var(--radius-sm);
  border: 1.5px dashed var(--teal-300);
  background: var(--teal-50); color: var(--teal-700);
  font-size: 0.82rem; font-weight: 700;
  cursor: pointer; transition: all .18s;
  font-family: inherit;
}
.btn-add-opsi:hover { background: var(--teal-100); border-color: var(--teal-500); }

/* Toggle */
.toggle-row {
  display: flex; align-items: center; justify-content: space-between;
  background: var(--slate-50); border: 1.5px solid var(--slate-200);
  border-radius: var(--radius-sm); padding: 12px 16px;
  margin-bottom: 10px;
}
.toggle-info .ti-label { font-size: 0.86rem; font-weight: 700; color: var(--slate-700); }
.toggle-info .ti-desc  { font-size: 0.74rem; color: var(--slate-400); margin-top: 2px; }
.form-switch-c { position: relative; display: inline-block; width: 44px; height: 24px; }
.form-switch-c input { opacity: 0; width: 0; height: 0; }
.slider-c {
  position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
  background: var(--slate-200); border-radius: 24px; transition: .3s;
}
.slider-c:before {
  content: ""; position: absolute; height: 18px; width: 18px;
  left: 3px; bottom: 3px; background: #fff; border-radius: 50%;
  transition: .3s; box-shadow: 0 1px 4px rgba(0,0,0,.18);
}
input:checked + .slider-c { background: var(--teal-600); }
input:checked + .slider-c:before { transform: translateX(20px); }

/* Footer */
.pt-footer {
  display: flex; justify-content: space-between; align-items: center;
  gap: 10px; margin-top: 26px; padding-top: 20px;
  border-top: 1.5px solid var(--slate-100); flex-wrap: wrap;
}
.btn-submit {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 11px 28px; border-radius: var(--radius-sm); border: none;
  background: linear-gradient(135deg, var(--teal-800), var(--teal-600));
  color: #fff; font-size: 0.9rem; font-weight: 700; cursor: pointer;
  box-shadow: 0 4px 14px rgba(13,148,136,0.32); transition: all .2s;
  font-family: inherit;
}
.btn-submit:hover {
  background: linear-gradient(135deg, var(--teal-900), var(--teal-700));
  transform: translateY(-1px);
}

/* Hidden opsi inputs */
#opsi-hidden-inputs { display: none; }

@media (max-width: 600px) {
  .pt-wrapper { padding: 0 0 60px; }
  .pt-card-body { padding: 18px 16px; }
  .date-row { grid-template-columns: 1fr; }
  .pt-footer { flex-direction: column-reverse; }
  .btn-submit, .btn-back { width: 100%; justify-content: center; }
}
</style>

<div class="pt-wrapper">

  <!-- ── Header ────────────────────────────────────────────── -->
  <div class="pt-header">
    <div class="pt-header-left">
      <h4>
        <span class="hi"><i class="bi bi-bar-chart-fill"></i></span>
        <?php echo isset($edit_mode) && $edit_mode ? 'Edit Polling' : 'Buat Polling Baru'; ?>
      </h4>
      <div class="pt-breadcrumb">
        <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
        <span class="sep">/</span>
        <a href="<?php echo base_url('polling'); ?>">Polling</a>
        <span class="sep">/</span>
        <span><?php echo isset($edit_mode) && $edit_mode ? 'Edit' : 'Tambah'; ?></span>
      </div>
    </div>
    <a href="<?php echo base_url('polling'); ?>" class="btn-back">
      <i class="bi bi-arrow-left"></i> Kembali
    </a>
  </div>

  <!-- ── Card Form ──────────────────────────────────────────── -->
  <div class="pt-card">
    <div class="pt-card-header">
      <i class="bi bi-ui-checks"></i>
      <?php echo isset($edit_mode) && $edit_mode ? 'Form Edit Polling' : 'Form Polling Baru'; ?>
    </div>
    <div class="pt-card-body">

      <?php if(validation_errors()): ?>
      <div class="val-error">
        <i class="bi bi-exclamation-triangle-fill" style="color:var(--red-500);flex-shrink:0;margin-top:1px"></i>
        <div><?php echo validation_errors(); ?></div>
      </div>
      <?php endif; ?>

      <?php
      $action = (isset($edit_mode) && $edit_mode)
        ? base_url('polling/update/'.$item->id)
        : base_url('polling/simpan');
      echo form_open($action, ['id'=>'formPolling']);
      ?>

      <!-- ── INFO DASAR ──────────────────────────────────── -->
      <div class="form-section-title">Informasi Polling</div>

      <div class="form-group-c">
        <label class="form-label-c">Judul Polling <span class="req">*</span></label>
        <input type="text" name="judul" class="form-control-c"
               placeholder="Contoh: Lokasi Pembangunan Taman RT..."
               value="<?php echo set_value('judul', isset($item) ? $item->judul : ''); ?>" required>
      </div>

      <div class="form-group-c">
        <label class="form-label-c">Deskripsi / Konteks
          <span class="hint">(opsional)</span>
        </label>
        <textarea name="deskripsi" class="form-textarea-c"
                  placeholder="Jelaskan latar belakang atau tujuan polling ini..."><?php echo set_value('deskripsi', isset($item) ? $item->deskripsi : ''); ?></textarea>
      </div>

      <div class="date-row">
        <div class="form-group-c" style="margin-bottom:0">
          <label class="form-label-c">Tanggal Mulai <span class="req">*</span></label>
          <input type="date" name="tanggal_mulai" class="form-control-c"
                 value="<?php echo set_value('tanggal_mulai', isset($item) ? $item->tanggal_mulai : date('Y-m-d')); ?>" required>
        </div>
        <div class="form-group-c" style="margin-bottom:0">
          <label class="form-label-c">Tanggal Selesai
            <span class="hint">(opsional)</span>
          </label>
          <input type="date" name="tanggal_selesai" class="form-control-c"
                 value="<?php echo set_value('tanggal_selesai', isset($item) && $item->tanggal_selesai ? $item->tanggal_selesai : ''); ?>">
        </div>
      </div>

      <!-- ── OPSI JAWABAN ────────────────────────────────── -->
      <div class="form-section-title">Opsi Jawaban <span style="color:var(--red-500)">*</span></div>

      <div class="opsi-list" id="opsiList">
        <!-- Dirender oleh JS -->
      </div>
      <button type="button" class="btn-add-opsi" id="btnAddOpsi">
        <i class="bi bi-plus-circle"></i> Tambah Opsi
      </button>

      <!-- Hidden inputs for opsi (submitted as JSON) -->
      <div id="opsi-hidden-inputs">
        <input type="hidden" name="opsi_json" id="opsiJson">
      </div>

      <!-- ── PENGATURAN ──────────────────────────────────── -->
      <div class="form-section-title">Pengaturan</div>

      <div class="toggle-row">
        <div class="toggle-info">
          <div class="ti-label">Tampilkan Hasil Real-time</div>
          <div class="ti-desc">Warga bisa melihat hasil sebelum polling selesai</div>
        </div>
        <label class="form-switch-c">
          <input type="checkbox" name="hasil_realtime" value="1"
                 <?php echo (set_value('hasil_realtime', isset($item) ? $item->hasil_realtime : '1') == '1') ? 'checked' : ''; ?>>
          <span class="slider-c"></span>
        </label>
      </div>

      <div class="toggle-row">
        <div class="toggle-info">
          <div class="ti-label">Izinkan Ganti Suara</div>
          <div class="ti-desc">Warga bisa mengubah pilihan sebelum polling ditutup</div>
        </div>
        <label class="form-switch-c">
          <input type="checkbox" name="izin_ganti" value="1"
                 <?php echo (set_value('izin_ganti', isset($item) ? $item->izin_ganti : '0') == '1') ? 'checked' : ''; ?>>
          <span class="slider-c"></span>
        </label>
      </div>

      <div class="toggle-row">
        <div class="toggle-info">
          <div class="ti-label">Polling Anonim</div>
          <div class="ti-desc">Identitas pemilih tidak ditampilkan pada hasil</div>
        </div>
        <label class="form-switch-c">
          <input type="checkbox" name="anonim" value="1"
                 <?php echo (set_value('anonim', isset($item) ? $item->anonim : '0') == '1') ? 'checked' : ''; ?>>
          <span class="slider-c"></span>
        </label>
      </div>

      <!-- Footer -->
      <div class="pt-footer">
        <a href="<?php echo base_url('polling'); ?>" class="btn-back">
          <i class="bi bi-x"></i> Batal
        </a>
        <button type="submit" class="btn-submit">
          <i class="bi bi-check-circle"></i>
          <?php echo isset($edit_mode) && $edit_mode ? 'Simpan Perubahan' : 'Buat Polling'; ?>
        </button>
      </div>

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

</div>

<script>
// ── Initial opsi data (from server on edit, or defaults on tambah) ──
var opsiData = <?php
  if(isset($item) && !empty($item->opsi_json)) {
    $opsiArr = json_decode($item->opsi_json, true) ?? [];
    echo json_encode(array_column($opsiArr, 'teks'));
  } else {
    echo '["",""]'; // 2 opsi kosong default
  }
?>;

// ── Render opsi list ──────────────────────────────────────────────
function renderOpsi() {
  var list = document.getElementById('opsiList');
  list.innerHTML = '';
  opsiData.forEach(function(val, idx) {
    var item = document.createElement('div');
    item.className = 'opsi-item';
    item.dataset.idx = idx;
    item.innerHTML =
      '<span class="opsi-drag bi bi-grip-vertical"></span>' +
      '<span class="opsi-num">' + (idx + 1) + '</span>' +
      '<input class="opsi-input" type="text" placeholder="Opsi ' + (idx + 1) + '..." ' +
        'value="' + escHtml(val) + '" ' +
        'oninput="opsiData[' + idx + ']=this.value" ' +
        'required>' +
      (opsiData.length > 2
        ? '<button type="button" class="opsi-del bi bi-x-circle" onclick="removeOpsi(' + idx + ')"></button>'
        : '');
    list.appendChild(item);
  });
}
function escHtml(s) {
  return (s||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;');
}
function removeOpsi(idx) {
  opsiData.splice(idx, 1); renderOpsi();
}
document.getElementById('btnAddOpsi').addEventListener('click', function() {
  if(opsiData.length >= 10) { alert('Maksimal 10 opsi.'); return; }
  opsiData.push(''); renderOpsi();
  var inputs = document.querySelectorAll('.opsi-input');
  inputs[inputs.length - 1].focus();
});

// ── Sebelum submit: validasi & kumpulkan opsi ke JSON hidden ──────
document.getElementById('formPolling').addEventListener('submit', function(e) {
  var filled = opsiData.filter(function(v){ return v.trim() !== ''; });
  if(filled.length < 2) {
    e.preventDefault();
    alert('Minimal 2 opsi jawaban harus diisi!'); return;
  }
  var opsiArr = filled.map(function(t){ return {teks: t.trim(), suara: 0}; });
  document.getElementById('opsiJson').value = JSON.stringify(opsiArr);
  document.getElementById('opsi-hidden-inputs').style.display = '';
});

renderOpsi();
</script>