<?php
// gestionar_plataformas.php
// Módulo unificado visualmente con la referencia de Admin > Buzones.

require_once __DIR__ . '/init.php';

if (isset($_GET['fetch_data']) || $_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['delete'])) {
    if (!tiene_permiso('gestionar_plataformas')) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'message' => 'Acceso denegado.']);
        exit;
    }

    if (isset($_GET['fetch_data'])) {
        header('Content-Type: application/json; charset=utf-8');
        $id = filter_input(INPUT_GET, 'fetch_data', FILTER_VALIDATE_INT);
        $response = ['success' => false, 'message' => 'Plataforma no encontrada.'];
        if ($id) {
            $stmt = $pdo->prepare("SELECT id, nombre, concepto, orden, imagen_url FROM plataformas WHERE id = ?");
            $stmt->execute([$id]);
            if ($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $response = ['success' => true, 'data' => $data];
            }
        }
        echo json_encode($response);
        exit;
    }

    if (isset($_POST['guardar_plataforma'])) {
        header('Content-Type: application/json; charset=utf-8');
        $response = ['success' => false, 'message' => 'Error desconocido.'];

        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        $nombre = trim($_POST['nombre'] ?? '');

        if ($nombre === '') {
            $response['message'] = 'El nombre es obligatorio.';
        } else {
            try {
                $concepto = trim($_POST['concepto'] ?? '');
                $orden = filter_input(INPUT_POST, 'orden', FILTER_VALIDATE_INT);
                $orden = $orden === false || $orden === null ? 99 : (int)$orden;
                $imagen_actual_url = trim($_POST['imagen_actual_url_db'] ?? '');
                $imagen_url_to_save = $imagen_actual_url;

                if (isset($_FILES['imagen_plataforma']) && ($_FILES['imagen_plataforma']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {
                    $upload_dir = __DIR__ . '/../assets/img/plataformas/';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0775, true);
                    }

                    $file_extension = strtolower(pathinfo($_FILES['imagen_plataforma']['name'], PATHINFO_EXTENSION));
                    $file_name_unique = 'plat_' . uniqid('', true) . '.' . $file_extension;
                    $target_file = $upload_dir . $file_name_unique;

                    if (move_uploaded_file($_FILES['imagen_plataforma']['tmp_name'], $target_file)) {
                        if ($imagen_actual_url !== '' && file_exists(__DIR__ . '/../' . $imagen_actual_url)) {
                            @unlink(__DIR__ . '/../' . $imagen_actual_url);
                        }
                        $imagen_url_to_save = 'assets/img/plataformas/' . $file_name_unique;
                    }
                }

                if ($id) {
                    $pdo->prepare("UPDATE plataformas SET nombre = ?, concepto = ?, orden = ?, imagen_url = ? WHERE id = ?")
                        ->execute([$nombre, $concepto, $orden, $imagen_url_to_save, $id]);
                    $response = ['success' => true, 'message' => 'Plataforma actualizada correctamente.'];
                } else {
                    $pdo->prepare("INSERT INTO plataformas (nombre, concepto, orden, imagen_url) VALUES (?, ?, ?, ?)")
                        ->execute([$nombre, $concepto, $orden, $imagen_url_to_save]);
                    $response = ['success' => true, 'message' => 'Plataforma creada correctamente.'];
                }
            } catch (Exception $e) {
                $response['message'] = 'Error al guardar: ' . $e->getMessage();
            }
        }

        echo json_encode($response);
        exit;
    }

    if (isset($_GET['delete'])) {
        $id_a_borrar = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT);
        if ($id_a_borrar) {
            try {
                $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM asuntos WHERE id_plataforma = ?");
                $stmt_check->execute([$id_a_borrar]);
                if ((int)$stmt_check->fetchColumn() > 0) {
                    throw new Exception('No se puede eliminar. La plataforma está en uso por uno o más asuntos.');
                }

                $stmt_img = $pdo->prepare("SELECT imagen_url FROM plataformas WHERE id = ?");
                $stmt_img->execute([$id_a_borrar]);
                if ($img = $stmt_img->fetchColumn()) {
                    $full = __DIR__ . '/../' . ltrim($img, '/');
                    if (file_exists($full)) {
                        @unlink($full);
                    }
                }

                $pdo->prepare("DELETE FROM plataformas WHERE id = ?")->execute([$id_a_borrar]);
                $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Plataforma eliminada con éxito.'];
            } catch (Exception $e) {
                $_SESSION['flash_message'] = ['type' => 'error', 'text' => $e->getMessage()];
            }
        }
        header('Location: gestionar_plataformas.php');
        exit;
    }
}

$titulo_pagina = 'Gestionar Plataformas';
require_once 'admin_header.php';

$rol_actual = $_SESSION['admin']['rol'] ?? 'guest';
$plataformas = $pdo->query("SELECT * FROM plataformas ORDER BY orden, nombre ASC")->fetchAll(PDO::FETCH_ASSOC);
$total_plataformas = count($plataformas);
$total_con_imagen = 0;
$total_ordenadas = 0;
$total_sin_logo = 0;

foreach ($plataformas as $plat) {
    if (!empty($plat['imagen_url'])) {
        $total_con_imagen++;
    } else {
        $total_sin_logo++;
    }
    if (isset($plat['orden']) && $plat['orden'] !== null && $plat['orden'] !== '') {
        $total_ordenadas++;
    }
}
?>


<style>
.super-platform-ui{--brand:#ef3b43;--brand-dark:#d9252e;--ink:#0f172a;--muted:#64748b;--line:#dbe4ef;--surface:#fff;--soft:#f7f9fc;}
.super-platform-ui *{box-sizing:border-box;}
.module-context-strip{display:none!important;}
body.af-catalog-modal-open table.fixedHeader-floating,
body.af-catalog-modal-open table.fixedHeader-locked,
body.af-catalog-modal-open .fixedHeader-floating,
body.af-catalog-modal-open .fixedHeader-locked,
body.af-catalog-modal-open .dtfh-floatingparent{display:none!important;visibility:hidden!important;}
body.af-catalog-modal-open .admin-main table thead,
body.af-catalog-modal-open .admin-main table thead th{position:static!important;z-index:auto!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;}
body.af-catalog-modal-open .dataTables_scrollHead{visibility:hidden!important;opacity:0!important;}
.super-platform-ui{padding-left:0!important;padding-right:0!important;}
.super-platform-ui .module-shell{width:100%;max-width:1480px;margin:0 auto;}
.super-platform-ui .module-card{background:#fff;border:1px solid #dfe6ef;border-radius:20px;box-shadow:0 12px 30px rgba(15,23,42,.055);}
.super-platform-ui .module-hero{margin-top:18px;padding:18px 20px;display:flex;align-items:center;justify-content:space-between;gap:18px;}
.super-platform-ui .hero-main{display:flex;align-items:flex-start;gap:14px;min-width:0;}
.super-platform-ui .hero-icon{width:42px;height:42px;border-radius:13px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;font-size:17px;}
.super-platform-ui .eyebrow{font-size:11px;line-height:1.2;text-transform:uppercase;letter-spacing:.08em;font-weight:900;color:#50698a;margin-bottom:4px;}
.super-platform-ui .module-title{font-size:28px;line-height:1.05;font-weight:900;color:var(--ink);letter-spacing:-.035em;margin:0;}
.super-platform-ui .module-copy{font-size:13px;line-height:1.5;color:var(--muted);margin:6px 0 0;max-width:760px;}
.super-platform-ui .btn-primary,.super-platform-ui .btn-secondary{height:42px;border-radius:12px;padding:0 16px;display:inline-flex;align-items:center;justify-content:center;gap:8px;font-size:13px;font-weight:900;white-space:nowrap;transition:.16s;border:1px solid transparent;}
.super-platform-ui .btn-primary{background:linear-gradient(180deg,#fb444c 0%,#ee333c 100%);color:#fff;box-shadow:0 8px 18px rgba(239,59,67,.22);}
.super-platform-ui .btn-primary:hover{background:linear-gradient(180deg,#ef3942 0%,#d9252e 100%);transform:translateY(-1px);}
.super-platform-ui .btn-secondary{background:#fff;border-color:#d8e1ec;color:#0f172a;}
.super-platform-ui .btn-secondary:hover{background:#f8fafc;}
.super-platform-ui .stats-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-top:14px;}
.super-platform-ui .stat-card{background:#fff;border:1px solid #dfe6ef;border-radius:16px;padding:13px 15px;display:flex;align-items:center;gap:12px;min-height:78px;box-shadow:0 7px 18px rgba(15,23,42,.035);}
.super-platform-ui .stat-icon{width:38px;height:38px;border-radius:12px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-platform-ui .stat-label{font-size:10px;letter-spacing:.07em;text-transform:uppercase;font-weight:900;color:#5d728f;}
.super-platform-ui .stat-value{font-size:22px;line-height:1;font-weight:900;color:var(--ink);margin-top:4px;}
.super-platform-ui .stat-note{font-size:11px;color:#708199;margin-top:4px;line-height:1.25;}
.super-platform-ui .records-card{margin-top:14px;overflow:hidden;}
.super-platform-ui .records-head{padding:14px 16px;border-bottom:1px solid #e6edf5;display:flex;align-items:center;gap:11px;}
.super-platform-ui .section-icon{width:36px;height:36px;border-radius:11px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-platform-ui .records-title{font-size:18px;font-weight:900;color:var(--ink);margin:0;}
.super-platform-ui .records-copy{font-size:12px;color:var(--muted);margin:2px 0 0;}
.super-platform-ui .toolbar{padding:12px 16px;border-bottom:1px solid #e6edf5;background:#f8fafc;display:grid;grid-template-columns:minmax(0,1fr) 205px auto;gap:10px;align-items:end;}
.super-platform-ui .field-label{display:block;font-size:10px;font-weight:900;letter-spacing:.05em;text-transform:uppercase;color:#334155;margin:0 0 5px;}
.super-platform-ui .field-label i{color:var(--brand);margin-right:4px;}
.super-platform-ui .field,.super-platform-ui .textarea{width:100%;border:1px solid #cfd9e6;border-radius:10px;background:#fff;color:#0f172a;font-size:13px;outline:none;transition:.15s;}
.super-platform-ui .field{height:40px;padding:0 12px;}
.super-platform-ui .textarea{min-height:92px;padding:10px 12px;resize:vertical;line-height:1.45;}
.super-platform-ui .field:focus,.super-platform-ui .textarea:focus{border-color:#fb7185;box-shadow:0 0 0 3px rgba(239,68,68,.10);}
.super-platform-ui .search-wrap{position:relative;}
.super-platform-ui .search-wrap .field{padding-left:36px;}
.super-platform-ui .search-icon{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#94a3b8;pointer-events:none;}
.super-platform-ui .records-summary{padding:9px 16px;border-bottom:1px solid #e6edf5;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;background:#fff;font-size:12px;color:#64748b;}
.super-platform-ui .table-wrap{overflow-x:auto;}
.super-platform-ui table{width:100%;border-collapse:separate;border-spacing:0;min-width:820px;}
.super-platform-ui thead th{padding:10px 12px;background:#eaf1f8;border-bottom:1px solid #d5e0eb;font-size:10px;text-transform:uppercase;letter-spacing:.055em;font-weight:900;color:#30425b;text-align:left;}
.super-platform-ui tbody td{padding:10px 12px;border-bottom:1px solid #e7edf4;background:#fff;color:#172033;font-size:12px;vertical-align:middle;}
.super-platform-ui tbody tr:nth-child(even) td{background:#fbfcfe;}
.super-platform-ui tbody tr:hover td{background:#fff8f8;}
.super-platform-ui .logo-box{width:34px;height:34px;border-radius:10px;border:1px solid #dce4ed;background:#fff;display:flex;align-items:center;justify-content:center;overflow:hidden;}
.super-platform-ui .logo-box img{max-width:27px;max-height:27px;object-fit:contain;}
.super-platform-ui .concept-cell{max-width:520px;}
.super-platform-ui .concept-text{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#475569;}
.super-platform-ui .action-btn{width:34px;height:34px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;border:1px solid;margin-left:5px;transition:.15s;}
.super-platform-ui .action-edit{color:#1467df;background:#eff6ff;border-color:#bfd8ff;}
.super-platform-ui .action-edit:hover{background:#1467df;color:#fff;}
.super-platform-ui .action-delete{color:#d8242f;background:#fff1f2;border-color:#fecdd3;}
.super-platform-ui .action-delete:hover{background:#d8242f;color:#fff;}
.super-platform-ui .table-foot{padding:10px 16px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;background:#fff;color:#64748b;font-size:11px;}
.super-platform-ui .pagination-wrap{display:flex;align-items:center;gap:5px;}
.super-platform-ui .page-btn{min-width:32px;height:32px;padding:0 9px;border-radius:9px;border:1px solid #d9e2ec;background:#fff;color:#64748b;font-size:12px;font-weight:800;}
.super-platform-ui .page-btn.active{background:var(--brand);border-color:var(--brand);color:#fff;}
.super-platform-ui .page-btn:disabled{opacity:.45;cursor:not-allowed;}
.super-platform-ui .page-btn:not(:disabled):hover{background:#f8fafc;}
.super-platform-ui .modal-backdrop{position:fixed;inset:0;z-index:2147483646!important;background:rgba(15,23,42,.62);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);isolation:isolate;}
.super-platform-ui .modal-shell{width:min(94vw,900px);max-height:91vh;border-radius:18px;overflow:hidden;background:#fff;border:1px solid #dfe6ef;box-shadow:0 25px 65px rgba(15,23,42,.30);display:flex;flex-direction:column;}
.super-platform-ui .modal-head{padding:14px 16px;border-bottom:1px solid #e4eaf2;display:flex;align-items:flex-start;justify-content:space-between;gap:14px;background:#fff;}
.super-platform-ui .modal-head-main{display:flex;align-items:flex-start;gap:11px;min-width:0;}
.super-platform-ui .modal-head-icon{width:34px;height:34px;border-radius:10px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-platform-ui .modal-kicker{font-size:9px;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--brand);margin-bottom:3px;}
.super-platform-ui .modal-title{font-size:20px;line-height:1.1;font-weight:900;color:#0f172a;}
.super-platform-ui .modal-copy{font-size:11px;color:#64748b;line-height:1.4;margin-top:4px;}
.super-platform-ui .modal-close{width:34px;height:34px;border-radius:10px;border:1px solid #dce4ed;background:#fff;color:#64748b;display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-platform-ui .modal-close:hover{background:#f8fafc;color:#111827;}
.super-platform-ui .modal-body{padding:14px 16px;overflow-y:auto;display:flex;flex-direction:column;gap:12px;}
.super-platform-ui .modal-note{padding:10px 12px;border:1px solid #fecaca;background:#fff6f6;border-radius:10px;color:#8f2d34;font-size:11px;line-height:1.45;display:flex;gap:8px;align-items:flex-start;}
.super-platform-ui .modal-grid{display:grid;grid-template-columns:1fr 170px;gap:10px;}
.super-platform-ui .form-group{min-width:0;}
.super-platform-ui .form-help{font-size:10px;color:#7b8ba2;margin-top:5px;line-height:1.35;}
.super-platform-ui .file-field{height:auto;padding:8px 10px;}
.super-platform-ui .image-preview{margin-top:8px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
.super-platform-ui .image-preview img{height:48px;max-width:110px;object-fit:contain;border:1px solid #dfe6ef;border-radius:10px;background:#fff;padding:4px;}
.super-platform-ui .modal-foot{padding:11px 16px;border-top:1px solid #e5ebf2;background:#fff;display:flex;justify-content:flex-end;gap:8px;}
@media(max-width:900px){
  .super-platform-ui .stats-grid{grid-template-columns:repeat(2,minmax(0,1fr));}
  .super-platform-ui .toolbar{grid-template-columns:1fr 180px;}
  .super-platform-ui .toolbar .toolbar-action{grid-column:1/-1;}
}
@media(max-width:640px){
  .super-platform-ui{padding-left:10px!important;padding-right:10px!important;}
  .super-platform-ui .module-hero{align-items:flex-start;flex-direction:column;}
  .super-platform-ui .module-hero .btn-primary{width:100%;}
  .super-platform-ui .stats-grid{grid-template-columns:1fr;}
  .super-platform-ui .toolbar{grid-template-columns:1fr;}
  .super-platform-ui .toolbar .toolbar-action{grid-column:auto;}
  .super-platform-ui .modal-grid{grid-template-columns:1fr;}
  .super-platform-ui .module-title{font-size:24px;}
}
</style>

<div class="super-platform-ui pb-8">
    <div class="module-shell">
        <section class="module-card module-hero">
            <div class="hero-main">
                <span class="hero-icon"><i class="fas fa-desktop"></i></span>
                <div>
                    <div class="eyebrow">Catálogo global</div>
                    <h1 class="module-title">Plataformas</h1>
                    <p class="module-copy">Organiza los servicios que estarán disponibles en asuntos, cuentas y consultas del sistema.</p>
                </div>
            </div>
            <button type="button" id="openModalBtn" class="btn-primary"><i class="fas fa-plus-circle"></i> Nueva plataforma</button>
        </section>

        <section class="stats-grid" aria-label="Resumen de plataformas">
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-layer-group"></i></span>
                <div>
                    <div class="stat-label">Plataformas</div>
                    <div class="stat-value"><?= (int)$total_plataformas ?></div>
                    <div class="stat-note">Servicios registrados</div>
                </div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-image"></i></span>
                <div>
                    <div class="stat-label">Con imagen</div>
                    <div class="stat-value"><?= (int)$total_con_imagen ?></div>
                    <div class="stat-note">Logo disponible</div>
                </div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-sort-amount-down"></i></span>
                <div>
                    <div class="stat-label">Ordenadas</div>
                    <div class="stat-value"><?= (int)$total_ordenadas ?></div>
                    <div class="stat-note">Con prioridad definida</div>
                </div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-exclamation-triangle"></i></span>
                <div>
                    <div class="stat-label">Sin logo</div>
                    <div class="stat-value"><?= (int)$total_sin_logo ?></div>
                    <div class="stat-note">Pendientes de imagen</div>
                </div>
            </article>
        </section>

        <section class="module-card records-card">
            <div class="records-head">
                <span class="section-icon"><i class="fas fa-list"></i></span>
                <div>
                    <h2 class="records-title">Registros de plataformas</h2>
                    <p class="records-copy">Busca por nombre o concepto y administra el catálogo global.</p>
                </div>
            </div>

            <div class="toolbar">
                <div>
                    <label class="field-label" for="search-input"><i class="fas fa-search"></i>Buscar</label>
                    <div class="search-wrap">
                        <i class="fas fa-search search-icon"></i>
                        <input type="search" id="search-input" class="field" placeholder="Nombre o concepto">
                    </div>
                </div>
                <div>
                    <label class="field-label" for="platformPageLength"><i class="fas fa-list-ol"></i>Mostrar</label>
                    <select id="platformPageLength" class="field">
                        <option value="100" selected>100 registros</option>
                        <option value="200">200 registros</option>
                        <option value="400">400 registros</option>
                        <option value="-1">Todos</option>
                    </select>
                </div>
                <div class="toolbar-action">
                    <label class="field-label">&nbsp;</label>
                    <button type="button" id="clearSearchBtn" class="btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button>
                </div>
            </div>

            <div class="records-summary">
                <span id="platformRegistered"><?= (int)$total_plataformas ?> plataformas registradas</span>
                <span id="platformInfo">Mostrando 0–0 de 0 registros</span>
            </div>

            <div class="table-wrap">
                <table id="tablaPlataformas">
                    <thead>
                        <tr>
                            <th class="text-center">Logo</th>
                            <th>Nombre</th>
                            <th>Concepto</th>
                            <th class="text-center">Orden</th>
                            <th class="text-right">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($plataformas as $p): ?>
                            <tr>
                                <td class="text-center">
                                    <div class="inline-flex items-center justify-center">
                                        <div class="logo-box">
                                            <img src="../<?= htmlspecialchars($p['imagen_url'] ?: 'assets/img/placeholder.png') ?>" alt="<?= htmlspecialchars($p['nombre']) ?>">
                                        </div>
                                    </div>
                                </td>
                                <td><strong><?= htmlspecialchars($p['nombre']) ?></strong></td>
                                <td class="concept-cell" title="<?= htmlspecialchars(strip_tags($p['concepto'] ?? '')) ?>">
                                    <span class="concept-text"><?= htmlspecialchars(strip_tags($p['concepto'] ?? 'Sin descripción registrada.')) ?></span>
                                </td>
                                <td class="text-center font-bold"><?= htmlspecialchars((string)($p['orden'] ?? '99')) ?></td>
                                <td class="text-right whitespace-nowrap">
                                    <button type="button" class="action-btn action-edit edit-btn" title="Editar" data-id="<?= (int)$p['id'] ?>"><i class="fas fa-pen"></i></button>
                                    <a href="gestionar_plataformas.php?delete=<?= (int)$p['id'] ?>" class="action-btn action-delete delete-link" title="Eliminar"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="table-foot">
                <span>Las plataformas organizan los servicios utilizados por asuntos, cuentas y consultas.</span>
                <div id="platformPagination" class="pagination-wrap"></div>
            </div>
        </section>
    </div>
</div>

<div id="plataformaModal" class="super-platform-ui modal-backdrop fixed inset-0 hidden items-center justify-center z-[2147483000] px-3 py-4">
    <div class="modal-shell">
        <div class="modal-head">
            <div class="modal-head-main">
                <span class="modal-head-icon"><i class="fas fa-desktop"></i></span>
                <div>
                    <div class="modal-kicker">Gestionar plataformas · formulario</div>
                    <div class="modal-title" id="modalTitle">Nueva plataforma</div>
                    <p class="modal-copy">Registra el servicio, su descripción, el orden de visualización y su logo.</p>
                </div>
            </div>
            <button type="button" id="closeModalBtn" class="modal-close" aria-label="Cerrar"><i class="fas fa-times"></i></button>
        </div>

        <form id="plataformaForm" class="contents">
            <input type="hidden" name="id" id="plataformaId">
            <input type="hidden" name="imagen_actual_url_db" id="imagen_actual_url_db">
            <input type="hidden" name="guardar_plataforma" value="1">

            <div class="modal-body">
                <div class="modal-note">
                    <i class="fas fa-circle-info"></i>
                    <span>Usa el nombre con el que reconoces el servicio. Los números menores aparecen primero en los listados.</span>
                </div>

                <div class="modal-grid">
                    <div class="form-group">
                        <label for="nombre" class="field-label"><i class="fas fa-tag"></i>Nombre de la plataforma *</label>
                        <input type="text" name="nombre" id="nombre" required class="field" placeholder="Ejemplo: Netflix">
                        <div class="form-help">Se mostrará en asuntos, cuentas y consultas.</div>
                    </div>
                    <div class="form-group">
                        <label for="orden" class="field-label"><i class="fas fa-sort-numeric-down"></i>Orden *</label>
                        <input type="number" name="orden" id="orden" class="field" value="99" min="0" placeholder="99">
                        <div class="form-help">Usa 1, 2, 3… para priorizar.</div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="concepto" class="field-label"><i class="fas fa-align-left"></i>Descripción o concepto</label>
                    <textarea name="concepto" id="concepto" rows="4" class="textarea" placeholder="Describe brevemente para qué se utiliza esta plataforma."></textarea>
                    <div class="form-help">Texto breve para reconocer la función del servicio.</div>
                </div>

                <div class="form-group">
                    <label for="imagen_plataforma" class="field-label"><i class="fas fa-image"></i>Logo o imagen <span class="text-slate-400">· opcional</span></label>
                    <input type="file" name="imagen_plataforma" id="imagen_plataforma" class="field file-field" accept=".png,.jpg,.jpeg,.webp,.svg">
                    <div class="form-help">Se recomienda PNG, JPG, WebP o SVG. Al editar, déjalo vacío para conservar el logo actual.</div>
                    <div id="imagePreview" class="image-preview"></div>
                </div>
            </div>

            <div class="modal-foot">
                <button type="button" id="cancelModalBtn" class="btn-secondary"><i class="fas fa-times"></i> Cancelar</button>
                <button type="submit" id="savePlatformBtn" class="btn-primary"><i class="fas fa-save"></i> Guardar plataforma</button>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(function() {
    <?php if (isset($_SESSION['flash_message'])): ?>
    Swal.fire({
        icon: <?= json_encode($_SESSION['flash_message']['type']); ?>,
        title: <?= json_encode($_SESSION['flash_message']['type'] === 'success' ? 'Operación completada' : 'No se pudo completar'); ?>,
        text: <?= json_encode($_SESSION['flash_message']['text']); ?>,
        confirmButtonColor: '#dc2626'
    });
    <?php unset($_SESSION['flash_message']); endif; ?>

    const modal = $('#plataformaModal');
    const form = $('#plataformaForm');
    let table = $('#tablaPlataformas').DataTable({
        dom: 't',
        language: { url: '//cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json' },
        pageLength: 100,
        lengthMenu: [[100, 200, 400, -1], [100, 200, 400, 'Todos']],
        autoWidth: false,
        deferRender: true,
        order: [],
        columnDefs: [{ orderable: false, targets: [0, 4] }, { className: 'text-center', targets: [0,3] }, { className: 'text-right', targets: [4] }]
    });

    function renderFooter() {
        const info = table.page.info();
        const total = info.recordsDisplay || 0;
        const start = total === 0 ? 0 : info.start + 1;
        const end = total === 0 ? 0 : info.end;
        const totalPages = info.pages || 0;
        const currentPage = info.page || 0;

        $('#platformInfo').text(`Mostrando ${start}–${end} de ${total} registros`);

        let html = `<button type="button" class="page-btn" aria-label="Página anterior" ${(currentPage === 0 || totalPages === 0) ? 'disabled' : ''} data-page="prev"><i class="fas fa-chevron-left"></i></button>`;
        if (totalPages === 0) {
            html += `<button type="button" class="page-btn active" disabled>1</button>`;
        } else {
            for (let i = 0; i < totalPages; i++) {
                if (totalPages <= 5 || i === 0 || i === totalPages - 1 || Math.abs(i - currentPage) <= 1) {
                    html += `<button type="button" class="page-btn ${i === currentPage ? 'active' : ''}" data-page="${i}">${i + 1}</button>`;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    html += `<span class="px-1 text-slate-400">…</span>`;
                }
            }
        }
        html += `<button type="button" class="page-btn" aria-label="Página siguiente" ${(currentPage >= totalPages - 1 || totalPages === 0) ? 'disabled' : ''} data-page="next"><i class="fas fa-chevron-right"></i></button>`;
        $('#platformPagination').html(html);
    }

    function closeModal() {
        $('body').removeClass('overflow-hidden af-catalog-modal-open');
        modal.addClass('hidden').removeClass('flex');
    }

    function openModal(isEdit = false, data = {}) {
        form[0].reset();
        $('#plataformaId, #imagen_actual_url_db').val('');
        $('#imagePreview').empty();
        $('#modalTitle').text(isEdit ? 'Editar plataforma' : 'Nueva plataforma');
        $('#savePlatformBtn').html(`<i class="fas fa-save"></i> ${isEdit ? 'Guardar cambios' : 'Guardar plataforma'}`);
        $('#orden').val('99');

        if (isEdit) {
            $('#plataformaId').val(data.id || '');
            $('#nombre').val(data.nombre || '');
            $('#concepto').val(data.concepto || '');
            $('#orden').val(data.orden || '99');
            $('#imagen_actual_url_db').val(data.imagen_url || '');

            if (data.imagen_url) {
                $('#imagePreview').html(`<div class="text-xs font-semibold text-slate-500 w-full">Imagen actual</div><img src="../${data.imagen_url}" alt="Imagen actual">`);
            }
        }

        $('body').addClass('overflow-hidden af-catalog-modal-open');
        modal.removeClass('hidden').addClass('flex');
        setTimeout(() => $('#nombre').trigger('focus'), 80);
    }

    $('#search-input').on('input', function() {
        table.search(this.value).draw();
    });

    $('#platformPageLength').on('change', function() {
        table.page.len(parseInt($(this).val(), 10)).draw();
    }).val('100');

    $('#clearSearchBtn').on('click', function() {
        $('#search-input').val('');
        table.search('').draw();
    });

    table.on('draw length.dt page.dt search.dt order.dt', renderFooter);
    renderFooter();

    $('#openModalBtn').on('click', () => openModal(false));
    $('#closeModalBtn, #cancelModalBtn').on('click', closeModal);
    modal.on('click', function(e) { if (e.target === this) closeModal(); });
    $(document).on('keydown.platformModal', function(e) { if (e.key === 'Escape') closeModal(); });

    $('#tablaPlataformas').on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        Swal.fire({ title: 'Cargando...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        $.ajax({
            url: `gestionar_plataformas.php?fetch_data=${id}`,
            method: 'GET',
            dataType: 'json'
        }).done(function(response) {
            Swal.close();
            if (response.success) openModal(true, response.data || {});
            else Swal.fire({ icon: 'error', title: 'Error', text: response.message || 'No se pudo cargar la plataforma.', confirmButtonColor: '#dc2626' });
        }).fail(function() {
            Swal.close();
            Swal.fire({ icon: 'error', title: 'Error de comunicación', text: 'No se pudo conectar con el servidor.', confirmButtonColor: '#dc2626' });
        });
    });

    $('#tablaPlataformas').on('click', '.delete-link', function(e) {
        e.preventDefault();
        const deleteUrl = $(this).attr('href');
        Swal.fire({
            title: '¿Eliminar plataforma?',
            html: 'Se eliminará el registro y su imagen asociada.<br><strong>Si está siendo usada por asuntos, el sistema bloqueará la eliminación.</strong>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc2626',
            cancelButtonColor: '#64748b',
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        }).then((result) => { if (result.isConfirmed) window.location.href = deleteUrl; });
    });

    $('#platformPagination').on('click', '.page-btn', function() {
        if ($(this).is(':disabled')) return;
        const page = $(this).data('page');
        if (page === 'prev') table.page('previous').draw('page');
        else if (page === 'next') table.page('next').draw('page');
        else table.page(parseInt(page, 10)).draw('page');
    });

    $('#imagen_plataforma').on('change', function() {
        const file = this.files && this.files[0] ? this.files[0] : null;
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(e) {
            $('#imagePreview').html(`<div class="text-xs font-semibold text-slate-500 w-full">Vista previa</div><img src="${e.target.result}" alt="Vista previa">`);
        };
        reader.readAsDataURL(file);
    });

    form.on('submit', function(e) {
        e.preventDefault();
        const btn = $('#savePlatformBtn');
        const original = btn.html();
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Guardando...');

        $.ajax({
            url: 'gestionar_plataformas.php',
            method: 'POST',
            data: new FormData(this),
            processData: false,
            contentType: false,
            dataType: 'json'
        }).done(function(response) {
            if (response.success) {
                closeModal();
                Swal.fire({ icon: 'success', title: 'Listo', text: response.message, confirmButtonColor: '#dc2626' }).then(() => location.reload());
            } else {
                Swal.fire({ icon: 'error', title: 'No se pudo guardar', text: response.message || 'Revisa los datos e inténtalo nuevamente.', confirmButtonColor: '#dc2626' });
                btn.prop('disabled', false).html(original);
            }
        }).fail(function() {
            Swal.fire({ icon: 'error', title: 'Error de conexión', text: 'No se pudo conectar con el servidor.', confirmButtonColor: '#dc2626' });
            btn.prop('disabled', false).html(original);
        });
    });
});
</script>

<?php require_once 'admin_footer.php'; ?>
