<?php
session_start();
$title = 'Cuentas asignadas';
require_once __DIR__ . '/../templates/header.php';
require_role(['admin', 'superadmin']);
csrf_check();
$error = null;
$notice = null;
$user_role = $_SESSION['user_role'] ?? '';
$user_id = $_SESSION['uid'] ?? 0;

// Obtener clientes asignados a este admin
$clientsStmt = pdo()->prepare('SELECT id, name, email FROM users WHERE role = :role AND admin_id = :admin_id ORDER BY name');
$clientsStmt->execute(['role' => 'client', 'admin_id' => $user_id]);
$clients = $clientsStmt->fetchAll();

// Obtener plataformas
$platsStmt = pdo()->query('SELECT id, name FROM platforms ORDER BY name');
$plats = $platsStmt->fetchAll();
?>
<!-- Filtros -->
<div class="card card-body mb-3" style="padding: 15px;">
  <div class="row g-3">
    <div class="col-md-6">
      <label for="cliente-select" class="form-label">Cliente:</label>
      <select id="cliente-select" class="form-select">
        <option value="">-- Selecciona un cliente --</option>
        <?php foreach ($clients as $c): ?>
          <option value="<?= e($c['id']) ?>"><?= e($c['name']) ?> (<?= e($c['email']) ?>)</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-6">
      <label for="platform-filter" class="form-label">Filtrar por plataforma:</label>
      <select id="platform-filter" class="form-select">
        <option value="">Todas</option>
        <?php foreach ($plats as $p): ?>
          <option value="<?= e($p['id']) ?>"><?= e($p['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
  </div>
</div>

<div class="row mb-2">
  <div class="col-md-6">
    <input type="text" id="search-email" class="form-control" placeholder="Buscar por correo...">
  </div>
</div>

<!-- Contenedor tabla dinámica -->
<div id="cliente-cuentas" class="table-responsive">
  <p class="text-muted">Selecciona un cliente para ver sus cuentas asignadas aquí.</p>
</div>

<script>
document.addEventListener('click', function(e) {
  if (e.target.classList.contains('add-row')) {
    e.preventDefault();
    const container = document.getElementById('multi-accounts');
    if (!container) return;
    const row = container.querySelector('.multi-row');
    if (!row) return;
    const clone = row.cloneNode(true);
    clone.querySelector('select[name="platform_id[]"]').value = '';
    clone.querySelector('input[name="email[]"]').value = '';
    clone.querySelector('input[name="expiration_date[]"]').value = '';
    clone.querySelector('input[name="price[]"]').value = '';
    const btn = clone.querySelector('.btn-success');
    btn.classList.remove('btn-success', 'add-row');
    btn.classList.add('btn-danger', 'remove-row');
    btn.textContent = '-';
    container.appendChild(clone);
  } else if (e.target.classList.contains('remove-row')) {
    e.preventDefault();
    e.target.closest('.multi-row').remove();
  }
});

function attachSaveEvent(button, row) {
  button.onclick = function() {
    const emailInput = row.querySelector('input[type=email]');
    const expirationInput = row.querySelector('input[type=date]');
    const priceInput = row.querySelector('input[type=number]');
    const email = emailInput.value.trim();
    const expirationRaw = expirationInput.value; // AAAA-MM-DD
    const price = priceInput.value.trim();
    const id = row.getAttribute('data-id');

    if (!email) {
      alert('El correo no puede estar vacío.');
      return;
    }

    fetch(`ajax_client_assigned.php?client_id=${encodeURIComponent(currentClient)}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `action=update&id=${encodeURIComponent(id)}&email=${encodeURIComponent(email)}&expiration_date=${encodeURIComponent(expirationRaw)}&price=${encodeURIComponent(price)}`
    }).then(res => res.json()).then(res => {
      if (res.success) {
        const expiration = expirationRaw === '' ? 'N/A' : formatearFecha(expirationRaw);
        row.querySelector('.email-cell').textContent = email;
        row.querySelector('.expiration-cell').textContent = expiration;
        row.querySelector('.price-cell').textContent = parseFloat(price).toFixed(2);

        const estado = calcularEstadoCaducidad(expiration);
        // Actualiza la celda "Días restantes" que es la 5ª columna (index 4)
        row.querySelector('td:nth-child(5)').textContent = estado.texto;

        row.classList.remove('table-danger', 'table-warning', 'row-danger', 'row-warning');
        if (estado.clase) {
          row.classList.add(estado.clase);
        }

        button.textContent = 'Editar';
        button.classList.remove('btn-save');
        button.classList.add('btn-edit');

        attachActionEvents();
      } else {
        alert('Error al guardar cambios.');
      }
    }).catch(() => {
      alert('Error en la conexión al guardar.');
    });
  };
}

document.getElementById('cliente-select').addEventListener('change', function() {
  cargarCuentas(this.value, 1, document.getElementById('platform-filter').value, document.getElementById('search-email').value.trim());
});

document.getElementById('platform-filter').addEventListener('change', function() {
  cargarCuentas(document.getElementById('cliente-select').value, 1, this.value, document.getElementById('search-email').value.trim());
});

document.getElementById('search-email').addEventListener('input', function() {
  cargarCuentas(document.getElementById('cliente-select').value, 1, document.getElementById('platform-filter').value, this.value.trim());
});

let currentPage = 1;
let currentClient = null;
let currentPlatform = '';
let currentEmail = '';

function cargarCuentas(clientId, page = 1, platform = '', email = '') {
  if (!clientId) {
    document.getElementById('cliente-cuentas').innerHTML = '<p class="text-muted">Selecciona un cliente para ver sus cuentas asignadas.</p>';
    return;
  }
  currentClient = clientId;
  currentPage = page;
  currentPlatform = platform;
  currentEmail = email;

  fetch(`ajax_client_assigned.php?client_id=${encodeURIComponent(clientId)}&page=${page}&platform_id=${encodeURIComponent(platform)}&search_email=${encodeURIComponent(email)}`)
    .then(res => res.json())
    .then(data => {
      if (data.error) {
        document.getElementById('cliente-cuentas').innerHTML = `<p class="text-danger">${data.error}</p>`;
      } else if (data.html && data.html.trim() !== '') {
        document.getElementById('cliente-cuentas').innerHTML = data.html;
        attachPaginationEvents();
        attachActionEvents();
      } else {
        document.getElementById('cliente-cuentas').innerHTML = '<p>No hay cuentas asignadas para este filtro.</p>';
      }
    })
    .catch(() => {
      document.getElementById('cliente-cuentas').innerHTML = '<p>Error cargando cuentas.</p>';
    });
}

function attachPaginationEvents() {
  document.querySelectorAll('.pagination a.page-link').forEach(link => {
    link.onclick = function(e) {
      e.preventDefault();
      const page = parseInt(this.getAttribute('data-page'));
      cargarCuentas(currentClient, page, currentPlatform, currentEmail);
    };
  });
}

function attachActionEvents() {
  document.querySelectorAll('.btn-edit').forEach(button => {
    button.onclick = function() {
      const row = this.closest('tr');
      const emailCell = row.querySelector('.email-cell');
      const expirationCell = row.querySelector('.expiration-cell');
      const priceCell = row.querySelector('.price-cell');
      const emailText = emailCell.textContent;
      const expirationText = expirationCell.textContent;
      const priceText = priceCell.textContent;

      if (emailCell.querySelector('input')) return;
		
      emailCell.innerHTML = `<input type="email" class="form-control form-control-sm" value="${emailText}" />`;
      expirationCell.innerHTML = `<input type="date" class="form-control form-control-sm" value="${expirationText === 'N/A' || expirationText === 'Expirada' ? '' : expirationText.split('/').reverse().join('-')}" />`;
      priceCell.innerHTML = `<input type="number" class="form-control form-control-sm" value="${priceText}" min="0" step="0.01" />`;

      this.textContent = 'Guardar';
      this.classList.remove('btn-edit');
      this.classList.add('btn-save');

      attachSaveEvent(this, row);
    };
  });

  document.querySelectorAll('.btn-save').forEach(button => {
    const row = button.closest('tr');
    button.onclick = function() {
      attachSaveEvent(button, row);
    };
  });

  document.querySelectorAll('.btn-delete').forEach(button => {
    button.onclick = function() {
      if (!confirm('¿Eliminar esta asignación?')) return;
      const row = this.closest('tr');
      const id = row.getAttribute('data-id');
      fetch(`ajax_client_assigned.php?client_id=${encodeURIComponent(currentClient)}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `action=delete&id=${encodeURIComponent(id)}`
      }).then(r => r.json()).then(res => {
        if (res.success) {
          cargarCuentas(currentClient, currentPage, currentPlatform, currentEmail);
        } else {
          alert('Error al eliminar');
        }
      }).catch(() => {
        alert('Error en la conexión al eliminar.');
      });
    };
  });
}

// Formatea AAAA-MM-DD a DD/MM/AAAA
function formatearFecha(fecha) {
  if (!fecha) return 'N/A';
  const parts = fecha.split('-');
  if (parts.length === 3) {
    return `${parts[2]}/${parts[1]}/${parts[0]}`;
  }
  return fecha;
}

// Calcula estado basado en caducidad para colorear fila
function calcularEstadoCaducidad(fecha) {
  if (!fecha) return { texto: 'N/A', clase: '' };
  const parts = fecha.split('/');
  if (parts.length !== 3) return { texto: fecha, clase: '' };
  const exp = new Date(parts[2], parts[1] - 1, parts[0]);
  const hoy = new Date();
  const hoySinHoras = new Date(hoy.getFullYear(), hoy.getMonth(), hoy.getDate());
  const expSinHoras = new Date(exp.getFullYear(), exp.getMonth(), exp.getDate());
  const diffMs = expSinHoras - hoySinHoras;
  const diffDias = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  if (diffDias < 0) return { texto: 'Expirada', clase: 'row-danger table-danger' };
  if (diffDias === 0) return { texto: 'Vence hoy', clase: 'row-warning table-warning' };
  if (diffDias === 1) return { texto: 'Vence mañana', clase: 'row-warning table-warning' };
  return { texto: diffDias + ' días', clase: '' };
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
