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

echo "=============================================="
echo " ElaboraPro Corregir Compra V4.12.2"
echo " Alineacion estructural HTML"
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_2_$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_2') !== false) {
    fwrite(STDERR, "ERROR: V4.12.2 ya aplicado.\n");
    exit(1);
}

/* 1) Cabecera real: 10 columnas */
$oldHead = <<<'HTML'
                <th>Total actual</th>
                <th class="no-print">Corregir</th>
HTML;

$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;

if (substr_count($s, $oldHead) !== 1) {
    fwrite(STDERR, "ERROR: patrón de cabecera original no encontrado de forma única.\n");
    exit(1);
}
$s = str_replace($oldHead, $newHead, $s);

/* 2) Sin líneas: ahora son 10 columnas */
if (substr_count($s, '<td colspan="8">Sin líneas.</td>') !== 1) {
    fwrite(STDERR, "ERROR: colspan original no encontrado.\n");
    exit(1);
}
$s = str_replace(
    '<td colspan="8">Sin líneas.</td>',
    '<td colspan="10">Sin líneas.</td>',
    $s
);

/* 3) Reemplazar la única celda con formulario por 3 celdas reales.
      Se conserva un solo FORM por fila usando atributo form= para inputs/botón. */
$pattern = '~[ \t]*<td class="no-print">\s*'
         . '<form method="post" style="display:flex;gap:8px;flex-wrap:wrap;align-items:end">\s*'
         . '<input type="hidden" name="detalle_id" value="<\?= \(int\)\$r\[\'id\'\] \?>">\s*'
         . '<p>\s*<label>Nuevo costo</label>\s*'
         . '<input\s+type="number"\s+step="0\.0001"\s+name="nuevo_costo_unitario"\s+value="<\?= h\(\$r\[\'costo_unitario\'\]\) \?>"\s+required\s*>\s*'
         . '</p>\s*'
         . '<p>\s*<label>Motivo</label>\s*'
         . '<input\s+name="motivo"\s+placeholder="Ej: error digitación factura"\s+required\s*>\s*'
         . '</p>\s*'
         . '<button\s+class="btn"\s+onclick="return confirm\(\'¿Corregir costo de esta línea\?\'\)"\s*>\s*'
         . 'Corregir\s*</button>\s*</form>\s*</td>~s';

$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;

$count = 0;
$s = preg_replace($pattern, $newCells, $s, 1, $count);
if ($count !== 1) {
    fwrite(STDERR, "ERROR: formulario original no encontrado exactamente una vez.\n");
    exit(1);
}

/* 4) Eliminar parches V4.12 y V4.12.1 completos.
      Ya no necesitamos JS para reconstruir la tabla. */
$legacy = '~\s*<style>\s*/\* ELABORAPRO_CORREGIR_V4_12 \*/.*?'
        . '<script>.*?</script>\s*'
        . '<style>\s*/\* ELABORAPRO_CORREGIR_V4_12_1 \*/.*?'
        . '<script>.*?</script>\s*~s';

$legacyCount = 0;
$s = preg_replace($legacy, "\n", $s, 1, $legacyCount);
if ($legacyCount !== 1) {
    fwrite(STDERR, "ERROR: no fue posible retirar conjuntamente V4.12/V4.12.1.\n");
    exit(1);
}

/* 5) CSS limpio y directo sobre HTML real */
$css = <<<'HTML'

<style>
/* ELABORAPRO_CORREGIR_V4_12_2 */
.op3-main .ep-correct-table{
    width:100%;
    table-layout:auto;
}

.op3-main .ep-correct-table th{
    vertical-align:middle;
    white-space:nowrap;
}

.op3-main .ep-correct-table tbody td{
    vertical-align:middle !important;
    padding-top:12px !important;
    padding-bottom:12px !important;
}

.op3-main .ep-correct-table .ep-correct-hidden-form{
    display:none !important;
}

.op3-main .ep-correct-table .ep-correct-cost-cell,
.op3-main .ep-correct-table .ep-correct-reason-cell,
.op3-main .ep-correct-table .ep-correct-actions-cell{
    vertical-align:middle !important;
}

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

.op3-main .ep-correct-table .ep-correct-cost-cell{
    min-width:150px;
}

.op3-main .ep-correct-table .ep-correct-reason-cell{
    min-width:210px;
}

.op3-main .ep-correct-table .ep-correct-actions-cell{
    width:1%;
    white-space:nowrap;
    text-align:center;
}

.op3-main .ep-correct-table .ep-correct-action{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:center !important;
    min-height:42px !important;
    margin:0 !important;
    padding:8px 16px !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 .ep-correct-table .ep-correct-action:hover{
    background:#BBD3F8 !important;
    background-color:#BBD3F8 !important;
    border-color:#9EBFF3 !important;
    color:#123F80 !important;
}

/* En pantallas angostas la tabla puede desplazarse horizontalmente
   sin romper la alineación de columnas. */
.op3-main .ep-correct-table{
    min-width:1050px;
}
</style>

HTML;

/* Añadir clase directamente a la tabla real */
if (substr_count($s, '<table class="table">') !== 1) {
    fwrite(STDERR, "ERROR: tabla principal no encontrada de forma única.\n");
    exit(1);
}
$s = str_replace(
    '<table class="table">',
    '<table class="table ep-correct-table">',
    $s
);

$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);

/* Validaciones */
foreach ([
    'ELABORAPRO_CORREGIR_V4_12_2',
    '<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',
    'form="corregir-linea-<?= (int)$r[\'id\'] ?>"',
    '#C9DCFA'
] as $needle) {
    if (strpos($s, $needle) === false) {
        fwrite(STDERR, "ERROR validación: $needle\n");
        exit(1);
    }
}

if (strpos($s, 'ELABORAPRO_CORREGIR_V4_12_1') !== false ||
    strpos($s, 'document.addEventListener') !== false) {
    fwrite(STDERR, "ERROR: quedó lógica visual legacy.\n");
    exit(1);
}

if (file_put_contents($f, $s) === false) {
    fwrite(STDERR, "ERROR escribiendo temporal.\n");
    exit(1);
}

echo "OK: estructura HTML V4.12.2 preparada.\n";
PHP

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

echo
echo "===== VALIDACION ESTRUCTURA ====="
grep -n -E 'ep-correct-table|Nuevo costo|Motivo|Acciones|ep-correct-(cost|reason|actions)-cell|ep-correct-action|colspan="10"' "$TMP" | tail -n 80

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.2 instalado"
echo " HTML real: Nuevo costo | Motivo | Acciones"
echo " Sin JavaScript de redistribucion"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
