<?phpob_clean();header("Content-Type: application/json; charset=utf-8");error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);ini_set("display_errors", 0);$dest = "IMAGES_CHARGES/";$fichierLecture  = "Import_Image_06_12_2025-6.txt";$fichierEcriture = "Import_Image.txt";if (!is_dir($dest)) mkdir($dest, 0777, true);/* ============================================================   Nettoyer nom de fichier   ============================================================ */function nettoyer_nom_fichier($str) {    $str = strtolower($str);    $str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);    $str = preg_replace('/[^a-z0-9\.]/', '', $str);    return $str;}/* ============================================================   MISE À JOUR Import_Image.txt   (corrigé : remplacement OK même si guillemets)   ============================================================ */function updateImportImage($fichier, $ref, $nouvelleLigne) {    $out = [];    $existe = false;    // Normalise la référence cible    $refClean = trim($ref, "\"");    if (file_exists($fichier)) {        $lines = file($fichier, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);        foreach ($lines as $l) {            $cols = explode(";", $l);            if (count($cols) < 7) continue;            // Nettoie la référence de la ligne            $refL = trim($cols[3], "\"");            if ($refL === $refClean) {                // Ligne trouvée → on remplace                $out[] = $nouvelleLigne;                $existe = true;            } else {                $out[] = $l;            }        }    }    // Si aucune ligne existante → on ajoute    if (!$existe) {        $out[] = $nouvelleLigne;    }    // Réécrit entièrement le fichier    file_put_contents($fichier, implode("\n", $out) . "\n");}/* ============================================================   UPLOAD FTP   ============================================================ */function uploadFTP($localFile, $remoteName){    $ftp_server = "ftp.whost20.fr";    $ftp_user   = "whostb-011";    $ftp_pass   = "BianhFDn0";    $remote_dir = "PRODUITS/";    if (!file_exists($localFile)) {        return ["status" => "error", "msg" => "Fichier local introuvable"];    }    $conn_id = ftp_connect($ftp_server);    if (!$conn_id) {        return ["status" => "error", "msg" => "Connexion FTP impossible"];    }    if (!ftp_login($conn_id, $ftp_user, $ftp_pass)) {        ftp_close($conn_id);        return ["status" => "error", "msg" => "Identifiants FTP incorrects"];    }    ftp_pasv($conn_id, true);    if (!@ftp_chdir($conn_id, $remote_dir)) {        ftp_close($conn_id);        return ["status" => "error", "msg" => "Dossier FTP inaccessible : $remote_dir"];    }    $ok = ftp_put($conn_id, $remoteName, $localFile, FTP_BINARY);    ftp_close($conn_id);    if (!$ok) {        return ["status" => "error", "msg" => "Échec upload FTP"];    }    return ["status" => "ok"];}/* ============================================================   Référence   ============================================================ */$ref = trim($_POST["reference"] ?? "");if ($ref === "") {    echo json_encode(["status" => "error", "message" => "Aucune référence reçue"]);    exit;}/* ============================================================   Cherche la ligne d’origine dans Import_Image_06_12_2025-6.txt   ============================================================ */$linesLecture = file($fichierLecture, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);$ligneData = null;foreach ($linesLecture as $l) {    $cols = explode(";", $l);    if (count($cols) < 7) continue;    $refFichier = trim($cols[3], "\"");    if ($refFichier === $ref) {        $ligneData = $cols;        break;    }}if (!$ligneData) {    echo json_encode(["status" => "error", "message" => "Référence introuvable"]);    exit;}/* ============================================================   Construction de la ligne   ============================================================ */function ligne7($cols, $nom){    return trim($cols[0]) . ";" .           trim($cols[1]) . ";" .           trim($cols[2]) . ";" .           trim($cols[3], "\"") . ";" .   // supprime guillemets           trim($cols[4]) . ";" .           trim($cols[5]) . ";" .           $nom;}/* ============================================================   UPLOAD FICHIER LOCAL   ============================================================ */if (!empty($_FILES["file"]["name"])) {    $fileTmp  = $_FILES["file"]["tmp_name"];    $fileName = nettoyer_nom_fichier($_FILES["file"]["name"]);    $nom = nettoyer_nom_fichier($ref . "_" . $fileName);    $chemin = $dest . $nom;    if (!move_uploaded_file($fileTmp, $chemin)) {        echo json_encode(["status" => "error", "message" => "Erreur upload fichier"]);        exit;    }    $ligneFinale = ligne7($ligneData, $nom);    updateImportImage($fichierEcriture, $ref, $ligneFinale);    // FTP    $ftp = uploadFTP($chemin, $nom);    if ($ftp["status"] !== "ok") {        echo json_encode(["status" => "error", "message" => "Image OK mais FTP KO : ".$ftp["msg"]]);        exit;    }    echo json_encode(["status" => "ok", "fichier" => $nom, "ftp" => "ok"]);    exit;}/* ============================================================   UPLOAD PAR URL   ============================================================ */$image_url = trim($_POST["image_url"] ?? "");if ($image_url !== "") {    $nomOriginal = nettoyer_nom_fichier(basename(parse_url($image_url, PHP_URL_PATH)));    if (!$nomOriginal) $nomOriginal = "image.png";    $nom = nettoyer_nom_fichier($ref . "_" . $nomOriginal);    $chemin = $dest . $nom;    $data = @file_get_contents($image_url);    if ($data === false) {        echo json_encode(["status" => "error", "message" => "Téléchargement impossible"]);        exit;    }    file_put_contents($chemin, $data);    $ligneFinale = ligne7($ligneData, $nom);    updateImportImage($fichierEcriture, $ref, $ligneFinale);    // FTP    $ftp = uploadFTP($chemin, $nom);    if ($ftp["status"] !== "ok") {        echo json_encode(["status" => "error", "message" => "Image OK mais FTP KO : ".$ftp["msg"]]);        exit;    }    echo json_encode(["status" => "ok", "fichier" => $nom, "ftp" => "ok"]);    exit;}/* ============================================================   AUCUN FICHIER NI URL   ============================================================ */echo json_encode(["status" => "error", "message" => "Aucun fichier ou URL fourni"]);exit;?>