#!/usr/bin/env bash
set -e
cd /home/iotcuboc/pyme || exit 1

echo "=============================================="
echo " ElaboraPro Corregir Compra V4.12.1"
echo "=============================================="

F="public/compra_corregir_v3.php"
[ -f "$F" ] || { echo "ERROR: no existe $F"; exit 1; }

TS=$(date +%Y%m%d_%H%M%S)
B="backups/elaborapro_corregir_compra_v4_12_1_$TS"
mkdir -p "$B"
cp -p "$F" "$B/"
echo "Backup: /home/iotcuboc/pyme/$B"

TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT
cp -p "$F" "$TMP"

TMP="$TMP" php <<'PHP'
<?php
$f=getenv('TMP');
$s=file_get_contents($f);
if($s===false){fwrite(STDERR,"ERROR leyendo temporal.\n");exit(1);}
if(strpos($s,'ELABORAPRO_CORREGIR_V4_12_1')!==false){
    fwrite(STDERR,"ERROR: V4.12.1 ya aplicado.\n"); exit(1);
}
if(strpos($s,'ELABORAPRO_CORREGIR_V4_12')===false){
    fwrite(STDERR,"ERROR: no se detecta V4.12 como base.\n"); exit(1);
}

/*
 * Ajuste final de layout:
 * - Nuevo costo, Motivo y Corregir quedan en una sola línea.
 * - Corrige encabezados generados por V4.12.
 * - Motivo queda sobre su input.
 * - Acciones queda sobre el botón.
 * - Conserva azul pastel del botón.
 *
 * No cambia POST, cálculos, stock ni lógica de corrección.
 */
$block=<<<'HTML'

<style>
/* ELABORAPRO_CORREGIR_V4_12_1 */
.op3-main table.ep-correct-table{
    width:100% !important;
    table-layout:auto !important;
}
.op3-main table.ep-correct-table thead th{
    vertical-align:middle !important;
    white-space:nowrap !important;
}
.op3-main table.ep-correct-table tbody tr{
    height:auto !important;
}
.op3-main table.ep-correct-table tbody td{
    vertical-align:middle !important;
    padding-top:12px !important;
    padding-bottom:12px !important;
}
.op3-main table.ep-correct-table .ep-correct-inline{
    display:grid !important;
    grid-template-columns:minmax(150px,1fr) minmax(190px,1fr) auto !important;
    align-items:center !important;
    gap:10px !important;
    width:100% !important;
}
.op3-main table.ep-correct-table .ep-correct-inline input{
    width:100% !important;
    min-width:0 !important;
    margin:0 !important;
}
.op3-main table.ep-correct-table .ep-correct-inline .ep-correct-action{
    margin:0 !important;
    align-self:center !important;
}
.op3-main table.ep-correct-table .ep-correct-field-label{
    display:none !important;
}
@media (max-width:900px){
    .op3-main table.ep-correct-table .ep-correct-inline{
        grid-template-columns:minmax(130px,1fr) minmax(170px,1fr) auto !important;
        gap:8px !important;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const table = document.querySelector('.op3-main table.ep-correct-table');
    if (!table) return;

    const headRow = table.querySelector('thead tr');
    if (headRow) {
        const ths = Array.from(headRow.querySelectorAll('th'));

        /*
         * V4.12 creó Nuevo costo / Motivo / Acciones,
         * pero el contenido real continúa dentro de la última celda original.
         * Dejamos una sola cabecera visual que ocupa las 3 columnas internas.
         */
        const nuevoIdx = ths.findIndex(th => th.textContent.trim() === 'Nuevo costo');
        if (nuevoIdx >= 0) {
            const nuevo = ths[nuevoIdx];
            const motivo = ths.find(th => th.textContent.trim() === 'Motivo');
            const acciones = ths.find(th => th.textContent.trim() === 'Acciones');

            nuevo.innerHTML =
                '<div class="ep-correct-head-grid">' +
                    '<span>Nuevo costo</span>' +
                    '<span>Motivo</span>' +
                    '<span>Acciones</span>' +
                '</div>';

            if (motivo) motivo.remove();
            if (acciones) acciones.remove();
        }
    }

    /* Alinear los controles existentes dentro de la celda Corregir. */
    table.querySelectorAll('tbody tr').forEach(row => {
        const inputs = Array.from(row.querySelectorAll('input'));
        const nuevoCosto = inputs.find(el =>
            el.type === 'number' ||
            (el.name && /costo/i.test(el.name))
        );
        const motivo = inputs.find(el =>
            el !== nuevoCosto &&
            (el.type === 'text' || (el.name && /motivo/i.test(el.name)))
        );

        const accion = Array.from(row.querySelectorAll('button,input[type="submit"],a'))
            .find(el => {
                const txt = (el.textContent || el.value || '').trim();
                return txt === 'Corregir';
            });

        if (!nuevoCosto || !motivo || !accion) return;

        const candidates = [nuevoCosto, motivo, accion];
        let container = candidates[0].parentElement;
        while (container && container !== row) {
            if (candidates.every(el => container.contains(el))) break;
            container = container.parentElement;
        }
        if (!container || container === row) return;

        container.classList.add('ep-correct-inline');

        /* Mover directamente los 3 controles al grid y ocultar rótulos repetidos. */
        container.querySelectorAll('label').forEach(label => {
            const txt=label.textContent.trim();
            if(txt==='Nuevo costo' || txt==='Motivo'){
                label.classList.add('ep-correct-field-label');
            }
        });

        container.appendChild(nuevoCosto);
        container.appendChild(motivo);
        container.appendChild(accion);
        accion.classList.add('ep-correct-action');
    });

    /* Estilo de la cabecera interna con exactamente las mismas 3 columnas. */
    const style=document.createElement('style');
    style.textContent=`
      .op3-main table.ep-correct-table .ep-correct-head-grid{
        display:grid !important;
        grid-template-columns:minmax(150px,1fr) minmax(190px,1fr) auto !important;
        align-items:center !important;
        gap:10px !important;
        width:100% !important;
      }
      .op3-main table.ep-correct-table .ep-correct-head-grid span:last-child{
        text-align:center !important;
      }
      @media (max-width:900px){
        .op3-main table.ep-correct-table .ep-correct-head-grid{
          grid-template-columns:minmax(130px,1fr) minmax(170px,1fr) auto !important;
          gap:8px !important;
        }
      }
    `;
    document.head.appendChild(style);
});
</script>

HTML;

$footer='/<\?php\s+render_footer_v3\(\);\s*\?>/';
if(preg_match_all($footer,$s)!==1){
    fwrite(STDERR,"ERROR: footer no encontrado de forma única.\n"); exit(1);
}
$s=preg_replace($footer,$block.'<?php render_footer_v3(); ?>',$s,1);

foreach([
    'ELABORAPRO_CORREGIR_V4_12_1',
    'ep-correct-inline',
    'ep-correct-head-grid',
    'Nuevo costo',
    'Motivo',
    'Acciones'
] as $needle){
    if(strpos($s,$needle)===false){
        fwrite(STDERR,"ERROR validación: $needle\n"); exit(1);
    }
}

if(file_put_contents($f,$s)===false){
    fwrite(STDERR,"ERROR escribiendo temporal.\n"); exit(1);
}
echo "OK: V4.12.1 preparado en temporal.\n";
PHP

echo
echo "===== LINT TEMPORAL ====="
php -l "$TMP"

echo
echo "===== VALIDACION ====="
grep -n -E 'ELABORAPRO_CORREGIR_V4_12_1|ep-correct-inline|ep-correct-head-grid' "$TMP" | tail -30

echo
echo "===== INSTALANDO ====="
cp -p "$TMP" "$F"

echo
echo "===== LINT FINAL ====="
if ! php -l "$F"; then
    echo "ERROR: restaurando respaldo..."
    cp -p "$B/compra_corregir_v3.php" "$F"
    exit 1
fi

echo
echo "=============================================="
echo " OK - Corregir compra V4.12.1 instalado"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
