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

echo "=============================================="
echo " ElaboraPro Presupuesto Editar V4.17.1"
echo " Quitar -> Eliminar rojo"
echo "=============================================="

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

TS=$(date +%Y%m%d_%H%M%S)
B="backups/elaborapro_presupuesto_editar_v4_17_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_PRESUPUESTO_EDITAR_V4_17_1')!==false){
 fwrite(STDERR,"ERROR: V4.17.1 ya aplicado.\n");exit(11);
}

/* Identifica el enlace por la operación real &del=, no por formato visual. */
$pat='~<a\b(?=[^>]*href=["\'][^"\']*presupuesto_editar_v3\.php\?id=[^"\']*&del=[^"\']*["\'])[^>]*>.*?</a>~isu';
if(preg_match_all($pat,$s)!==1){
 fwrite(STDERR,"ERROR: enlace de eliminación &del= no encontrado de forma única.\n");exit(20);
}
$s=preg_replace_callback($pat,function($m){
 $tag=$m[0];

 /* Preserva href y onclick; cambia sólo clase, texto y confirmación. */
 if(preg_match('~\bclass=(["\'])(.*?)\1~is',$tag)){
   $tag=preg_replace('~\bclass=(["\'])(.*?)\1~is','class=$1btn ep-budget-delete$1',$tag,1);
 } else {
   $tag=preg_replace('~^<a\b~i','<a class="btn ep-budget-delete"',$tag,1);
 }

 $tag=preg_replace(
   '~onclick=(["\'])return\s+confirm\(\s*[\'"]¿Quitar esta línea\?[\'"]\s*\)\1~iu',
   'onclick="return confirm(\'¿Eliminar esta línea del presupuesto?\')"',
   $tag,1
 );

 $tag=preg_replace('~>\s*Quitar\s*</a>~iu', '>Eliminar</a>', $tag,1,$nText);
 if($nText!==1){
   fwrite(STDERR,"ERROR: texto Quitar no encontrado dentro del enlace.\n");exit(21);
 }
 return $tag;
},$s,1,$changed);

if($changed!==1){fwrite(STDERR,"ERROR modificando enlace.\n");exit(22);}

$css=<<<'CSS'

<style>
/* ELABORAPRO_PRESUPUESTO_EDITAR_V4_17_1 */
body.op3-body .op3-main a.btn.ep-budget-delete{
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:#F3C2BE!important;border:1px solid #EAB0AB!important;color:#8B302C!important;
text-decoration:none!important;white-space:nowrap!important;box-shadow:none!important;font-weight:600!important}
body.op3-body .op3-main a.btn.ep-budget-delete:hover{
background:#ECB3AE!important;border-color:#DFA39E!important;color:#7A2926!important}
</style>

CSS;

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

foreach([
 'ELABORAPRO_PRESUPUESTO_EDITAR_V4_17_1',
 'ep-budget-delete',
 '>Eliminar</a>',
 '&del=',
 '¿Eliminar esta línea del presupuesto?'
] as $x){
 if(strpos($s,$x)===false){fwrite(STDERR,"ERROR validación: $x\n");exit(40);}
}
if(preg_match('~>\s*Quitar\s*</a>~iu',$s)){fwrite(STDERR,"ERROR: todavía existe Quitar.\n");exit(41);}

if(file_put_contents($f,$s)===false){fwrite(STDERR,"ERROR escribiendo temporal.\n");exit(50);}
echo "OK: V4.17.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 -B4 -A5 -E 'Eliminar|ep-budget-delete|ELABORAPRO_PRESUPUESTO_EDITAR_V4_17_1' "$TMP" | tail -50

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

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

echo "=============================================="
echo " OK - Presupuesto Editar V4.17.1 instalado"
echo " Quitar -> Eliminar"
echo " Eliminar = rojo pastel"
echo " Confirmación actualizada"
echo " Lógica &del= preservada"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
