Deploy: 2026-05-23 23:18:56

This commit is contained in:
Hamza-Ayed
2026-05-23 23:18:56 +03:00
parent bae23e8da7
commit b627a52c6e
3 changed files with 565 additions and 91 deletions

View File

@@ -207,107 +207,50 @@ class SuperAdminController extends BaseController
return;
}
// Get the WhatsApp session for the Super Admin company (ID 1)
// Get the active session for the Super Admin company (ID 1)
$session = \App\Models\WhatsAppSession::findByCompany(1);
if (!$session) {
$response->status(404)->json(['error' => 'Super Admin WhatsApp session not found']);
if (!$session || $session['status'] !== 'connected') {
$response->status(404)->json(['error' => 'Super Admin WhatsApp session not active or connected']);
return;
}
try {
$sessionId = $session['id'];
// 1. Fetch all logged messages for this session
$messages = Database::select(
"SELECT * FROM messages_log WHERE session_id = ? ORDER BY id ASC",
[$sessionId]
);
// Send request to the WhatsApp gateway to export chats
$gatewayUrl = rtrim(getenv('WHATSAPP_GATEWAY_URL') ?: 'http://localhost:3722', '/');
if (substr($gatewayUrl, -4) === '/api') {
$exportUrl = substr($gatewayUrl, 0, -4) . '/api/chats/export';
} else {
$exportUrl = $gatewayUrl . '/api/chats/export';
}
// 2. Fetch all contacts for Company 1 to map phone numbers to names
$contactsList = Database::select(
"SELECT name, phone FROM contacts WHERE company_id = 1"
);
$contactNames = [];
foreach ($contactsList as $c) {
try {
$decryptedPhone = Security::decrypt($c['phone']);
$contactNames[$decryptedPhone] = $c['name'];
} catch (\Exception $e) {
// Skip decryption failure for this specific contact
}
}
$payload = json_encode([
'session_key' => $session['session_key']
]);
// 3. Construct the formatted chat log
$outputText = "==================================================\n";
$outputText .= "سجل محادثات منصة نبيه - جلسة: " . $session['session_key'] . "\n";
$outputText .= "تاريخ التصدير: " . date('Y-m-d H:i:s') . "\n";
$outputText .= "==================================================\n\n";
if (empty($messages)) {
$outputText .= "لا يوجد سجل رسائل متاح في قاعدة البيانات لهذه الجلسة.\n";
} else {
// Group messages by decrypted contact phone number
$chats = [];
foreach ($messages as $msg) {
try {
$phone = Security::decrypt($msg['contact_phone']);
} catch (\Exception $e) {
$phone = 'unknown_' . ($msg['contact_phone_hash'] ?? $msg['id']);
}
if (!isset($chats[$phone])) {
$chats[$phone] = [];
}
$chats[$phone][] = $msg;
}
// Format each chat group
foreach ($chats as $phone => $chatMsgs) {
$name = isset($contactNames[$phone]) ? $contactNames[$phone] : 'عميل غير مسمى';
$outputText .= "--------------------------------------------------\n";
$outputText .= "المحادثة مع: {$name} ({$phone})\n";
$outputText .= "--------------------------------------------------\n";
foreach ($chatMsgs as $msg) {
$fromMe = $msg['direction'] === 'outbound';
$sender = $fromMe ? 'المنصة (نبيه)' : $name;
try {
$body = Security::decrypt($msg['message_body']);
} catch (\Exception $e) {
$body = '[خطأ في فك تشفير الرسالة]';
}
$dateStr = $msg['created_at'];
if ($msg['message_type'] === 'text') {
$outputText .= "[{$dateStr}] {$sender}: {$body}\n";
} else if ($msg['message_type'] === 'audio') {
$outputText .= "[{$dateStr}] {$sender}: [رسالة صوتية] " . ($body ? "- {$body}" : "") . "\n";
} else if ($msg['message_type'] === 'image') {
$outputText .= "[{$dateStr}] {$sender}: [صورة] " . ($body ? "- {$body}" : "") . "\n";
} else {
$outputText .= "[{$dateStr}] {$sender}: [" . $msg['message_type'] . "] " . ($body ? "- {$body}" : "") . "\n";
}
}
$outputText .= "\n\n";
}
}
// 4. Write the file to public directory
$publicDir = __DIR__ . '/../../public';
$filePath = $publicDir . '/whatsapp_chats_history.txt';
file_put_contents($filePath, $outputText);
$ch = curl_init($exportUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'X-Webhook-Secret: ' . getenv('WEBHOOK_SECRET')
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$data = json_decode($result, true);
$response->json([
'status' => 'success',
'message' => 'Chat history exported successfully from database',
'message' => 'Chat history exported successfully',
'download_url' => '/whatsapp_chats_history.txt'
]);
} catch (\Exception $e) {
error_log("[SuperAdminController Export Error] " . $e->getMessage());
$response->status(500)->json([
'error' => 'Failed to export chats from database: ' . $e->getMessage()
]);
} else {
$err = json_decode($result, true);
$errMsg = $err['error'] ?? 'HTTP Code ' . $httpCode;
$response->status(500)->json(['error' => 'Failed to export chats: ' . $errMsg]);
}
}
}