#!/bin/bash
# ---------------------------------------------------------------------------
# RidinFamily — Rendre exploitables les erreurs d'attributs de variante Splash.
#
# Aujourd'hui, un attribut invalide produit :
#     "Product Attribute Value Name is Not Valid."
# ...sans dire quel produit ni quel attribut. C'est ce qui a rendu le
# diagnostic du 02/09/2026 si long (attributs foyer/membre, produit 269).
#
# Après patch :
#     "Product Attribute Value Name is Not Valid. [produit RF-INS-2023-NON-3M
#      (id 269) / attribut foyer] (reçu: '')"
#
# Aucun surcoût de log : on enrichit les messages existants, on n'en ajoute pas.
#
# Usage :  ./patch_splash_messages.sh            # vérification seule
#          ./patch_splash_messages.sh --apply    # sauvegarde + application
#          ./patch_splash_messages.sh --revert   # restaure la sauvegarde
# ---------------------------------------------------------------------------
set -euo pipefail

F="$HOME/ridin/dolibarr/htdocs/custom/splash/src/Objects/Product/Variants/AttributesTrait.php"
BAKDIR="$HOME/_modbak_splashmsg"
MARKER="MODIF Pichinov : contexte d erreur"
ACTION="${1:-}"

[ -f "$F" ] || { echo "ABSENT : $F"; exit 1; }
is_patched() { grep -q "$MARKER" "$F"; }

echo "=== Messages d'erreur des attributs de variante ==="
if is_patched; then echo "État : DÉJÀ patché"; else echo "État : NON patché"; fi

if [ "$ACTION" = "--revert" ]; then
  LAST=$(ls -1t "$BAKDIR"/AttributesTrait.php.* 2>/dev/null | head -1 || true)
  [ -n "$LAST" ] || { echo "Aucune sauvegarde dans $BAKDIR"; exit 1; }
  cp "$LAST" "$F"; echo "Restauré depuis $LAST"; php -l "$F"; exit 0
fi

if [ "$ACTION" != "--apply" ]; then
  echo; echo "Vérification seule. Relancer avec --apply pour sauvegarder et patcher."
  exit 0
fi
if is_patched; then echo "Rien à faire."; exit 0; fi

mkdir -p "$BAKDIR"
TS=$(date +%Y%m%d-%H%M%S)
cp "$F" "$BAKDIR/AttributesTrait.php.$TS"
echo "Sauvegarde : $BAKDIR/AttributesTrait.php.$TS  (hors du module)"

php -r '
$f = $argv[1];
$src = file_get_contents($f);
$changes = 0;

// --- 1) isValidAttributeDefinition : construire le contexte et le propager ---
$old1 = "        // Check Attributes Code is Given\n"
      . "        if (empty(\$attrData[\"code\"]) || !is_string(\$attrData[\"code\"])) {\n"
      . "            return Splash::log()->err(\" Product Attribute Code is Not Valid.\");\n"
      . "        }";
$new1 = "        // MODIF Pichinov : contexte d erreur (produit + attribut concernes)\n"
      . "        \$context = sprintf(\n"
      . "            \" [produit %s (id %s) / attribut %s]\",\n"
      . "            \$this->object->ref ?? \"?\",\n"
      . "            \$this->object->id ?? \"?\",\n"
      . "            is_scalar(\$attrData[\"code\"] ?? null) ? (string) \$attrData[\"code\"] : \"?\"\n"
      . "        );\n"
      . "        // Check Attributes Code is Given\n"
      . "        if (empty(\$attrData[\"code\"]) || !is_string(\$attrData[\"code\"])) {\n"
      . "            return Splash::log()->err(\" Product Attribute Code is Not Valid.\".\$context);\n"
      . "        }";

$old2 = "        if (!\$this->isValidScalarData(\$attrData, \"name\", \"Public Name\")) {";
$new2 = "        if (!\$this->isValidScalarData(\$attrData, \"name\", \"Public Name\", \$context)) {";

$old3 = "        if (!\$this->isValidScalarData(\$attrData, \"value\", \"Value Name\")) {";
$new3 = "        if (!\$this->isValidScalarData(\$attrData, \"value\", \"Value Name\", \$context)) {";

// --- 2) isValidScalarData : accepter le contexte et montrer la valeur reçue ---
$old4 = "    private function isValidScalarData(array \$attrData, string \$key, string \$name): bool\n"
      . "    {\n"
      . "        //====================================================================//\n"
      . "        // Check Attributes Values are Given\n"
      . "        if (empty(\$attrData[\$key]) || !is_scalar(\$attrData[\$key])) {\n"
      . "            return Splash::log()->err(\"Product Attribute \".\$name.\" is Not Valid.\");\n"
      . "        }";
$new4 = "    private function isValidScalarData(array \$attrData, string \$key, string \$name, string \$context = \"\"): bool\n"
      . "    {\n"
      . "        //====================================================================//\n"
      . "        // Check Attributes Values are Given\n"
      . "        if (empty(\$attrData[\$key]) || !is_scalar(\$attrData[\$key])) {\n"
      . "            return Splash::log()->err(\n"
      . "                \"Product Attribute \".\$name.\" is Not Valid.\".\$context\n"
      . "                .\" (recu: \".var_export(\$attrData[\$key] ?? null, true).\")\"\n"
      . "            );\n"
      . "        }";

foreach (array(array($old1,$new1,"contexte"), array($old2,$new2,"name"),
               array($old3,$new3,"value"), array($old4,$new4,"isValidScalarData")) as $p) {
    list($old, $new, $label) = $p;
    $n = substr_count($src, $old);
    if (1 !== $n) { fwrite(STDERR, "ARRET : motif \"".$label."\" trouve ".$n." fois (attendu 1)\n"); exit(1); }
    $src = str_replace($old, $new, $src);
    $changes++;
}
file_put_contents($f, $src);
echo $changes." remplacement(s) appliques.\n";
' "$F"

echo "=== Lint ==="
php -l "$F"
