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

echo "=============================================="
echo " ElaboraPro Ventas V4.13.1"
echo " Botones y buscador"
echo "=============================================="

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

TS=$(date +%Y%m%d_%H%M%S)
B="backups/elaborapro_ventas_v4_13_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 archivo.\n");exit(1);}
if(strpos($s,'ELABORAPRO_VENTAS_V4_13_1')!==false){
    fwrite(STDERR,"ERROR: V4.13.1 ya aplicado.\n"); exit(1);
}

function once(&$s,$old,$new,$label){
    $n=substr_count($s,$old);
    if($n!==1){
        fwrite(STDERR,"ERROR patrón $label: coincidencias=$n\n");
        exit(1);
    }
    $s=str_replace($old,$new,$s);
}

/* Botones: reemplazos exactos según fuente diagnosticada */
once(
    $s,
    '<a class="badge" href="<?= BASE_URL ?>/venta_editar_v3.php?id=<?= (int)$r[\'id\'] ?>">',
    '<a class="btn ep-sale-action ep-sale-detail" href="<?= BASE_URL ?>/venta_editar_v3.php?id=<?= (int)$r[\'id\'] ?>">',
    'Detalle'
);

once(
    $s,
    '<a class="badge" href="<?= BASE_URL ?>/venta_stock_revisar_v3.php?id=<?= (int)$r[\'id\'] ?>">',
    '<a class="btn ep-sale-action ep-sale-review" href="<?= BASE_URL ?>/venta_stock_revisar_v3.php?id=<?= (int)$r[\'id\'] ?>">',
    'Revisar stock'
);

once(
    $s,
    'class="badge good"' . "\n" . '                                onclick="return confirm(\'¿Descontar stock de esta venta?\')"',
    'class="btn ep-sale-action ep-sale-stock"' . "\n" . '                                onclick="return confirm(\'¿Descontar stock de esta venta?\')"',
    'Descontar stock'
);

/* Buscador */
once(
    $s,
    '<form method="get" class="no-print" style="margin:15px 0;display:flex;gap:10px;flex-wrap:wrap">',
    '<form method="get" class="no-print ep-sale-search">',
    'Formulario Buscar'
);

$css=<<<'HTML'

<style>
/* ELABORAPRO_VENTAS_V4_13_1 */
.op3-main .ep-sale-action{
    display:inline-flex !important;
    align-items:center !important;
    justify-content:center !important;
    min-height:34px !important;
    padding:6px 12px !important;
    border-radius:8px !important;
    line-height:1.15 !important;
    text-decoration:none !important;
    white-space:nowrap !important;
    box-shadow:none !important;
}

/* Detalle: verde pastel */
.op3-main a.btn.ep-sale-detail{
    background:#BFE3C9 !important;
    border:1px solid #A8D5B5 !important;
    color:#205C36 !important;
}
.op3-main a.btn.ep-sale-detail:hover{
    background:#AEDAB9 !important;
    border-color:#9BCDAA !important;
    color:#205C36 !important;
}

/* Revisar stock: gris neutro */
.op3-main a.btn.ep-sale-review{
    background:#F1F3F5 !important;
    border:1px solid #DCE3EA !important;
    color:#475569 !important;
}
.op3-main a.btn.ep-sale-review:hover{
    background:#E7EAEE !important;
    border-color:#CDD5DE !important;
    color:#334155 !important;
}

/* Descontar stock: azul pastel */
.op3-main a.btn.ep-sale-stock{
    background:#C9DCFA !important;
    border:1px solid #AFCBF8 !important;
    color:#174F9E !important;
}
.op3-main a.btn.ep-sale-stock:hover{
    background:#BBD3F8 !important;
    border-color:#9EBFF3 !important;
    color:#123F80 !important;
}

/* Barra Buscar + botón en una sola línea */
.op3-main form.ep-sale-search{
    margin:15px 0 !important;
    display:flex !important;
    flex-direction:row !important;
    align-items:center !important;
    gap:10px !important;
    flex-wrap:nowrap !important;
    width:100% !important;
}
.op3-main form.ep-sale-search input[name="q"]{
    flex:1 1 auto !important;
    width:auto !important;
    min-width:0 !important;
    margin:0 !important;
}
.op3-main form.ep-sale-search button.btn{
    flex:0 0 auto !important;
    width:auto !important;
    margin:0 !important;
}
@media(max-width:640px){
    .op3-main form.ep-sale-search{gap:8px !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);

foreach([
    'ELABORAPRO_VENTAS_V4_13_1',
    'ep-sale-detail',
    'ep-sale-review',
    'ep-sale-stock',
    'ep-sale-search',
    '¿Descontar stock de esta venta?'
] 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.13.1 preparado en temporal.\n";
PHP

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

echo
echo "===== VALIDACION ====="
grep -n -E 'ELABORAPRO_VENTAS_V4_13_1|ep-sale-(detail|review|stock|search)' "$TMP" | tail -50

echo
echo "===== VERIFICAR LOGICA DESCUENTO ====="
grep -n -B3 -A8 '¿Descontar stock de esta venta?' "$TMP"

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

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

echo
echo "=============================================="
echo " OK - Ventas V4.13.1 instalado"
echo " Detalle        = verde pastel"
echo " Revisar stock  = gris"
echo " Descontar stock= azul pastel"
echo " Buscar         = alineado"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
