<?php
/**********************************************************
 *  admin/subjects_admin.php
 *  CRUD de asuntos de email por plataforma
 **********************************************************/

// 0) Conexión y sesión
require_once __DIR__ . '/conexion.php';          // $pdo
require_once __DIR__ . '/../config/config.php';  // inicia sesión

// 1) Autorización (solo administradores logueados)
if (empty($_SESSION['admin_id'])) {
    header('Location: ../login_admin.php');
    exit;
}

// 2) CSRF
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/*==================  RUTAS AJAX  ==================*/

/* a) LISTAR ---------------------------------------*/
if (isset($_GET['ajax']) && $_GET['ajax'] === 'list') {
    header('Content-Type: application/json; charset=utf-8');
    $rows = $pdo->query("
        SELECT id, platform, subject_line
        FROM email_subjects
        WHERE active = 1
        ORDER BY id DESC 
    ")->fetchAll();
    echo json_encode(['data' => $rows]);
    exit;
}

/* b) CREATE / UPDATE / DELETE ---------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json; charset=utf-8');

    if (!hash_equals($csrf, $_POST['csrf'] ?? '')) {
        http_response_code(403);
        echo json_encode(['error' => 'CSRF inválido']);
        exit;
    }

    try {
        switch ($_POST['action']) {
            case 'create':
                $plat = trim($_POST['platform'] ?? '');
                $sub  = trim($_POST['subject']  ?? '');
                if ($plat === '' || $sub === '') throw new Exception('Campos requeridos vacíos');

                $pdo->prepare("
                    INSERT INTO email_subjects (platform, subject_line)
                    VALUES (?, ?)
                    ON DUPLICATE KEY UPDATE active = 1
                ")->execute([$plat, $sub]);

                echo json_encode(['success' => 'Asunto añadido']);
                break;

            case 'update':
                $id   = (int)($_POST['id'] ?? 0);
                $plat = trim($_POST['platform'] ?? '');
                $sub  = trim($_POST['subject']  ?? '');
                if ($id <= 0 || $plat === '' || $sub === '') throw new Exception('Datos inválidos');

                $pdo->prepare("
                    UPDATE email_subjects
                    SET platform = ?, subject_line = ?
                    WHERE id = ?
                ")->execute([$plat, $sub, $id]);

                echo json_encode(['success' => 'Asunto actualizado']);
                break;

            case 'delete':
                $id = (int)($_POST['id'] ?? 0);
                if ($id <= 0) throw new Exception('ID inválido');

                $pdo->prepare("UPDATE email_subjects SET active = 0 WHERE id = ?")
                    ->execute([$id]);

                echo json_encode(['success' => 'Asunto eliminado']);
                break;

            default:
                throw new Exception('Acción desconocida');
        }

    } catch (Exception $e) {
        http_response_code(422);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

/*==================  HTML  ==================*/
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Administrar asuntos de email</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- DataTables + Bootstrap 5 (CSS) -->
  <link href="https://cdn.datatables.net/1.13.8/css/dataTables.bootstrap5.min.css" rel="stylesheet">
  <!-- Bootstrap Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="icon" href="/images/logo/favicon.ico" type="image/x-icon">
</head>
<body class="bg-dark text-white">
<?php include 'navbar.php'; ?>
<div class="container py-4">
  <h1 class="h3 mb-4"><i class="bi bi-envelope-paper me-1"></i> Asuntos de correo</h1>

  <button id="btnAdd" class="btn btn-success mb-3">
    <i class="bi bi-plus-circle me-1"></i> Nuevo asunto
  </button>
  
<!-- Contenedor de toasts -->
<div class="position-fixed top-0 end-0 p-3" style="z-index: 1080">
  <div id="toastContainer"></div>
</div>

  <table id="subjectsTable" class="table table-striped table-dark table-bordered w-100">
    <thead>
      <tr>
        <th>ID</th>
        <th>Plataforma</th>
        <th>Asunto</th>
        <th style="width:100px">Acciones</th>
      </tr>
    </thead>
  </table>
</div>

<!-- Modal alta/edición -->
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog">
    <form id="editForm" class="modal-content bg-dark text-white">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle"></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <input type="hidden" name="id"  id="fieldId">
        <div class="mb-3">
          <label class="form-label">Plataforma</label>
          <input type="text" name="platform" id="fieldPlatform" class="form-control bg-dark text-white" required maxlength="50">
        </div>
        <div class="mb-3">
          <label class="form-label">Asunto</label>
          <input type="text" name="subject" id="fieldSubject" class="form-control bg-dark text-white" required maxlength="255">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-primary" id="btnSave"></button>
      </div>
    </form>
  </div>
</div>

<!-- jQuery + Bootstrap bundle -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- DataTables + Bootstrap 5 (JS) -->
<script src="https://cdn.datatables.net/1.13.8/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.8/js/dataTables.bootstrap5.min.js"></script>

<script>
$(function () {

/*==== DataTable ====*/
const table = $('#subjectsTable').DataTable({
  ajax: {
    url: 'subjects_admin.php?ajax=list',
    dataSrc: 'data'
  },
  order: [[0, 'desc']],       // 👈 último registro primero
  responsive: true,
  columns: [
    { data: 'id' },
    { data: 'platform' },
    { data: 'subject_line' },
    {
      data: null,
      orderable: false,
      render: (_, __, row) => `
        <button class="btn btn-warning btn-sm me-1 btn-edit" data-id="${row.id}">
          <i class="bi bi-pencil-square"></i>
        </button>
        <button class="btn btn-danger btn-sm btn-del" data-id="${row.id}">
          <i class="bi bi-trash"></i>
        </button>`
    }
  ]
});

/*==== NUEVO ====*/
$('#btnAdd').on('click', () => {
  $('#modalTitle').text('Añadir asunto');
  $('#btnSave').text('Crear');
  $('#fieldId').val('');
  $('#editForm').data('action', 'create')[0].reset();
  bootstrap.Modal.getOrCreateInstance('#modalEdit').show();
});

/*==== EDITAR ====*/
$('#subjectsTable').on('click', '.btn-edit', function () {
  const rowData = table.row($(this).closest('tr')).data();

  $('#modalTitle').text('Editar asunto');
  $('#btnSave').text('Guardar');
  $('#fieldId').val(rowData.id);
  $('#fieldPlatform').val(rowData.platform);
  $('#fieldSubject').val(rowData.subject_line);
  $('#editForm').data('action', 'update');
  bootstrap.Modal.getOrCreateInstance('#modalEdit').show();
});

/*==== BORRAR ====*/
$('#subjectsTable').on('click', '.btn-del', function () {
  const id = $(this).data('id');
  if (!confirm('¿Eliminar este asunto?')) return;

  $.post('subjects_admin.php', {
    action: 'delete',
    id,
    csrf: '<?= $csrf ?>'
  }, res => {
    if (res.error) { showToast(res.error, 'danger'); return; }   // 👈 toast error
    showToast(res.success);                                      // 👈 toast éxito
    table.ajax.reload(null, false);
  }, 'json');
});

/*==== GUARDAR (alta / edición) ====*/
$('#editForm').on('submit', function (e) {
  e.preventDefault();
  const action = $(this).data('action');
  const formData = $(this).serialize() + '&action=' + action;

  $.post('subjects_admin.php', formData, res => {
    if (res.error) { showToast(res.error, 'danger'); return; }   // 👈 toast error
    showToast(res.success);                                      // 👈 toast éxito
    bootstrap.Modal.getInstance('#modalEdit').hide();
    table.ajax.reload(null, false);
  }, 'json');
});

/*==== helper de toast ====*/
function showToast(message, type = 'success') {
  const icon = type === 'success'
    ? '<i class="bi bi-check-circle-fill me-2"></i>'
    : '<i class="bi bi-exclamation-triangle-fill me-2"></i>';

  const toast = $(`
    <div class="toast align-items-center text-bg-${type} border-0 mb-2" role="alert">
      <div class="d-flex">
        <div class="toast-body">${icon}${message}</div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
      </div>
    </div>
  `).appendTo('#toastContainer');

  new bootstrap.Toast(toast[0], { delay: 3000 }).show();
}

});// NO BORRAR
</script>
<?php include __DIR__ . '/footer.php'; ?>
</body>
</html>
