<?php
/**
 * Test-WhatsApp-Template
 */

// Alle Ausgaben vor JSON unterdrücken
ob_start();

// PHP-Warnings und Errors unterdrücken
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json');
require_once '../config/database.php';

session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Nicht angemeldet']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || $input['action'] !== 'test_whatsapp_template') {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Ungültige Anfrage']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Hole WhatsApp-Einstellungen
    $stmt = $conn->prepare("
        SELECT setting_key, setting_value FROM settings 
        WHERE setting_key IN ('whatsapp_api_key', 'whatsapp_template_id', 'whatsapp_phone_number', 'whatsapp_business_name')
    ");
    $stmt->execute();
    $settings = [];
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    $apiKey = $settings['whatsapp_api_key'] ?? '';
    $templateId = $settings['whatsapp_template_id'] ?? '';
    $phoneNumber = $settings['whatsapp_phone_number'] ?? '+49123456789';
    $businessName = $settings['whatsapp_business_name'] ?? 'Boxenstop Volvo Service';
    
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    if (empty($apiKey)) {
        echo json_encode([
            'success' => false, 
            'error' => 'Kein HelloMateo API-Key konfiguriert. Bitte geben Sie Ihren API-Key in den Einstellungen ein.',
            'template_id' => $templateId,
            'status' => 'Kein API-Key'
        ]);
        exit;
    }
    
    if (empty($templateId)) {
        echo json_encode([
            'success' => true, 
            'message' => 'Kein Template konfiguriert - verwende Standard-Nachrichten',
            'template_id' => 'Kein Template',
            'status' => 'Standard-Nachrichten aktiv'
        ]);
        exit;
    }
    
    // Teste Template mit HelloMateo API
    $url = 'https://api.hellomateo.com/v1/templates/' . $templateId;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $templateData = json_decode($response, true);
        echo json_encode([
            'success' => true, 
            'message' => 'Template erfolgreich abgerufen',
            'template_id' => $templateId,
            'status' => 'Template verfügbar',
            'template_name' => $templateData['name'] ?? 'Unbekannt',
            'template_status' => $templateData['status'] ?? 'Unbekannt'
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'error' => 'Template nicht gefunden oder API-Fehler (HTTP: ' . $httpCode . ')',
            'template_id' => $templateId,
            'status' => 'Fehler'
        ]);
    }
    
} catch (Exception $e) {
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => false, 
        'error' => 'Fehler: ' . $e->getMessage()
    ]);
}
?>
