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

echo "=============================================="
echo " ElaboraPro Ventas V4.13 - Botones y búsqueda"
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_$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')!==false){
    fwrite(STDERR,"ERROR: V4.13 ya aplicado.\n"); exit(1);
}

/* Agregar clases semánticas según texto, sin tocar href ni lógica. */
$patterns = [
    'Detalle' => ['class'=>'ep-sale-detail', 'count'=>0],
    'Revisar stock' => ['class'=>'ep-sale-review', 'count'=>0],
    'Descontar stock' => ['class'=>'ep-sale-stock', 'count'=>0],
];

foreach ($patterns as $text => &$cfg) {
    $re='~<a\b([^>]*?)class=(["\'])([^"\']*)\2([^>]*)>\s*'.preg_quote($text,'~').'\s*</a>~is';
    $s=preg_replace_callback($re,function($m) use (&$cfg,$text){
        $cfg['count']++;
        $classes=trim($m[3].' ep-sale-action '.$cfg['class']);
        return '<a'.$m[1].'class='.$m[2].$classes.$m[2].$m[4].'>'.$text.'</a>';
    },$s);
}
unset($cfg);

foreach($patterns as $text=>$cfg){
    if($cfg['count']<1){
        fwrite(STDERR,"ERROR: no se encontró botón $text.\n"); exit(1);
    }
}

/* Identificar el formulario GET que contiene el campo q y añadir clase propia. */
$re='~<form\b([^>]*method=(["\'])get\2[^>]*)>([\s\S]*?<input\b[^>]*name=(["\'])q\4[^>]*>[\s\S]*?</form>)~i';
$s2=preg_replace_callback($re,function($m){
    $open=$m[1];
    if(preg_match('~class=(["\'])([^"\']*)\1~i',$open,$cm)){
        $newClass=trim($cm[2].' ep-sale-search');
        $open=preg_replace('~class=(["\'])([^"\']*)\1~i','class="'.$newClass.'"',$open,1);
    } else {
        $open.=' class="ep-sale-search"';
    }
    return '<form'.$open.'>'.$m[3];
},$s,1,$nSearch);
if($nSearch!==1){
    fwrite(STDERR,"ERROR: formulario Buscar no encontrado de forma única. coincidencias=$nSearch\n"); exit(1);
}
$s=$s2;

$css=<<<'HTML'

<style>
/* ELABORAPRO_VENTAS_V4_13 */
.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.ep-sale-detail{
    background:#BFE3C9 !important;
    border:1px solid #A8D5B5 !important;
    color:#205C36 !important;
}
.op3-main a.ep-sale-detail:hover{
    background:#AEDAB9 !important;
    border-color:#9BCDAA !important;
    color:#205C36 !important;
}

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

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

/* Buscar alineado a la derecha de la barra */
.op3-main form.ep-sale-search{
    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,
.op3-main form.ep-sale-search .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','ep-sale-detail','ep-sale-review','ep-sale-stock','ep-sale-search'] as $x){
    if(strpos($s,$x)===false){fwrite(STDERR,"ERROR validación: $x\n");exit(1);}
}
if(file_put_contents($f,$s)===false){fwrite(STDERR,"ERROR escribiendo temporal.\n");exit(1);}
echo "OK: cambios preparados en temporal.\n";
PHP

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

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

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 instalado"
echo " Detalle: verde pastel"
echo " Revisar stock: gris"
echo " Descontar stock: azul pastel"
echo " Buscar: alineado"
echo " Respaldo: /home/iotcuboc/pyme/$B"
echo "=============================================="
