<?php
session_start();
include '../../script/conexion.php';
require '../general/validacion.php';

date_default_timezone_set('America/Bogota');

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function nf0($value)
{
    return number_format((float)$value, 0, ',', '.');
}

function formatDateEs($date)
{
    if (!$date) return '';
    return date('d/m/Y', strtotime($date));
}

function buildQueryParams(array $params)
{
    foreach ($params as $key => $value) {
        if ($value === '' || $value === null) {
            unset($params[$key]);
        }
    }
    return http_build_query($params);
}

/*
|--------------------------------------------------------------------------
| Autofocus y preselección de referencia
|--------------------------------------------------------------------------
*/
$referenciaPreseleccion = trim($_GET['referencia_producto'] ?? '');
$autofocus_fecha = $referenciaPreseleccion === '' ? 'autofocus' : '';
$autofocus_talla = $referenciaPreseleccion !== '' ? 'autofocus' : '';

/*
|--------------------------------------------------------------------------
| Catálogo de productos
|--------------------------------------------------------------------------
*/
$productos = [];
$sqlProductos = "SELECT referencia, codigo, categoria FROM producto WHERE habilitado='Si' ORDER BY referencia ASC";
$queryProductos = $conn->query($sqlProductos);
if ($queryProductos && $queryProductos->num_rows > 0) {
    while ($row = $queryProductos->fetch_assoc()) {
        $productos[] = $row;
    }
}

/*
|--------------------------------------------------------------------------
| Filtros de lista
|--------------------------------------------------------------------------
*/
$q           = trim($_GET['q'] ?? '');
$referencia  = trim($_GET['referencia'] ?? '');
$fecha_desde = trim($_GET['fecha_desde'] ?? '');
$fecha_hasta = trim($_GET['fecha_hasta'] ?? '');

$where = [];
$where[] = "n.tipo_novedad = 'Novedad'";

if ($q !== '') {
    $qSql = $conn->real_escape_string($q);
    $where[] = "(
        n.referencia_producto LIKE '%$qSql%' OR
        n.observacion LIKE '%$qSql%' OR
        n.talla LIKE '%$qSql%' OR
        n.id LIKE '%$qSql%'
    )";
}

if ($referencia !== '') {
    $referenciaSql = $conn->real_escape_string($referencia);
    $where[] = "n.referencia_producto = '$referenciaSql'";
}

if ($fecha_desde !== '') {
    $fechaDesdeSql = $conn->real_escape_string($fecha_desde);
    $where[] = "n.fecha >= '$fechaDesdeSql'";
}

if ($fecha_hasta !== '') {
    $fechaHastaSql = $conn->real_escape_string($fecha_hasta);
    $where[] = "n.fecha <= '$fechaHastaSql'";
}

$whereSql = implode(' AND ', $where);

/*
|--------------------------------------------------------------------------
| Estadísticas
|--------------------------------------------------------------------------
*/
$stats = [
    'total_registros'   => 0,
    'total_cantidad'    => 0,
    'refs_distintas'    => 0,
    'valor_total'       => 0,
];

$sqlStats = "
    SELECT
        COUNT(*) AS total_registros,
        COALESCE(SUM(n.cantidad), 0) AS total_cantidad,
        COUNT(DISTINCT n.referencia_producto) AS refs_distintas,
        COALESCE(SUM(n.cantidad * n.precio_unidad), 0) AS valor_total
    FROM alm_novedad n
    WHERE $whereSql
";
$queryStats = $conn->query($sqlStats);
if ($queryStats && $queryStats->num_rows > 0) {
    $rowStats = $queryStats->fetch_assoc();
    $stats['total_registros'] = (int)($rowStats['total_registros'] ?? 0);
    $stats['total_cantidad']  = (float)($rowStats['total_cantidad'] ?? 0);
    $stats['refs_distintas']  = (int)($rowStats['refs_distintas'] ?? 0);
    $stats['valor_total']     = (float)($rowStats['valor_total'] ?? 0);
}

/*
|--------------------------------------------------------------------------
| Paginación
|--------------------------------------------------------------------------
*/
$porPagina = 20;
$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$totalPaginas = max(1, (int)ceil($stats['total_registros'] / $porPagina));

if ($pagina > $totalPaginas) {
    $pagina = $totalPaginas;
}

$offset = ($pagina - 1) * $porPagina;

/*
|--------------------------------------------------------------------------
| Lista
|--------------------------------------------------------------------------
*/
$novedades = [];
$sqlLista = "
    SELECT
        n.*,
        p.color
    FROM alm_novedad n
    LEFT JOIN producto p ON p.referencia = n.referencia_producto
    WHERE $whereSql
    ORDER BY n.fecha DESC, n.id DESC
    LIMIT $offset, $porPagina
";
$queryLista = $conn->query($sqlLista);
if ($queryLista && $queryLista->num_rows > 0) {
    while ($row = $queryLista->fetch_assoc()) {
        $novedades[] = $row;
    }
}

$queryBase = [
    'q'          => $q,
    'referencia' => $referencia,
    'fecha_desde'=> $fecha_desde,
    'fecha_hasta'=> $fecha_hasta,
];

$desde = $stats['total_registros'] > 0 ? ($offset + 1) : 0;
$hasta = min($offset + $porPagina, $stats['total_registros']);
?>
<!doctype html>
<html lang="es" class="light-theme">
<head>
    <?php include '../general/libreria-css.php'; ?>

    <style>
        :root {
            --page-bg: #f6f8fb;
            --card-bg: #ffffff;
            --text-main: #1f2937;
            --text-soft: #6b7280;
            --line: #e5e7eb;
            --primary: #111827;
            --primary-soft: rgba(17, 24, 39, .06);
            --success-soft: rgba(34, 197, 94, .12);
            --warning-soft: rgba(245, 158, 11, .12);
            --danger-soft: rgba(239, 68, 68, .12);
            --info-soft: rgba(59, 130, 246, .12);
            --shadow: 0 10px 30px rgba(15, 23, 42, .06);
            --radius: 18px;
        }

        body {
            background: var(--page-bg);
            color: var(--text-main);
        }

        .page-title-card,
        .form-card,
        .filter-card,
        .stats-card,
        .list-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body,
        .form-card .card-body,
        .filter-card .card-body,
        .list-card .card-body {
            padding: 1.25rem 1.35rem;
        }

        .page-title-main {
            font-size: 1.55rem;
            font-weight: 800;
            margin-bottom: .2rem;
            letter-spacing: .2px;
        }

        .page-subtitle {
            color: var(--text-soft);
            margin: 0;
            font-size: .95rem;
        }

        .page-badges {
            display: flex;
            gap: .5rem;
            flex-wrap: wrap;
            margin-top: .8rem;
        }

        .info-chip {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .45rem .75rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .82rem;
            color: var(--text-main);
            font-weight: 600;
        }

        .label-soft {
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            color: var(--text-soft);
            font-weight: 700;
            margin-bottom: .45rem;
        }

        .btn-modern {
            border-radius: 12px;
            padding: .72rem 1rem;
            font-weight: 800;
        }

        .stats-card .card-body {
            padding: 1rem 1.1rem;
        }

        .stats-icon {
            width: 44px;
            height: 44px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-soft);
            color: var(--primary);
            font-size: 1.05rem;
            margin-bottom: .85rem;
        }

        .stats-title {
            font-size: .78rem;
            color: var(--text-soft);
            text-transform: uppercase;
            letter-spacing: .08em;
            margin-bottom: .35rem;
            font-weight: 700;
        }

        .stats-value {
            font-size: 1.35rem;
            font-weight: 800;
            line-height: 1.1;
            color: var(--text-main);
        }

        .stats-note {
            font-size: .8rem;
            color: var(--text-soft);
            margin-top: .35rem;
        }

        .section-head {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }

        .section-title {
            font-size: 1rem;
            font-weight: 800;
            margin-bottom: .15rem;
        }

        .section-subtitle {
            color: var(--text-soft);
            font-size: .88rem;
            margin: 0;
        }

        .table-modern {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table-modern thead th {
            background: #f8fafc;
            color: #334155;
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            font-weight: 800;
            border-bottom: 1px solid var(--line);
            border-top: 0;
            white-space: nowrap;
            padding: .8rem .65rem;
        }

        .table-modern tbody td {
            padding: .82rem .65rem;
            vertical-align: middle;
            border-color: #eef2f7;
        }

        .table-modern tbody tr:hover {
            background: #fafcff;
        }

        .ref-main {
            font-weight: 800;
            color: #111827;
        }

        .obs-cell {
            max-width: 260px;
            white-space: normal;
            color: #475569;
        }

        .action-btn {
            width: 38px;
            height: 38px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            border: 1px solid #e5e7eb;
            background: #fff;
            transition: all .18s ease;
        }

        .action-btn:hover {
            transform: translateY(-1px);
        }

        .action-edit {
            color: #b45309;
        }

        .action-edit:hover {
            background: rgba(245, 158, 11, .10);
            border-color: rgba(245, 158, 11, .35);
            color: #b45309;
        }

        .action-delete {
            color: #b91c1c;
        }

        .action-delete:hover {
            background: rgba(239, 68, 68, .10);
            border-color: rgba(239, 68, 68, .35);
            color: #b91c1c;
        }

        .pagination .page-link {
            border-radius: 12px !important;
            margin: 0 .15rem;
            border: 1px solid #e5e7eb;
            color: #111827;
            font-weight: 700;
        }

        .pagination .page-item.active .page-link {
            background: #111827;
            border-color: #111827;
            color: #fff;
        }

        .pagination .page-item.disabled .page-link {
            color: #9ca3af;
        }

        .modal-content {
            border: 0;
            border-radius: 18px;
            overflow: hidden;
        }

        .modal-header-edit {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: #fff;
        }

        .modal-header-delete {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: #fff;
        }

        .empty-state {
            border: 1px dashed #cbd5e1;
            border-radius: 18px;
            padding: 2rem 1rem;
            text-align: center;
            background: #fff;
        }

        .empty-state i {
            font-size: 2rem;
            color: #94a3b8;
            margin-bottom: .75rem;
        }

        .empty-state h5 {
            font-weight: 800;
            margin-bottom: .35rem;
        }

        .empty-state p {
            color: var(--text-soft);
            margin-bottom: 0;
        }

        @media print {
            .d-print-none,
            .wrapper aside,
            .top-header,
            .modal,
            .pagination {
                display: none !important;
            }

            body {
                background: #fff !important;
            }

            .page-title-card,
            .form-card,
            .filter-card,
            .stats-card,
            .list-card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php echo include '../general/menu.php'; ?>

        <div class="page-content-wrapper">
            <div class="page-content">

                <nav aria-label="breadcrumb" class="mb-3 d-print-none">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item">
                            <a href="../inicio/inicio.php">
                                <ion-icon name="home-outline"></ion-icon>
                            </a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Novedades</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Novedades - Salidas</div>
                        <p class="page-subtitle">
                            Registro y control de novedades del almacén con filtros útiles y edición centralizada.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-list"></i>
                                Registros: <?= nf0($stats['total_registros']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-boxes-stacked"></i>
                                Cantidad: <?= nf0($stats['total_cantidad']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-tag"></i>
                                Referencias: <?= nf0($stats['refs_distintas']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-dollar-sign"></i>
                                Valor: $ <?= nf0($stats['valor_total']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-list"></i></div>
                                <div class="stats-title">Novedades</div>
                                <div class="stats-value"><?= nf0($stats['total_registros']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-boxes-stacked"></i></div>
                                <div class="stats-title">Cantidad</div>
                                <div class="stats-value"><?= nf0($stats['total_cantidad']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-tags"></i></div>
                                <div class="stats-title">Refs. distintas</div>
                                <div class="stats-value"><?= nf0($stats['refs_distintas']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-money-bill-wave"></i></div>
                                <div class="stats-title">Valor total</div>
                                <div class="stats-value">$ <?= nf0($stats['valor_total']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-xl-4">
                        <div class="card form-card">
                            <div class="card-body">
                                <div class="section-title">Nueva novedad</div>
                                <p class="section-subtitle">
                                    Registra una salida con referencia, talla y observación.
                                </p>

                                <form method="POST" action="script/novedad-guardar.php" class="row g-3">
                                    <input type="hidden" name="nombre_usuario" value="<?= h($rowusu['nombre']) ?>">

                                    <div class="col-md-4">
                                        <label class="label-soft">Fecha</label>
                                        <input class="form-control" type="date" required name="fecha" value="<?= date('Y-m-d') ?>" <?= $autofocus_fecha ?>>
                                    </div>

                                    <div class="col-md-8">
                                        <label class="label-soft">Referencia</label>
                                        <select class="single-select form-control" required name="referencia_producto">
                                            <option value="">Seleccione</option>
                                            <?php foreach ($productos as $item): ?>
                                                <option value="<?= h($item['referencia']) ?>" <?= $referenciaPreseleccion === $item['referencia'] ? 'selected' : '' ?>>
                                                    <?= h($item['referencia']) ?> - <?= h($item['categoria']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="label-soft">Talla</label>
                                        <select class="single-select form-control" id="talla" required name="talla" <?= $autofocus_talla ?>>
                                            <option value="">Seleccione</option>
                                            <?php for ($i = 10; $i < 49; $i++): ?>
                                                <option value="<?= $i ?>">Talla <?= $i ?></option>
                                            <?php endfor; ?>
                                        </select>
                                    </div>

                                    <div class="col-md-6">
                                        <label class="label-soft">Cantidad</label>
                                        <input class="form-control" type="number" required name="cantidad" value="0">
                                    </div>

                                    <div class="col-md-12">
                                        <label class="label-soft">Observación</label>
                                        <textarea class="form-control" required name="observacion" rows="4">No aplica</textarea>
                                    </div>

                                    <div class="col-12 text-end">
                                        <button class="btn btn-dark btn-modern" type="submit">
                                            <i class="fas fa-save me-1"></i> Guardar
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-xl-8">
                        <div class="card filter-card mb-3">
                            <div class="card-body">
                                <div class="section-title">Filtros</div>
                                <p class="section-subtitle">
                                    Busca por referencia, observación, talla o acota por fechas.
                                </p>

                                <form method="GET" action="novedad.php" class="row g-3 align-items-end">
                                    <div class="col-md-4">
                                        <label class="label-soft">Buscar</label>
                                        <input type="text" class="form-control" name="q" value="<?= h($q) ?>" placeholder="Referencia, talla, observación o id">
                                    </div>

                                    <div class="col-md-3">
                                        <label class="label-soft">Referencia</label>
                                        <select class="single-select form-control" name="referencia">
                                            <option value="">Todas</option>
                                            <?php foreach ($productos as $item): ?>
                                                <option value="<?= h($item['referencia']) ?>" <?= $referencia === $item['referencia'] ? 'selected' : '' ?>>
                                                    <?= h($item['referencia']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div class="col-md-2">
                                        <label class="label-soft">Desde</label>
                                        <input type="date" class="form-control" name="fecha_desde" value="<?= h($fecha_desde) ?>">
                                    </div>

                                    <div class="col-md-2">
                                        <label class="label-soft">Hasta</label>
                                        <input type="date" class="form-control" name="fecha_hasta" value="<?= h($fecha_hasta) ?>">
                                    </div>

                                    <div class="col-md-12">
                                        <div class="d-flex gap-2 flex-wrap">
                                            <button class="btn btn-dark btn-modern" type="submit">
                                                <i class="fas fa-search me-1"></i> Filtrar
                                            </button>
                                            <a href="novedad.php" class="btn btn-outline-secondary btn-modern">
                                                Restablecer
                                            </a>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <div class="card list-card">
                            <div class="card-body">
                                <div class="section-head">
                                    <div>
                                        <div class="section-title">Lista de novedades</div>
                                        <p class="section-subtitle">
                                            Mostrando <?= nf0($desde) ?> - <?= nf0($hasta) ?> de <?= nf0($stats['total_registros']) ?> registros.
                                        </p>
                                    </div>
                                </div>

                                <?php if (empty($novedades)): ?>
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <h5>Sin resultados</h5>
                                        <p>No se encontraron novedades con los filtros seleccionados.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-modern align-middle table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <th class="text-center">Id</th>
                                                    <th class="text-center">Fecha</th>
                                                    <th>Referencia</th>
                                                    <th>Color</th>
                                                    <th class="text-center">Talla</th>
                                                    <th class="text-center">Cant.</th>
                                                    <th class="text-end">Precio unidad</th>
                                                    <th>Observación</th>
                                                    <th class="text-center">Acciones</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($novedades as $row): ?>
                                                    <tr>
                                                        <td class="text-center"><strong><?= h($row['id']) ?></strong></td>
                                                        <td class="text-center"><?= h(formatDateEs($row['fecha'])) ?></td>
                                                        <td><span class="ref-main"><?= h($row['referencia_producto']) ?></span></td>
                                                        <td><?= h($row['color']) ?></td>
                                                        <td class="text-center"><?= h($row['talla']) ?></td>
                                                        <td class="text-center"><?= nf0($row['cantidad']) ?></td>
                                                        <td class="text-end">$ <?= nf0($row['precio_unidad']) ?></td>
                                                        <td class="obs-cell"><?= h($row['observacion']) ?></td>
                                                        <td class="text-center">
                                                            <button
                                                                type="button"
                                                                class="action-btn action-edit"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#editarModal"
                                                                data-id="<?= h($row['id']) ?>"
                                                                data-fecha="<?= h($row['fecha']) ?>"
                                                                data-referencia="<?= h($row['referencia_producto']) ?>"
                                                                data-talla="<?= h($row['talla']) ?>"
                                                                data-cantidad="<?= h($row['cantidad']) ?>"
                                                                data-observacion="<?= h($row['observacion']) ?>"
                                                                title="Editar"
                                                            >
                                                                <i class="far fa-edit"></i>
                                                            </button>

                                                            <button
                                                                type="button"
                                                                class="action-btn action-delete ms-2"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#eliminarModal"
                                                                data-id="<?= h($row['id']) ?>"
                                                                data-referencia="<?= h($row['referencia_producto']) ?>"
                                                                title="Eliminar"
                                                            >
                                                                <i class="far fa-trash-alt"></i>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if ($totalPaginas > 1): ?>
                            <div class="d-flex justify-content-end mt-3 d-print-none">
                                <nav aria-label="Paginación novedades">
                                    <ul class="pagination mb-0 flex-wrap">
                                        <li class="page-item <?= $pagina <= 1 ? 'disabled' : '' ?>">
                                            <a class="page-link" href="novedad.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => max(1, $pagina - 1)])) ?>">«</a>
                                        </li>

                                        <?php
                                        $inicio = max(1, $pagina - 2);
                                        $fin = min($totalPaginas, $pagina + 2);

                                        if ($inicio > 1) {
                                            echo '<li class="page-item"><a class="page-link" href="novedad.php?' . buildQueryParams(array_merge($queryBase, ['pagina' => 1])) . '">1</a></li>';
                                            if ($inicio > 2) {
                                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                            }
                                        }

                                        for ($i = $inicio; $i <= $fin; $i++):
                                        ?>
                                            <li class="page-item <?= $pagina == $i ? 'active' : '' ?>">
                                                <a class="page-link" href="novedad.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => $i])) ?>">
                                                    <?= $i ?>
                                                </a>
                                            </li>
                                        <?php endfor; ?>

                                        <?php
                                        if ($fin < $totalPaginas) {
                                            if ($fin < $totalPaginas - 1) {
                                                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                            }
                                            echo '<li class="page-item"><a class="page-link" href="novedad.php?' . buildQueryParams(array_merge($queryBase, ['pagina' => $totalPaginas])) . '">' . $totalPaginas . '</a></li>';
                                        }
                                        ?>

                                        <li class="page-item <?= $pagina >= $totalPaginas ? 'disabled' : '' ?>">
                                            <a class="page-link" href="novedad.php?<?= buildQueryParams(array_merge($queryBase, ['pagina' => min($totalPaginas, $pagina + 1)])) ?>">»</a>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php echo include '../general/footer.php'; ?>
            </div>
        </div>
    </div>

    <div class="modal fade" id="editarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-md modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header modal-header-edit">
                    <h5 class="modal-title mb-0">Editar novedad</h5>
                    <button type="button" class="btn-close btn-close-white shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/novedad-editar.php">
                    <input type="hidden" name="id" id="editar_id">

                    <div class="modal-body p-4">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="label-soft">Fecha</label>
                                <input class="form-control" type="date" required name="fecha" id="editar_fecha">
                            </div>

                            <div class="col-md-6">
                                <label class="label-soft">Talla</label>
                                <select class="form-control" required name="talla" id="editar_talla">
                                    <?php for ($i = 10; $i < 49; $i++): ?>
                                        <option value="<?= $i ?>"><?= $i ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>

                            <div class="col-md-12">
                                <label class="label-soft">Referencia</label>
                                <select class="single-select-modal form-control" required name="referencia_producto" id="editar_referencia">
                                    <option value="">Seleccione</option>
                                    <?php foreach ($productos as $item): ?>
                                        <option value="<?= h($item['referencia']) ?>">
                                            <?= h($item['referencia']) ?> - <?= h($item['categoria']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-12">
                                <label class="label-soft">Cantidad</label>
                                <input class="form-control" type="number" required name="cantidad" id="editar_cantidad">
                            </div>

                            <div class="col-md-12">
                                <label class="label-soft">Observación</label>
                                <textarea class="form-control" required name="observacion" id="editar_observacion" rows="4"></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer px-4 pb-4 border-0">
                        <button type="button" class="btn btn-outline-secondary btn-modern" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-dark btn-modern">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="eliminarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header modal-header-delete">
                    <h5 class="modal-title mb-0">Eliminar novedad</h5>
                    <button type="button" class="btn-close btn-close-white shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/novedad-eliminar.php">
                    <input type="hidden" name="id" id="eliminar_id">

                    <div class="modal-body p-4">
                        <p class="mb-0">
                            ¿Seguro deseas eliminar la novedad de la referencia
                            <strong id="eliminar_referencia"></strong>?
                        </p>
                    </div>

                    <div class="modal-footer px-4 pb-4 border-0">
                        <button type="button" class="btn btn-outline-secondary btn-modern" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-danger btn-modern">Eliminar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php echo include '../general/libreria-js.php'; ?>

    <script>
        $(document).ready(function () {
            $('.single-select').select2({
                theme: 'bootstrap4',
                width: '100%'
            });

            $('.single-select-modal').select2({
                dropdownParent: $('#editarModal'),
                theme: 'bootstrap4',
                width: '100%'
            });
        });

        const editarModal = document.getElementById('editarModal');
        if (editarModal) {
            editarModal.addEventListener('show.bs.modal', function (event) {
                const button = event.relatedTarget;

                document.getElementById('editar_id').value = button.getAttribute('data-id') || '';
                document.getElementById('editar_fecha').value = button.getAttribute('data-fecha') || '';
                document.getElementById('editar_talla').value = button.getAttribute('data-talla') || '';
                document.getElementById('editar_cantidad').value = button.getAttribute('data-cantidad') || '';
                document.getElementById('editar_observacion').value = button.getAttribute('data-observacion') || '';

                const referencia = button.getAttribute('data-referencia') || '';
                $('#editar_referencia').val(referencia).trigger('change');
            });
        }

        const eliminarModal = document.getElementById('eliminarModal');
        if (eliminarModal) {
            eliminarModal.addEventListener('show.bs.modal', function (event) {
                const button = event.relatedTarget;

                document.getElementById('eliminar_id').value = button.getAttribute('data-id') || '';
                document.getElementById('eliminar_referencia').textContent = button.getAttribute('data-referencia') || '';
            });
        }
    </script>
</body>
</html>