<?php
// envoyer-article.php → MODE DIEU 2025 (upload + auto-add JSON + mail)
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

if (!$data || empty($data['fichier']) || empty($data['nomfichier'])) {
    echo json_encode(['success' => false, 'message' => 'Données manquantes']);
    exit;
}

// 1. Créer le fichier .html
$fileName = $data['nomfichier'];
$htmlContent = base64_decode($data['fichier']);
file_put_contents($fileName, $htmlContent);

// 2. Ajouter automatiquement dans articles.json
$article = [
    "titre" => $data['titre'],
    "extrait" => substr(strip_tags($data['contenu']), 0, 150) . "...",
    "url" => $fileName,
    "image" => $data['image'] ?: "https://stock-exchange-crypto.com/images/default-pro.jpg",
    "date" => date("d F Y"),
    "prix" => $data['prix'],
    "mots" => ($data['prix'] == 19 ? 500 : ($data['prix'] == 33 ? 1000 : 2000)),
    "theme" => "crypto"
];

$jsonFile = 'articles.json';
$current = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];
$current[] = $article;
file_put_contents($jsonFile, json_encode($current, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

// 3. Envoi mail avec pièce jointe
$to = "info@stock-exchange-crypto.com";
$subject = "NOUVEAU BACKLINK À VALIDER - {$data['titre']} ({$data['prix']}€)";
$message = "
Nouvel article en attente de paiement/validation :
Titre : {$data['titre']}
Lien : https://stock-exchange-crypto.com/{$fileName}
Email client : {$data['email']}
Prix : {$data['prix']}€
Mots : " . ($data['prix'] == 19 ? 500 : ($data['prix'] == 33 ? 1000 : 2000)) . "

LIEN DIRECT DU FICHIER : https://stock-exchange-crypto.com/{$fileName}

Valider = laisser en ligne
Supprimer = supprimer le fichier en FTP
";

$boundary = md5(time());
$headers = "From: no-reply@stock-exchange-crypto.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"";

$body = "--{$boundary}\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
$body .= $message . "\r\n\r\n";
$body .= "--{$boundary}\r\n";
$body .= "Content-Type: text/html; name=\"{$fileName}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$fileName}\"\r\n\r\n";
$body .= chunk_split(base64_encode($htmlContent)) . "\r\n";
$body .= "--{$boundary}--";

mail($to, $subject, $body, $headers);

echo json_encode(['success' => true]);
?>