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

echo "=============================================="
echo " ElaboraPro Stock V4.18"
echo " Buscar + Expandir en una línea"
echo "=============================================="

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

TS=$(date +%Y%m%d_%H%M%S)
B="backups/elaborapro_stock_v4_18_$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"

if ! TMP="$TMP" php <<'PHP'
<?php
$f=getenv('TMP'); $s=file_get_contents($f);
if($s===false){fwrite(STDERR,"ERROR leyendo archivo.\n");exit(10);}
if(strpos($s,'ELABORAPRO_STOCK_V4_18')!==false){fwrite(STDERR,"ERROR: V4.18 ya aplicado.\n");exit(11);}

/* Marcar formulario de búsqueda por el input q. */
$forms='~<form\b([^>]*)>(?=(?:(?!</form>).)*\bname=["\']q["\'])(.*?)</form>~isu';
if(preg_match_all($forms,$s)!==1){fwrite(STDERR,"ERROR: formulario de búsqueda q no único.\n");exit(20);}
$s=preg_replace_callback($forms,function($m){
 $open='<form'.$m[1].'>';
 if(preg_match('~\bclass=(["\'])(.*?)\1~is',$open))
   $open=preg_replace('~\bclass=(["\'])(.*?)\1~is','class=$1$2 ep-stock-search$1',$open,1);
 else
   $open=substr($open,0,-1).' class="ep-stock-search">';
 $open=preg_replace('~\s+style=(["\']).*?\1~is','',$open);
 return $open.$m[2].'</form>';
},$s,1);

/* Marcar Expandir todos dondequiera que esté, sin cambiar su JS/href. */
$pat='~<(a|button)\b([^>]*)>\s*Expandir todos\s*</\1>~isu';
if(preg_match_all($pat,$s)!==1){fwrite(STDERR,"ERROR: control Expandir todos no único.\n");exit(30);}
$s=preg_replace_callback($pat,function($m){
 $tag=$m[1]; $attrs=$m[2];
 if(preg_match('~\bclass=(["\'])(.*?)\1~is',$attrs))
   $attrs=preg_replace('~\bclass=(["\'])(.*?)\1~is','class=$1$2 ep-stock-expand$1',$attrs,1);
 else
   $attrs=' class="ep-stock-expand"'.$attrs;
 return '<'.$tag.$attrs.'>Expandir todos</'.$tag.'>';
},$s,1);

/*
 * CSS: el formulario ocupa una sola línea.
 * Expandir se reposiciona visualmente junto a Buscar aunque en el HTML
 * sea hermano inmediato posterior. Se usa display:contents en el wrapper
 * sólo si el layout actual ya los mantiene en el mismo bloque.
 */
$css=<<<'CSS'

<style>
/* ELABORAPRO_STOCK_V4_18 */
body.op3-body .op3-main form.ep-stock-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;
}
body.op3-body .op3-main form.ep-stock-search input[name="q"]{
 flex:1 1 auto!important;
 width:auto!important;
 min-width:0!important;
 margin:0!important;
}
body.op3-body .op3-main form.ep-stock-search button,
body.op3-body .op3-main form.ep-stock-search .btn{
 flex:0 0 auto!important;
 width:auto!important;
 margin:0!important;
}
body.op3-body .op3-main .ep-stock-expand{
 display:inline-flex!important;
 align-items:center!important;
 justify-content:center!important;
 min-height:34px!important;
 padding:6px 12px!important;
 border-radius:8px!important;
 background:#BFE3C9!important;
 border:1px solid #A8D5B5!important;
 color:#205C36!important;
 text-decoration:none!important;
 white-space:nowrap!important;
 box-shadow:none!important;
 font-weight:600!important;
}
body.op3-body .op3-main .ep-stock-expand:hover{
 background:#AEDAB9!important;
 border-color:#9BCDAA!important;
 color:#205C36!important;
}
</style>

CSS;

/*
 * Mover Expandir dentro del formulario, justo después de Buscar.
 * Captura el control ya marcado y lo elimina de su posición original.
 */
$expandPat='~<(a|button)\b([^>]*\bep-stock-expand\b[^>]*)>Expandir todos</\1>~isu';
if(!preg_match($expandPat,$s,$em)){fwrite(STDERR,"ERROR: no se pudo capturar Expandir.\n");exit(31);}
$expand=$em[0];
$s=preg_replace($expandPat,'',$s,1,$removed);
if($removed!==1){fwrite(STDERR,"ERROR retirando Expandir original.\n");exit(32);}

/* Insertarlo antes del cierre del formulario de búsqueda. */
$searchForm='~(<form\b[^>]*\bep-stock-search\b[^>]*>.*?)(</form>)~isu';
if(preg_match_all($searchForm,$s)!==1){fwrite(STDERR,"ERROR: formulario marcado no único.\n");exit(33);}
$s=preg_replace($searchForm,'$1'.$expand.'$2',$s,1);

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

foreach(['ELABORAPRO_STOCK_V4_18','ep-stock-search','ep-stock-expand','Expandir todos'] as $x)
 if(strpos($s,$x)===false){fwrite(STDERR,"ERROR validación: $x\n");exit(50);}

if(file_put_contents($f,$s)===false){fwrite(STDERR,"ERROR escribiendo temporal.\n");exit(60);}
echo "OK: V4.18 preparado en temporal.\n";
PHP
then
 echo "ERROR: parche abortado. No se instaló ningún cambio."
 exit 1
fi

echo "===== LINT TEMPORAL ====="
php -l "$TMP"
echo "===== VALIDACION ====="
grep -n -B4 -A8 -E 'ep-stock-search|ep-stock-expand|ELABORAPRO_STOCK_V4_18' "$TMP" | tail -70

cp -p "$TMP" "$F"
if ! php -l "$F"; then
 echo "ERROR: restaurando respaldo..."
 cp -p "$B/stock_v3.php" "$F"; exit 1
fi

echo "=============================================="
echo " OK - Stock V4.18 instalado"
echo " Buscar + Expandir = misma línea"
echo " Expandir = verde pastel"
echo " Lógica original preservada"
echo "=============================================="
