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

echo "=============================================="
echo " ElaboraPro Presupuestos V4.16.1"
echo " Botones y búsqueda"
echo "=============================================="

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

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

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_PRESUPUESTOS_V4_16_1')!==false){
 fwrite(STDERR,"ERROR: V4.16.1 ya aplicado.\n");exit(11);
}

function patchHrefClass(&$s,$hrefNeedle,$newClass,$label){
 $pat='~<a\b(?=[^>]*href=["\'][^"\']*'.preg_quote($hrefNeedle,'~').'[^"\']*["\'])[^>]*>~is';
 if(preg_match_all($pat,$s)!==1){
   fwrite(STDERR,"ERROR: $label no encontrado de forma única.\n");exit(20);
 }
 $s=preg_replace_callback($pat,function($m)use($newClass){
   $tag=$m[0];
   if(preg_match('~\bclass=(["\'])(.*?)\1~is',$tag)){
     return preg_replace('~\bclass=(["\'])(.*?)\1~is','class=$1btn ep-budget-action '.$newClass.'$1',$tag,1);
   }
   return preg_replace('~^<a\b~i','<a class="btn ep-budget-action '.$newClass.'"',$tag,1);
 },$s,1);
}

patchHrefClass($s,'presupuesto_editar_v3.php?id=','ep-budget-detail','Detalle');
patchHrefClass($s,'presupuesto_costos_v3.php?id=','ep-budget-neutral','Costos');
patchHrefClass($s,'presupuesto_presentacion_v3.php?id=','ep-budget-neutral','Presentación');
patchHrefClass($s,'presupuestos_v3.php?convertir=','ep-budget-convert','Convertir a venta');

/* Formulario de búsqueda exacto según diagnóstico */
$old='class="no-print"'."\n".'        style="margin:15px 0;display:flex;gap:10px;flex-wrap:wrap"';
$new='class="no-print ep-budget-search"';
if(substr_count($s,$old)!==1){
 fwrite(STDERR,"ERROR: formulario de búsqueda no coincide con diagnóstico.\n");exit(30);
}
$s=str_replace($old,$new,$s);

$css=<<<'CSS'

<style>
/* ELABORAPRO_PRESUPUESTOS_V4_16_1 */
body.op3-body .op3-main .ep-budget-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;font-weight:600!important}
body.op3-body .op3-main a.ep-budget-detail{
background:#BFE3C9!important;border:1px solid #A8D5B5!important;color:#205C36!important}
body.op3-body .op3-main a.ep-budget-detail:hover{
background:#AEDAB9!important;border-color:#9BCDAA!important;color:#205C36!important}
body.op3-body .op3-main a.ep-budget-neutral{
background:#F1F3F5!important;border:1px solid #DCE3EA!important;color:#475569!important}
body.op3-body .op3-main a.ep-budget-neutral:hover{
background:#E7EAEE!important;border-color:#CDD5DE!important;color:#334155!important}
body.op3-body .op3-main a.ep-budget-convert{
background:#C9DCFA!important;border:1px solid #AFCBF8!important;color:#174F9E!important}
body.op3-body .op3-main a.ep-budget-convert:hover{
background:#BBD3F8!important;border-color:#9EBFF3!important;color:#123F80!important}
body.op3-body .op3-main form.ep-budget-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-budget-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-budget-search button{
flex:0 0 auto!important;width:auto!important;margin:0!important}
</style>

CSS;

$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_PRESUPUESTOS_V4_16_1','ep-budget-detail','ep-budget-neutral','ep-budget-convert','ep-budget-search'] 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.16.1 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 -B2 -A3 -E 'ep-budget-(detail|neutral|convert|search)|ELABORAPRO_PRESUPUESTOS_V4_16_1' "$TMP" | tail -80

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

echo "=============================================="
echo " OK - Presupuestos V4.16.1 instalado"
echo " Detalle           = verde pastel"
echo " Costos            = gris"
echo " Presentación      = gris"
echo " Convertir a venta = azul pastel"
echo " Buscar            = alineado"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
