<%- include('../partials/header') %>

<style>
.segment-layout {
  display:grid;
  grid-template-columns:minmax(360px,.9fr) minmax(520px,1.5fr);
  gap:16px;
  align-items:start;
}

.segment-form-grid {
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:10px;
}

.segment-form-grid .full {
  grid-column:1 / -1;
}

.quick-presets {
  display:flex;
  flex-wrap:wrap;
  gap:7px;
  margin:8px 0 14px;
}

.preset-btn {
  border:1px solid #cbd5e1;
  border-radius:999px;
  background:#fff;
  padding:6px 10px;
  cursor:pointer;
  font-size:12px;
}

.preset-btn:hover {
  background:#f8fafc;
}

.rule-list {
  margin:6px 0 0;
  padding-left:18px;
}

.segment-count {
  font-size:30px;
  font-weight:800;
  line-height:1;
}

.preview-table td,
.preview-table th,
.saved-segments td,
.saved-segments th {
  font-size:12px;
  padding:8px 7px;
}

.badge-type {
  display:inline-block;
  border-radius:999px;
  padding:3px 7px;
  font-weight:800;
  font-size:11px;
  background:#eef2ff;
}

.order-time-extra {
  border:1px solid #e5e7eb;
  border-radius:10px;
  padding:10px;
  background:#f8fafc;
}

@media (max-width:1100px) {
  .segment-layout {
    grid-template-columns:1fr;
  }
}

@media (max-width:650px) {
  .segment-form-grid {
    grid-template-columns:1fr;
  }

  .segment-form-grid .full {
    grid-column:auto;
  }
}
</style>

<div class="segment-layout">
  <div>
    <form class="card" method="post" id="segment-form">
      <h2>Segment inteligent nou</h2>

      <p class="small">
        Combină filtrele. Clientul trebuie să îndeplinească toate condițiile selectate.
      </p>

      <div class="quick-presets">
        <button type="button" class="preset-btn" data-preset="compressor">
          Compresoare
        </button>

        <button type="button" class="preset-btn" data-preset="airless">
          Pompe de zugrăvit
        </button>

        <button type="button" class="preset-btn" data-preset="inactive30">
          Inactivi 30 zile
        </button>

        <button type="button" class="preset-btn" data-preset="inactive90">
          Inactivi 90 zile
        </button>

        <button type="button" class="preset-btn" data-preset="high1000">
          Peste 1.000 RON
        </button>

        <button type="button" class="preset-btn" data-preset="repeat3">
          Minimum 3 comenzi
        </button>
      </div>

      <div class="segment-form-grid">
        <label>
          Magazin
          <select name="store_id">
            <option value="">Toate magazinele</option>
            <% stores.forEach(s => { %>
              <option
                value="<%= s.id %>"
                <%= String(form.store_id || '')===String(s.id)?'selected':'' %>
              >
                <%= s.name %>
              </option>
            <% }) %>
          </select>
        </label>

        <label>
          PF / PJ
          <select name="customer_type">
            <option value="">PF + PJ</option>
            <option value="PF" <%= form.customer_type==='PF'?'selected':'' %>>
              Persoană fizică
            </option>
            <option value="PJ" <%= form.customer_type==='PJ'?'selected':'' %>>
              Firmă / PJ
            </option>
          </select>
        </label>

        <label class="full">
          Categorie cumpărată conține
          <input
            name="category_contains"
            list="segment-categories"
            value="<%= form.category_contains || '' %>"
            placeholder="Ex: Compresoare, Pompe de zugrăvit, Fitinguri aer comprimat"
          >
          <datalist id="segment-categories">
            <% categories.forEach(c => { %>
              <option value="<%= c.category %>"></option>
            <% }) %>
          </datalist>
        </label>

        <label>
          A cumpărat produsul (SKU)
          <input
            name="product_sku"
            value="<%= form.product_sku || '' %>"
            placeholder="Ex: KD1188"
          >
        </label>

        <label>
          NU a cumpărat produsul (SKU)
          <input
            name="exclude_product_sku"
            value="<%= form.exclude_product_sku || '' %>"
            placeholder="Ex: KD1189"
          >
        </label>

        <label class="full">
          Perioada comenzilor
          <select name="order_time_mode" id="order_time_mode">
            <option value="any" <%= (form.order_time_mode||'any')==='any'?'selected':'' %>>
              Nu contează perioada
            </option>
            <option value="has_orders" <%= form.order_time_mode==='has_orders'?'selected':'' %>>
              Cu cel puțin o comandă
            </option>
            <option value="no_orders" <%= form.order_time_mode==='no_orders'?'selected':'' %>>
              Fără nicio comandă / nu a comandat niciodată
            </option>
            <option value="no_order_last_days" <%= form.order_time_mode==='no_order_last_days'?'selected':'' %>>
              Fără comandă în ultimele X zile
            </option>
            <option value="has_order_last_days" <%= form.order_time_mode==='has_order_last_days'?'selected':'' %>>
              Cu comandă în ultimele X zile
            </option>
            <option value="last_order_between_days" <%= form.order_time_mode==='last_order_between_days'?'selected':'' %>>
              Ultima comandă între X și Y zile în urmă
            </option>
            <option value="has_order_between_dates" <%= form.order_time_mode==='has_order_between_dates'?'selected':'' %>>
              Cu comandă într-un interval de date
            </option>
            <option value="no_order_between_dates" <%= form.order_time_mode==='no_order_between_dates'?'selected':'' %>>
              Fără comandă într-un interval de date
            </option>
          </select>
        </label>

        <div class="full order-time-extra" id="order-days-box">
          <label>
            Număr zile (X)
            <input
              type="number"
              min="1"
              max="3650"
              name="order_days"
              value="<%= form.order_days || form.inactive_days || '' %>"
              placeholder="Ex: 45"
            >
          </label>
          <div class="quick-presets" style="margin-top:7px;margin-bottom:0">
            <% [7,14,30,45,60,90,120,180,365].forEach(n => { %>
              <button type="button" class="preset-btn order-days-preset" data-days="<%= n %>"><%= n %> zile</button>
            <% }) %>
          </div>
        </div>

        <div class="full order-time-extra" id="order-days-range-box">
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
            <label>
              De la X zile în urmă
              <input type="number" min="0" max="3650" name="order_days_from" value="<%= form.order_days_from || '' %>" placeholder="Ex: 30">
            </label>
            <label>
              Până la Y zile în urmă
              <input type="number" min="1" max="3650" name="order_days_to" value="<%= form.order_days_to || '' %>" placeholder="Ex: 90">
            </label>
          </div>
          <div class="quick-presets" style="margin-top:7px;margin-bottom:0">
            <button type="button" class="preset-btn order-range-preset" data-from="0" data-to="30">0–30 zile</button>
            <button type="button" class="preset-btn order-range-preset" data-from="30" data-to="60">30–60 zile</button>
            <button type="button" class="preset-btn order-range-preset" data-from="30" data-to="90">30–90 zile</button>
            <button type="button" class="preset-btn order-range-preset" data-from="60" data-to="90">60–90 zile</button>
            <button type="button" class="preset-btn order-range-preset" data-from="90" data-to="180">90–180 zile</button>
            <button type="button" class="preset-btn order-range-preset" data-from="180" data-to="365">180–365 zile</button>
          </div>
        </div>

        <div class="full order-time-extra" id="order-date-range-box">
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
            <label>
              Data de la
              <input type="date" name="order_date_from" value="<%= form.order_date_from || '' %>">
            </label>
            <label>
              Data până la
              <input type="date" name="order_date_to" value="<%= form.order_date_to || '' %>">
            </label>
          </div>
        </div>

        <label>
          Valoare cumpărături minimă
          <select name="min_spent">
            <option value="">Nu contează</option>
            <% [500,1000,2000,5000,10000].forEach(n => { %>
              <option
                value="<%= n %>"
                <%= Number(form.min_spent||0)===n?'selected':'' %>
              >
                <%= n.toLocaleString('ro-RO') %> RON
              </option>
            <% }) %>
          </select>
        </label>

        <label>
          Minimum comenzi
          <select name="min_orders">
            <option value="">Nu contează</option>
            <% [2,3,5,10].forEach(n => { %>
              <option
                value="<%= n %>"
                <%= Number(form.min_orders||0)===n?'selected':'' %>
              >
                <%= n %> comenzi
              </option>
            <% }) %>
          </select>
        </label>

        <label class="full">
          Blacklist comenzi
          <select name="blacklist_mode">
            <option
              value="exclude"
              <%= (form.blacklist_mode || 'exclude')==='exclude'?'selected':'' %>
            >
              Exclude clienții cu comenzi anulate / refuzate / neridicate
            </option>

            <option
              value="include"
              <%= form.blacklist_mode==='include'?'selected':'' %>
            >
              Include și clienții blacklist
            </option>

            <option
              value="only"
              <%= form.blacklist_mode==='only'?'selected':'' %>
            >
              Doar clienții blacklist
            </option>
          </select>

          <div class="small" style="margin-top:4px">
            Blacklist = client cu cel puțin o comandă anulată, refuzată, neridicată/nepreluată sau retur la expeditor.
          </div>
        </label>

        <div>
          <label style="display:flex;gap:8px;align-items:center;margin-top:29px">
            <input
              type="checkbox"
              name="active_customers_only"
              value="1"
              style="width:auto"
              <%= form.active_customers_only ? 'checked' : '' %>
            >
            Doar clienți care au comandat
          </label>
        </div>

        <div class="full">
          <label style="display:flex;gap:8px;align-items:center">
            <input
              type="checkbox"
              name="marketing_only"
              value="1"
              style="width:auto"
              <%= form.marketing_only ? 'checked' : '' %>
            >
            Doar contacte eligibile pentru marketing
          </label>
        </div>

        <label class="full">
          Nume segment
          <input
            name="name"
            value="<%= form.name || '' %>"
            placeholder="Ex: Compresoare – inactivi 60 zile"
          >
        </label>
      </div>

      <div class="toolbar" style="margin-top:14px">
        <button
          class="btn"
          type="submit"
          formaction="/segments/preview"
        >
          Previzualizează
        </button>

        <button
          class="btn primary"
          type="submit"
          formaction="/segments/create"
          onclick="
            if(!this.form.name.value.trim()){
              alert('Completează numele segmentului înainte de salvare.');
              return false;
            }
            return confirm('Salvezi acest segment?');
          "
        >
          Salvează segment
        </button>
      </div>
    </form>

    <% if (preview) { %>
      <div class="card" style="margin-top:16px">
        <div class="segment-count"><%= preview.total %></div>
        <div class="small">clienți se potrivesc segmentului</div>

        <ul class="rule-list">
          <% preview.summary.forEach(x => { %>
            <li><%= x %></li>
          <% }) %>
        </ul>

        <p class="small" style="margin-top:10px">
          Sunt afișați maximum 50 clienți în previzualizare.
        </p>

        <table class="preview-table">
          <thead>
            <tr>
              <th>Email</th>
              <th>Tip</th>
              <th>Client</th>
              <th>Comenzi</th>
              <th>Valoare</th>
              <th>Blacklist</th>
            </tr>
          </thead>

          <tbody>
            <% preview.contacts.forEach(c => { %>
              <tr>
                <td>
                  <a href="/contacts/<%= c.id %>"><%= c.email %></a>
                </td>
                <td>
                  <span class="badge-type"><%= c.customer_type || '-' %></span>
                </td>
                <td>
                  <%= c.company_name ||
                      [c.first_name,c.last_name].filter(Boolean).join(' ') ||
                      '-' %>
                </td>
                <td><%= c.total_orders || 0 %></td>
                <td><%= Number(c.total_spent || 0).toFixed(2) %> RON</td>
                <td>
                  <%= Number(c.is_blacklisted)===1
                    ? (c.blacklist_status || 'DA')
                    : 'Nu' %>
                </td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>
    <% } %>
  </div>

  <div class="card">
    <h2>Segmente salvate</h2>

    <% if (!segments.length) { %>
      <p class="small">Nu există încă segmente salvate.</p>
    <% } else { %>
      <table class="saved-segments">
        <thead>
          <tr>
            <th>Nume</th>
            <th>Magazin</th>
            <th>Reguli</th>
            <th>Clienți acum</th>
            <th></th>
          </tr>
        </thead>

        <tbody>
          <% segments.forEach(s => { %>
            <tr>
              <td>
                <strong><%= s.name %></strong>
              </td>

              <td><%= s.store_name || 'Toate' %></td>

              <td>
                <% s.rule_summary.slice(0,3).forEach(x => { %>
                  <div class="small"><%= x %></div>
                <% }) %>

                <% if (s.rule_summary.length > 3) { %>
                  <div class="small">
                    + încă <%= s.rule_summary.length - 3 %> reguli
                  </div>
                <% } %>
              </td>

              <td>
                <strong><%= s.live_count %></strong>
              </td>

              <td>
                <a class="btn" href="/segments/<%= s.id %>">
                  Deschide
                </a>
              </td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    <% } %>
  </div>
</div>

<script>
(function () {
  const form = document.getElementById('segment-form');
  if (!form) return;

  function set(name, value) {
    const el = form.elements[name];
    if (!el) return;
    if (el.type === 'checkbox') {
      el.checked = Boolean(value);
    } else {
      el.value = value;
    }
  }

  document.querySelectorAll('[data-preset]').forEach(btn => {
    btn.addEventListener('click', () => {
      const p = btn.dataset.preset;

      // Reset criteriile principale, păstrând magazinul.
      [
        'category_contains',
        'product_sku',
        'exclude_product_sku',
        'inactive_days',
        'order_time_mode',
        'order_days',
        'order_days_from',
        'order_days_to',
        'order_date_from',
        'order_date_to',
        'customer_type',
        'min_spent',
        'min_orders',
        'name'
      ].forEach(k => set(k, ''));

      set('active_customers_only', true);

      if (p === 'compressor') {
        set('category_contains', 'compres');
        set('name', 'Clienți compresoare');
      }

      if (p === 'airless') {
        set('category_contains', 'zugrav');
        set('name', 'Clienți pompe de zugrăvit');
      }

      if (p === 'inactive30') {
        set('order_time_mode', 'no_order_last_days');
        set('order_days', '30');
        set('name', 'Clienți fără comandă în ultimele 30 zile');
      }

      if (p === 'inactive90') {
        set('order_time_mode', 'no_order_last_days');
        set('order_days', '90');
        set('name', 'Clienți fără comandă în ultimele 90 zile');
      }

      if (p === 'high1000') {
        set('min_spent', '1000');
        set('name', 'Clienți peste 1.000 RON');
      }

      if (p === 'repeat3') {
        set('min_orders', '3');
        set('name', 'Clienți recurenți minimum 3 comenzi');
      }
    });
  });

  const timeMode = form.elements.order_time_mode;
  const daysBox = document.getElementById('order-days-box');
  const daysRangeBox = document.getElementById('order-days-range-box');
  const dateRangeBox = document.getElementById('order-date-range-box');

  function refreshTimeFields() {
    const mode = timeMode ? timeMode.value : 'any';

    if (daysBox) {
      daysBox.style.display =
        ['no_order_last_days','has_order_last_days'].includes(mode)
          ? 'block' : 'none';
    }

    if (daysRangeBox) {
      daysRangeBox.style.display =
        mode === 'last_order_between_days'
          ? 'block' : 'none';
    }

    if (dateRangeBox) {
      dateRangeBox.style.display =
        ['has_order_between_dates','no_order_between_dates'].includes(mode)
          ? 'block' : 'none';
    }
  }

  if (timeMode) {
    timeMode.addEventListener('change',refreshTimeFields);
    refreshTimeFields();
  }

  document.querySelectorAll('.order-days-preset').forEach(btn => {
    btn.addEventListener('click',() => {
      set('order_days',btn.dataset.days);
    });
  });

  document.querySelectorAll('.order-range-preset').forEach(btn => {
    btn.addEventListener('click',() => {
      set('order_days_from',btn.dataset.from);
      set('order_days_to',btn.dataset.to);
    });
  });
})();
</script>

<%- include('../partials/footer') %>
