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

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

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_$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) exit(1);
if(strpos($s,'ELABORAPRO_CORREGIR_V4_12')!==false){
  fwrite(STDERR,"ERROR: V4.12 ya aplicado.\n"); exit(1);
}

/*
 * Esta versión no toca la lógica PHP de corrección.
 * Reorganiza visualmente la tabla al cargarla:
 * - encabezado Corregir -> Nuevo costo / Motivo / Acciones
 * - elimina los rótulos repetidos Nuevo costo y Motivo de cada fila
 * - compacta y alinea filas
 * - botón Corregir azul pastel
 */
$block=<<<'HTML'

<style>
/* ELABORAPRO_CORREGIR_V4_12 */
.op3-main table.ep-correct-table tbody td{
    vertical-align:middle !important;
    padding-top:10px !important;
    padding-bottom:10px !important;
}
.op3-main table.ep-correct-table input{
    margin:0 !important;
}
.op3-main table.ep-correct-table .ep-correct-field-label{
    display:none !important;
}
.op3-main table.ep-correct-table .ep-correct-action{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:center !important;
    min-height:38px !important;
    padding:7px 14px !important;
    border-radius:8px !important;
    background:#C9DCFA !important;
    background-color:#C9DCFA !important;
    border:1px solid #AFCBF8 !important;
    color:#174F9E !important;
    box-shadow:none !important;
    white-space:nowrap !important;
}
.op3-main table.ep-correct-table .ep-correct-action:hover{
    background:#BBD3F8 !important;
    background-color:#BBD3F8 !important;
    border-color:#9EBFF3 !important;
    color:#123F80 !important;
}
@media (min-width:900px){
    .op3-main table.ep-correct-table input[type="number"]{
        min-width:130px !important;
    }
    .op3-main table.ep-correct-table input[type="text"]{
        min-width:190px !important;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const tables = Array.from(document.querySelectorAll('.op3-main table'));
    const table = tables.find(t => {
        const txt = (t.textContent || '').replace(/\s+/g,' ').trim();
        return txt.includes('Costo actual') &&
               txt.includes('Total actual') &&
               txt.includes('Nuevo costo') &&
               txt.includes('Motivo');
    });
    if (!table) return;

    table.classList.add('ep-correct-table');

    const headRow = table.querySelector('thead tr');
    if (headRow) {
        const ths = Array.from(headRow.querySelectorAll('th'));
        const last = ths[ths.length - 1];
        if (last && last.textContent.trim() === 'Corregir') {
            last.textContent = 'Nuevo costo';

            const motivo = document.createElement('th');
            motivo.textContent = 'Motivo';
            last.after(motivo);

            const acciones = document.createElement('th');
            acciones.textContent = 'Acciones';
            motivo.after(acciones);
        }
    }

    table.querySelectorAll('tbody tr').forEach(row => {
        row.querySelectorAll('label').forEach(label => {
            const txt = label.textContent.trim();
            if (txt === 'Nuevo costo' || txt === 'Motivo') {
                label.classList.add('ep-correct-field-label');
            }
        });

        row.querySelectorAll('button,input[type="submit"],a').forEach(el => {
            if (el.textContent.trim() === 'Corregir' ||
                (el.value && el.value.trim() === 'Corregir')) {
                el.classList.add('ep-correct-action');
            }
        });
    });
});
</script>

HTML;

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

foreach(['ELABORAPRO_CORREGIR_V4_12','ep-correct-table','ep-correct-action','#C9DCFA'] as $x){
  if(strpos($s,$x)===false){fwrite(STDERR,"ERROR validación: $x\n");exit(1);}
}
if(file_put_contents($f,$s)===false) exit(1);
echo "OK: cambios preparados en temporal.\n";
PHP

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

echo
echo "=== VALIDACION ==="
grep -n -E 'ELABORAPRO_CORREGIR_V4_12|ep-correct-table|ep-correct-action|C9DCFA' "$TMP" | tail -40

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 instalado"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
