<?php
require_once __DIR__ . '/includes/db.php';

$pageTitle  = 'Sesiuni titluri';
$breadcrumb = [['label' => 'Sesiuni titluri']];

$sessions = [];
$dbError = null;
try {
    $sessions = db_select(
        "SELECT s.*,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id) AS items_count,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id AND sent_status = 'success') AS success_count,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id AND sent_status = 'failed')  AS failed_count,
                (SELECT COUNT(*) FROM title_session_items WHERE session_id = s.id AND sent_status = 'pending') AS pending_count
         FROM title_sessions s
         ORDER BY s.updated_at DESC"
    );
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

require __DIR__ . '/includes/header.php';
?>

<?php if ($dbError): ?>
  <div class="mb-6 bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm text-amber-900">
    Eroare DB: <pre class="mt-2 text-xs"><?= e($dbError) ?></pre>
  </div>
<?php endif; ?>

<div x-data="sessionsPage(<?= htmlspecialchars(json_encode($sessions), ENT_QUOTES, 'UTF-8') ?>)">

  <div class="flex items-center justify-between mb-4">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">Sesiuni schimbare titluri</h1>
      <p class="text-sm text-slate-500 mt-0.5">
        Pregătește batch-uri cu titluri noi pentru produse, apoi trimite la eMAG într-un singur click.
      </p>
    </div>
    <button @click="openAdd()"
      class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg shadow-soft transition">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
      Sesiune nouă
    </button>
  </div>

  <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden">
    <template x-if="all.length === 0">
      <div class="p-10 text-center text-sm text-slate-400">
        Nicio sesiune încă.<br>
        Creează una și adaugă produse din pagina <a href="<?= url('products.php') ?>" class="text-brand-600 hover:underline">Produse</a> → bulk action „Adaugă în sesiune".
      </div>
    </template>
    <template x-if="all.length > 0">
      <table class="w-full text-sm">
        <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
          <tr class="divide-x divide-slate-200">
            <th class="px-3 py-2.5 text-left font-medium">Nume</th>
            <th class="px-3 py-2.5 text-left font-medium">Status</th>
            <th class="px-3 py-2.5 text-right font-medium">Items</th>
            <th class="px-3 py-2.5 text-left font-medium">Progres</th>
            <th class="px-3 py-2.5 text-left font-medium">Creată</th>
            <th class="px-3 py-2.5 text-right font-medium">Acțiuni</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
          <template x-for="s in all" :key="s.id">
            <tr class="hover:bg-slate-50 divide-x divide-slate-100">
              <td class="px-3 py-2.5">
                <a :href="'<?= url('title-session.php') ?>?id=' + s.id" class="font-medium text-brand-700 hover:underline" x-text="s.name"></a>
                <div class="text-[11px] text-slate-400 mt-0.5" x-show="s.description" x-text="s.description"></div>
              </td>
              <td class="px-3 py-2.5">
                <span class="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide font-semibold px-2 py-0.5 rounded-full"
                      :class="statusBadgeClass(s.status)" x-text="s.status"></span>
              </td>
              <td class="px-3 py-2.5 text-right text-sm font-semibold text-slate-700" x-text="s.items_count"></td>
              <td class="px-3 py-2.5 text-xs text-slate-600 whitespace-nowrap">
                <span x-show="parseInt(s.success_count) > 0" class="text-emerald-700">✓ <span x-text="s.success_count"></span></span>
                <span x-show="parseInt(s.failed_count) > 0" class="text-rose-700 ml-2">✗ <span x-text="s.failed_count"></span></span>
                <span x-show="parseInt(s.pending_count) > 0" class="text-amber-700 ml-2">⏳ <span x-text="s.pending_count"></span></span>
              </td>
              <td class="px-3 py-2.5 text-xs text-slate-500 whitespace-nowrap" x-text="formatDate(s.created_at)"></td>
              <td class="px-3 py-2.5 text-right whitespace-nowrap">
                <a :href="'<?= url('title-session.php') ?>?id=' + s.id" class="inline-block text-brand-600 hover:text-brand-700 p-1.5 rounded hover:bg-brand-50 transition" title="Deschide">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
                </a>
                <button @click="deleteSession(s)" class="text-rose-600 hover:text-rose-700 p-1.5 rounded hover:bg-rose-50 transition" title="Șterge">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"/></svg>
                </button>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </template>
  </div>

  <!-- ============== MODAL ============== -->
  <div x-show="modalOpen" x-cloak @keydown.escape.window="modalOpen = false"
       x-data="{ _bg: false }"
       @mousedown.self="_bg = true"
       @mouseup="if (_bg && $event.target === $el) modalOpen = false; _bg = false"
       class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
    <div class="modal-enter bg-white rounded-2xl shadow-2xl w-full max-w-lg">
      <form @submit.prevent="saveSession()">
        <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <h3 class="font-semibold text-slate-900" x-text="editing.id ? 'Editare sesiune' : 'Sesiune nouă'"></h3>
          <button type="button" @click="modalOpen = false" class="text-slate-400 hover:text-slate-600 p-1">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <div class="p-6 space-y-4">
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Nume sesiune *</label>
            <input type="text" x-model="editing.name" required maxlength="255"
              x-init="$nextTick(() => $el.focus())"
              placeholder="ex: Rebranding huse iPhone — Mai 2026"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
          </div>
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Descriere (opțional)</label>
            <textarea x-model="editing.description" rows="2" maxlength="500"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"></textarea>
          </div>
        </div>
        <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-2 rounded-b-2xl">
          <button type="button" @click="modalOpen = false" class="px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200 rounded-lg transition">Anulează</button>
          <button type="submit" :disabled="saving"
            class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg shadow-soft transition disabled:opacity-50">
            <span x-show="saving" class="spinner"></span>
            <span x-text="saving ? 'Salvez…' : 'Salvează'"></span>
          </button>
        </div>
      </form>
    </div>
  </div>

</div>

<script>
function sessionsPage(initial) {
  return {
    all: initial || [],
    modalOpen: false,
    saving: false,
    editing: {},
    csrf: '<?= e(csrf_token()) ?>',

    statusBadgeClass(s) {
      return {
        'draft':     'bg-slate-100 text-slate-700',
        'queued':    'bg-sky-100 text-sky-800',
        'sending':   'bg-amber-100 text-amber-800',
        'completed': 'bg-emerald-100 text-emerald-800',
        'partial':   'bg-amber-100 text-amber-800',
        'failed':    'bg-rose-100 text-rose-800',
      }[s] || 'bg-slate-100 text-slate-700';
    },

    formatDate(s) {
      if (!s) return '—';
      const d = new Date(s.replace(' ', 'T'));
      return d.toLocaleDateString('ro-RO') + ' ' + d.toLocaleTimeString('ro-RO', {hour:'2-digit', minute:'2-digit'});
    },

    openAdd() {
      this.editing = { id: 0, name: '', description: '' };
      this.modalOpen = true;
    },

    async saveSession() {
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        Object.entries(this.editing).forEach(([k, v]) => fd.append(k, v ?? ''));
        const r = await fetch('<?= url('api/save-session.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);
        const idx = this.all.findIndex(x => x.id == data.session.id);
        if (idx >= 0) this.all[idx] = data.session;
        else this.all.unshift(data.session);
        this.modalOpen = false;
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    },

    async deleteSession(s) {
      if (!confirm(`Ștergi sesiunea „${s.name}" cu ${s.items_count} itemi?`)) return;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', s.id);
        const r = await fetch('<?= url('api/delete-session.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);
        this.all = this.all.filter(x => x.id != s.id);
      } catch (e) {
        alert('Eroare: ' + e.message);
      }
    }
  };
}
</script>

<?php require __DIR__ . '/includes/footer.php'; ?>
