<?php
// Secure token check to prevent unauthorized execution
if (($_GET['token'] ?? '') !== 'restore_nabeh_9281') {
    http_response_code(403);
    die('Unauthorized');
}

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Core\Database;

header('Content-Type: text/plain; charset=utf-8');

echo "=== Restoring WhatsApp Sessions ===\n\n";

$sessions = Database::select("SELECT * FROM whatsapp_sessions WHERE status = 'connected'");

if (empty($sessions)) {
    echo "No connected sessions found in the database.\n";
    exit;
}

$gatewayUrl = rtrim(getenv('WHATSAPP_GATEWAY_URL') ?: 'http://localhost:3722', '/');
if (substr($gatewayUrl, -4) === '/api') {
    $startUrl = substr($gatewayUrl, 0, -4) . '/api/sessions/start';
} else {
    $startUrl = $gatewayUrl . '/api/sessions/start';
}
$appUrl = rtrim(getenv('APP_URL') ?: 'https://nabeh.intaleqapp.com', '/');

foreach ($sessions as $session) {
    echo "Restoring session: {$session['session_key']} for company ID: {$session['company_id']}...\n";
    
    $payload = json_encode([
        'session_key' => $session['session_key'],
        'webhook_url' => $appUrl . '/api/whatsapp/webhook'
    ]);
    
    $ch = curl_init($startUrl);
    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, 10);
    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    echo "Response (HTTP {$httpCode}): {$res}\n\n";
}

echo "=== Sessions Restore Complete ===\n";
