<?php
function logDebug($message) {
    file_put_contents('webhook_debug.log', date('Y-m-d H:i:s') . " - " . $message . PHP_EOL, FILE_APPEND);
}

logDebug("Webhook aufgerufen.");

// --- KONFIGURATION ---
$nextcloud_url = 'URL EINFÜGEN';
$nextcloud_user = 'USER EINFÜGEN';
$nextcloud_pass = 'APP PASSWORT EINFÜGEN'; 
$api_key = 'API KEY EINFPÜGEN';
$webhook_secret = 'Secret von Docuseal!';
$signature = '';

if (function_exists('getallheaders')) {
    $headers = array_change_key_case(getallheaders(), CASE_LOWER);
    $signature = $headers['x-docuseal-signature'] ?? '';
}

if (empty($signature)) {
    $signature = $_SERVER['HTTP_X_DOCUSEAL_SIGNATURE'] ?? $_SERVER['x-docuseal-signature'] ?? '';
}

logDebug("Signature erhalten: " . (!empty($signature) ? "JA (Wert vorhanden)" : "NEIN (Leer)"));

if (empty($signature) || $signature !== $webhook_secret) {
    logDebug("FEHLER: Secret passt nicht oder Header fehlt. Erhalten: " . $signature);
    http_response_code(403);
    die('Zugriff verweigert: Secret passt nicht.'); 
}

$json = file_get_contents('php://input'); 
$data = json_decode($json, true);
$event = $data['event_type'] ?? 'unbekannt';

logDebug("Event empfangen: " . $event);

if ($event === 'submission.completed' || $event === 'form.submitted') {
    $pdf_url = $data['data']['documents'][0]['url'] ?? '';
    logDebug("PDF-URL gefunden: " . $pdf_url);
    
    $fields = $data['data']['submitters'][0]['values'] ?? [];
    $values = [];
    foreach ($fields as $item) {
        $values[$item['field']] = $item['value'];
    }
    
    $vorname  = $values['Vorname'] ?? 'unbekannt';
    $nachname = $values['Nachname'] ?? 'volunteer';
    
    $search  = [' ', 'ä', 'ö', 'ü', 'ß', ';', '/', '\\', ':'];
    $replace = ['_', 'ae', 'oe', 'ue', 'ss', '-', '-', '-', '-'];
    $safe_nachname = str_replace($search, $replace, strtolower($nachname));
    $safe_vorname  = str_replace($search, $replace, strtolower($vorname));
    
    $time_raw = $data['data']['completed_at'] ?? 'now';
    $datum    = date('Y-m-d', strtotime($time_raw));
    $uhrzeit  = date('H-i', strtotime($time_raw));
    $filename = $safe_nachname . '_' . $safe_vorname . '_' . $datum . '_' . $uhrzeit . '.pdf';
    
    logDebug("Zieldateiname formatiert: $filename");

    if (!empty($pdf_url)) {

        $ch_down = curl_init($pdf_url);
        curl_setopt($ch_down, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch_down, CURLOPT_FOLLOWLOCATION, true);
        $pdf_content = curl_exec($ch_down);
        $down_status = curl_getinfo($ch_down, CURLINFO_HTTP_CODE);
        curl_close($ch_down);

        if ($pdf_content && $down_status == 200) {
            logDebug("PDF per cURL geladen (" . strlen($pdf_content) . " Bytes). Starte Upload...");
            $full_target_url = rtrim($nextcloud_url, '/') . '/' . rawurlencode($filename);
            
            $ch_up = curl_init($full_target_url);
            curl_setopt($ch_up, CURLOPT_USERPWD, $nextcloud_user . ':' . $nextcloud_pass);
            curl_setopt($ch_up, CURLOPT_PUT, 1);
            curl_setopt($ch_up, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_up, CURLOPT_BINARYTRANSFER, true);
            
            $fh = tmpfile();
            fwrite($fh, $pdf_content);
            fseek($fh, 0);
            
            curl_setopt($ch_up, CURLOPT_INFILE, $fh);
            curl_setopt($ch_up, CURLOPT_INFILESIZE, strlen($pdf_content));
            
            $result = curl_exec($ch_up);
            $http_code = curl_getinfo($ch_up, CURLINFO_HTTP_CODE);
            curl_close($ch_up);
            fclose($fh);
        
            logDebug("Nextcloud HTTP-Code: " . $http_code);  
            
            if ($http_code >= 200 && $http_code < 300) {
                echo "Erfolg!";
                logDebug("DATEI ERFOLGREICH IN NEXTCLOUD ERSTELLT: $filename");
    
                $submission_id = $data['data']['id'] ?? null;
                if ($submission_id) {
                    $ch_del = curl_init("URL EINFÜGEN" . $submission_id);
                    curl_setopt($ch_del, CURLOPT_CUSTOMREQUEST, "DELETE");
                    curl_setopt($ch_del, CURLOPT_HTTPHEADER, [
                        "X-Auth-Token: " . $api_key,
                        "Content-Type: application/json"
                    ]);
                    curl_setopt($ch_del, CURLOPT_RETURNTRANSFER, true);
                    $del_result = curl_exec($ch_del);
                    $del_status = curl_getinfo($ch_del, CURLINFO_HTTP_CODE);
                    curl_close($ch_del);
                    
                    logDebug("DocuSeal Löschauftrag ID $submission_id gesendet. Status: $del_status. Antwort: $del_result");
                }
            } else {
                http_response_code(500);
                logDebug("UPLOAD FEHLGESCHLAGEN. HTTP-Code: " . $http_code . " Antwort: " . $result);
            }
        } else {
            logDebug("FEHLER: PDF konnte nicht per cURL heruntergeladen werden. Status: " . $down_status);
        }
    }
} else {
    logDebug("Event $event wird ignoriert.");
}
?>