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

echo "=============================================="
echo " ElaboraPro Corregir Compra V4.12.3"
echo " Reparacion estructural tolerante"
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_3_$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 archivo.\n");exit(1);}
if(strpos($s,'ELABORAPRO_CORREGIR_V4_12_3')!==false){
    fwrite(STDERR,"ERROR: V4.12.3 ya aplicado.\n"); exit(1);
}

/* La fuente PHP real sigue teniendo una cabecera Corregir.
   Los títulos Nuevo costo/Motivo/Acciones vistos en navegador eran creados por JS. */
$headPattern='~<th>\s*Total actual\s*</th>\s*<th[^>]*>\s*Corregir\s*</th>~i';
$newHead=<<<'HTML'
<th>Total actual</th>
                <th class="no-print">Nuevo costo</th>
                <th class="no-print">Motivo</th>
                <th class="no-print">Acciones</th>
HTML;
$s2=preg_replace($headPattern,$newHead,$s,1,$n);
if($s2===null || $n!==1){
    fwrite(STDERR,"ERROR: cabecera Total actual/Corregir no encontrada. coincidencias=$n\n"); exit(1);
}
$s=$s2;

/* colspan vacío */
$s=preg_replace('~<td\s+colspan=["\']8["\']>\s*Sin líneas\.\s*</td>~i',
                '<td colspan="10">Sin líneas.</td>',$s,1,$nCol);
if($nCol!==1){
    fwrite(STDERR,"ERROR: colspan=8 de Sin líneas no encontrado. coincidencias=$nCol\n"); exit(1);
}

/* Sustituir la celda original del formulario usando límites estables. */
$cellPattern='~<td\s+class=["\']no-print["\']>\s*'
    . '<form\s+method=["\']post["\'][^>]*>\s*'
    . '<input\s+type=["\']hidden["\']\s+name=["\']detalle_id["\'][^>]*>\s*'
    . '.*?'
    . '<button[^>]*>\s*Corregir\s*</button>\s*'
    . '</form>\s*</td>~is';

$newCells=<<<'HTML'
<td class="no-print ep-correct-cost-cell">
                        <form id="corregir-linea-<?= (int)$r['id'] ?>" method="post" class="ep-correct-hidden-form">
                            <input type="hidden" name="detalle_id" value="<?= (int)$r['id'] ?>">
                        </form>
                        <input
                            form="corregir-linea-<?= (int)$r['id'] ?>"
                            type="number"
                            step="0.0001"
                            name="nuevo_costo_unitario"
                            value="<?= h($r['costo_unitario']) ?>"
                            required
                            aria-label="Nuevo costo"
                        >
                    </td>
                    <td class="no-print ep-correct-reason-cell">
                        <input
                            form="corregir-linea-<?= (int)$r['id'] ?>"
                            name="motivo"
                            placeholder="Ej: error digitación factura"
                            required
                            aria-label="Motivo"
                        >
                    </td>
                    <td class="no-print ep-correct-actions-cell">
                        <button
                            form="corregir-linea-<?= (int)$r['id'] ?>"
                            type="submit"
                            class="btn ep-correct-action"
                            onclick="return confirm('¿Corregir costo de esta línea?')"
                        >Corregir</button>
                    </td>
HTML;

$s2=preg_replace($cellPattern,$newCells,$s,1,$nCell);
if($s2===null || $nCell!==1){
    fwrite(STDERR,"ERROR: celda/formulario Corregir no encontrada. coincidencias=$nCell\n"); exit(1);
}
$s=$s2;

/* Retirar TODOS los bloques visuales anteriores V4.12 y V4.12.1 por marcadores. */
$s=preg_replace(
    '~\s*<style>\s*/\*\s*ELABORAPRO_CORREGIR_V4_12\s*\*/.*?</style>\s*<script>.*?</script>~is',
    '', $s, 1, $n12
);
$s=preg_replace(
    '~\s*<style>\s*/\*\s*ELABORAPRO_CORREGIR_V4_12_1\s*\*/.*?</style>\s*<script>.*?</script>~is',
    '', $s, 1, $n121
);
if($n12!==1 || $n121!==1){
    fwrite(STDERR,"ERROR retirando legacy: V4.12=$n12 V4.12.1=$n121\n"); exit(1);
}

/* Tabla real con clase propia */
$s2=preg_replace('~<table\s+class=["\']table["\']\s*>~i',
                 '<table class="table ep-correct-table">',$s,1,$nTable);
if($s2===null || $nTable!==1){
    fwrite(STDERR,"ERROR: tabla principal no encontrada. coincidencias=$nTable\n"); exit(1);
}
$s=$s2;

$css=<<<'HTML'

<style>
/* ELABORAPRO_CORREGIR_V4_12_3 */
.op3-main .ep-correct-table{
    width:100% !important;
    min-width:1080px;
    table-layout:auto !important;
}
.op3-main .ep-correct-table thead th{
    vertical-align:middle !important;
    white-space:nowrap !important;
}
.op3-main .ep-correct-table tbody td{
    vertical-align:middle !important;
    padding-top:10px !important;
    padding-bottom:10px !important;
}
.op3-main .ep-correct-hidden-form{display:none !important;}

.op3-main .ep-correct-cost-cell{min-width:145px;}
.op3-main .ep-correct-reason-cell{min-width:210px;}
.op3-main .ep-correct-actions-cell{
    width:1%;
    min-width:105px;
    text-align:center;
    white-space:nowrap;
}

.op3-main .ep-correct-cost-cell input,
.op3-main .ep-correct-reason-cell input{
    display:block !important;
    width:100% !important;
    min-height:44px !important;
    margin:0 !important;
    box-sizing:border-box !important;
}

.op3-main .ep-correct-action{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:center !important;
    min-height:40px !important;
    margin:0 !important;
    padding:7px 14px !important;
    border-radius:8px !important;
    background:#C9DCFA !important;
    border:1px solid #AFCBF8 !important;
    color:#174F9E !important;
    box-shadow:none !important;
}
.op3-main .ep-correct-action:hover{
    background:#BBD3F8 !important;
    border-color:#9EBFF3 !important;
    color:#123F80 !important;
}
</style>

HTML;

$footer='~<\?php\s+render_footer_v3\(\);\s*\?>~';
if(preg_match_all($footer,$s)!==1){
    fwrite(STDERR,"ERROR: footer inesperado.\n");exit(1);
}
$s=preg_replace($footer,$css.'<?php render_footer_v3(); ?>',$s,1);

/* Validación estructural */
$checks=[
 'ELABORAPRO_CORREGIR_V4_12_3',
 '<th class="no-print">Nuevo costo</th>',
 '<th class="no-print">Motivo</th>',
 '<th class="no-print">Acciones</th>',
 'colspan="10"',
 'ep-correct-cost-cell',
 'ep-correct-reason-cell',
 'ep-correct-actions-cell',
 'ep-correct-action'
];
foreach($checks as $x){
    if(strpos($s,$x)===false){fwrite(STDERR,"ERROR validación: $x\n");exit(1);}
}
if(strpos($s,'document.addEventListener')!==false ||
   strpos($s,'ELABORAPRO_CORREGIR_V4_12_1')!==false){
    fwrite(STDERR,"ERROR: quedó JavaScript/legacy anterior.\n");exit(1);
}

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

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

echo
echo "===== VALIDACION ESTRUCTURAL ====="
grep -n -E 'Nuevo costo|Motivo|Acciones|ep-correct-(cost|reason|actions)-cell|ep-correct-action|ELABORAPRO_CORREGIR_V4_12_3' "$TMP" | tail -n 60

echo
echo "===== VERIFICAR SIN JS LEGACY ====="
if grep -n 'document.addEventListener' "$TMP"; then
    echo "ERROR: se detectó JS legacy."
    exit 1
else
    echo "OK: sin JS de redistribución."
fi

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