stripe = new StripeClient($stripeSecretKey); } } /** * Envoyer l'email de confirmation de commande * Remplace la fonction Supabase send-order-confirmation-email */ public function sendConfirmationEmail(Request $request) { $validator = Validator::make($request->all(), [ 'orderData' => 'required|array', 'sessionId' => 'nullable|string', ]); if ($validator->fails()) { return response()->json([ 'error' => 'Données invalides: ' . $validator->errors()->first() ], 400); } $orderData = $request->input('orderData'); $sessionId = $request->input('sessionId'); // 1. Récupérer l'email vérifié depuis la session Stripe $customerEmail = null; if ($sessionId && $this->stripe) { try { $session = $this->stripe->checkout->sessions->retrieve($sessionId); $customerEmail = $session->customer_details->email ?? $session->customer_email ?? null; } catch (ApiErrorException $e) { \Log::error('Error retrieving Stripe session: ' . $e->getMessage()); $customerEmail = $orderData['email'] ?? $orderData['customer_email'] ?? null; } } else { $customerEmail = $orderData['email'] ?? $orderData['customer_email'] ?? null; } // 2. Enregistrer la commande dans la base de données $finalOrderData = [ ...$orderData, 'customer_email' => $customerEmail, 'session_id' => $sessionId, 'status' => 'En attente de traitement', ]; try { $order = Order::create($finalOrderData); } catch (\Exception $e) { \Log::error('Error saving order: ' . $e->getMessage()); $order = null; } // 3. Envoyer l'email client $customerEmailResult = null; $customerEmailError = null; if ($customerEmail && env('RESEND_API_KEY')) { $customerEmailResult = $this->sendCustomerEmail($customerEmail, $orderData, $order); if (!$customerEmailResult) { $customerEmailError = 'Erreur lors de l\'envoi de l\'email client'; } } // 4. Envoyer l'email admin $adminEmailResult = null; $adminEmailError = null; if (env('RESEND_API_KEY') && env('ADMIN_EMAIL')) { $adminEmailResult = $this->sendAdminEmail($orderData, $order, $sessionId, $customerEmail); if (!$adminEmailResult) { $adminEmailError = 'Erreur lors de l\'envoi de l\'email admin'; } } return response()->json([ 'success' => true, 'orderId' => $order?->id ?? 'N/A', 'customerEmail' => $customerEmail, 'emailSent' => !!$customerEmailResult, 'customerEmailError' => $customerEmailError, 'adminEmailSent' => !!$adminEmailResult, 'adminEmailError' => $adminEmailError, ], 200); } private function sendCustomerEmail(string $customerEmail, array $orderData, ?Order $order): bool { $resendApiKey = env('RESEND_API_KEY'); if (!$resendApiKey) { return false; } $orderId = $order?->id ? substr($order->id, 0, 8) : ''; $html = $this->getCustomerEmailTemplate($orderData, $orderId); try { $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $resendApiKey, 'Content-Type' => 'application/json', ])->post('https://api.resend.com/emails', [ 'from' => 'Dites le en chanson ', 'to' => [$customerEmail], 'subject' => "Votre commande Dites le en chanson est confirmée ! (ID: {$orderId})", 'html' => $html, ]); return $response->successful(); } catch (\Exception $e) { \Log::error('Error sending customer email: ' . $e->getMessage()); return false; } } private function sendAdminEmail(array $orderData, ?Order $order, ?string $sessionId, ?string $customerEmail): bool { $resendApiKey = env('RESEND_API_KEY'); $adminEmail = env('ADMIN_EMAIL'); if (!$resendApiKey || !$adminEmail) { return false; } $orderId = $order?->id ?? 'N/A'; $html = $this->getAdminEmailTemplate($orderData, $orderId, $sessionId, $customerEmail); try { $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $resendApiKey, 'Content-Type' => 'application/json', ])->post('https://api.resend.com/emails', [ 'from' => 'Dites le en chanson ', 'to' => [$adminEmail], 'subject' => "Nouvelle commande reçue (ID: " . substr($orderId, 0, 8) . ")", 'html' => $html, ]); return $response->successful(); } catch (\Exception $e) { \Log::error('Error sending admin email: ' . $e->getMessage()); return false; } } private function getCustomerEmailTemplate(array $orderData, string $orderId): string { // Pré-calculer les valeurs pour éviter l'utilisation de ?? dans le heredoc $recipientName = $orderData['recipient_name'] ?? 'cher client'; $productName = $orderData['product_name'] ?? 'Chanson personnalisée'; $priceDisplay = isset($orderData['price']) ? $orderData['price'] . ' €' : '—'; $recipientNameDisplay = $orderData['recipient_name'] ?? '—'; $language = $orderData['language'] ?? '—'; $voiceGender = $orderData['voice_gender'] ?? '—'; $musicalStyle = $orderData['musical_style'] ?? '—'; $mood = $orderData['mood'] ?? '—'; $anecdote1 = isset($orderData['anecdote1']) ? "

Anecdote 1: {$orderData['anecdote1']}

" : ""; $anecdote2 = isset($orderData['anecdote2']) ? "

Anecdote 2: {$orderData['anecdote2']}

" : ""; $anecdote3 = isset($orderData['anecdote3']) ? "

Anecdote 3: {$orderData['anecdote3']}

" : ""; return << Confirmation de votre commande - Dites le en chanson
Dites-le en chanson Logo

Merci pour votre commande !

Bonjour {$recipientName},

Nous sommes ravis de vous confirmer que votre commande a bien été enregistrée. Notre équipe de créateurs est déjà prête à composer votre chanson personnalisée !

Récapitulatif de votre commande (ID: {$orderId}) :

Produit: {$productName}

Prix Payé: {$priceDisplay}

Pour: {$recipientNameDisplay}

Langue: {$language}

Voix: {$voiceGender}

Style: {$musicalStyle}

Ambiance: {$mood}

{$anecdote1} {$anecdote2} {$anecdote3}

Délai de création : Votre chanson unique sera prête et vous sera livrée par email dans les 48 heures.

Nous mettons tout notre cœur pour transformer vos histoires en mélodies inoubliables.

Si vous avez la moindre question, n'hésitez pas à nous contacter.

Visiter notre site

HTML; } private function getAdminEmailTemplate(array $orderData, string $orderId, ?string $sessionId, ?string $customerEmail): string { $sessionIdDisplay = $sessionId ?? 'N/A'; $customerEmailDisplay = $customerEmail ?? 'N/A'; // Pré-calculer les valeurs pour éviter l'utilisation de ?? dans le heredoc $recipientName = $orderData['recipient_name'] ?? 'Non spécifié'; $songForWhom = $orderData['song_for_whom'] ?? 'Non spécifié'; $occasion = $orderData['occasion'] ?? 'Non spécifié'; $language = $orderData['language'] ?? 'Non spécifié'; $anecdote1 = $orderData['anecdote1'] ?? 'Non spécifié'; $anecdote2 = $orderData['anecdote2'] ?? 'Non spécifié'; $anecdote3 = $orderData['anecdote3'] ?? 'Non spécifié'; $voiceGender = $orderData['voice_gender'] ?? 'Non spécifié'; $musicalStyle = $orderData['musical_style'] ?? 'Non spécifié'; $mood = $orderData['mood'] ?? 'Non spécifié'; $price = $orderData['price'] ?? 'Non spécifié'; $productName = $orderData['product_name'] ?? 'Non spécifié'; return << Nouvelle Commande Reçue

Nouvelle Commande Reçue !

Une nouvelle commande a été passée sur votre site.

ID de Commande : {$orderId}

ID de Session Stripe : {$sessionIdDisplay}

Email du Client : {$customerEmailDisplay}

Statut : En attente de traitement

Détails de la commande :

HTML; } }