#!/bin/bash
# ---------------------------------------------------------------------------
# RidinFamily — Nommer le produit dans l'erreur de création Splash.
#
# Aujourd'hui :
#     Splash\Local\Objects\Product::createSimpleProduct() => Un produit avec la référence existe déjà.
#     Unable to create new Product.
# ...sans jamais dire QUELLE référence, ni quel produit Dolibarr la porte déjà.
#
# Après patch :
#     Unable to create new Product [ref: RF-INS-2025 / label: Inscription club 2025/2026]
#     — reference deja portee par le produit id 731 (Inscription club 2025/2026)
#
# Usage :  ./patch_splash_create_context.sh            # vérification seule
#          ./patch_splash_create_context.sh --apply    # sauvegarde + application
#          ./patch_splash_create_context.sh --revert   # restaure la sauvegarde
# ---------------------------------------------------------------------------
set -euo pipefail

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

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

echo "=== Erreur de création de produit ==="
if is_patched; then echo "État : DÉJÀ patché"; else echo "État : NON patché"; fi

if [ "$ACTION" = "--revert" ]; then
  LAST=$(ls -1t "$BAKDIR"/CRUDTrait.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/CRUDTrait.php.$TS"
echo "Sauvegarde : $BAKDIR/CRUDTrait.php.$TS"

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

$old = "            \$this->catchDolibarrErrors(\$product);\n\n"
     . "            return Splash::log()->errNull(\"Unable to create new Product.\");";

$new = "            \$this->catchDolibarrErrors(\$product);\n"
     . "            //====================================================================//\n"
     . "            // MODIF Pichinov : contexte de creation (quelle ref, et qui la porte deja)\n"
     . "            \$conflict = \"\";\n"
     . "            \$existing = new Product(\$db);\n"
     . "            // Dolibarr assainit la reference a la creation (ex. \"/\" -> \"_\") :\n"
     . "            // chercher la forme brute ET la forme assainie.\n"
     . "            \$sanitized = dol_sanitizeFileName(dol_string_nospecial(trim(\$ref)));\n"
     . "            \$found = (\$existing->fetch(0, \$ref) > 0)\n"
     . "                || ((\$sanitized != \$ref) && (\$existing->fetch(0, \$sanitized) > 0));\n"
     . "            if (\$found) {\n"
     . "                \$conflict = sprintf(\n"
     . "                    \" - reference deja portee par le produit id %s (ref Dolibarr: %s / %s)\",\n"
     . "                    \$existing->id,\n"
     . "                    \$existing->ref,\n"
     . "                    \$existing->label\n"
     . "                );\n"
     . "            }\n\n"
     . "            return Splash::log()->errNull(sprintf(\n"
     . "                \"Unable to create new Product [ref: %s / label: %s]%s\",\n"
     . "                \$ref,\n"
     . "                \$label,\n"
     . "                \$conflict\n"
     . "            ));";

$n = substr_count($src, $old);
if (1 !== $n) { fwrite(STDERR, "ARRET : motif trouve ".$n." fois (attendu 1)\n"); exit(1); }
file_put_contents($f, str_replace($old, $new, $src));
echo "Patch appliqué.\n";
' "$F"

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