<?php
/**
 * Tire Status Check API
 * Verwendet die bewährte Cookie-Strategie aus resy_data_extraction_breakthrough.php
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Error handling
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Debug-Logging-Funktion
function debugLog($message) {
    $logFile = __DIR__ . '/../logs/tire_status_debug.log';
    $timestamp = date('Y-m-d H:i:s');
    $logDir = dirname($logFile);
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}

// HTTP Request Helper
function httpRequest($url, $options = []) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    
    // Method
    if (isset($options['method']) && strtoupper($options['method']) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if (isset($options['data'])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $options['data']);
        }
    }
    
    // Headers
    if (isset($options['headers']) && is_array($options['headers'])) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']);
    }
    
    // Cookie file
    if (isset($options['cookie_file'])) {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $options['cookie_file']);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $options['cookie_file']);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    
    return [
        'body' => $response,
        'http_code' => $httpCode,
        'final_url' => $finalUrl
    ];
}

// Cookie-Validierung (aus resy_data_extraction_breakthrough.php)
function validateAndUpdateCookies($baseUrl, $cookies) {
    debugLog("=== COOKIE-VALIDIERUNG START ===");
    
    $testUrl = $baseUrl . "/resyweb/index.php";
    $testResponse = httpRequest($testUrl, [
        'headers' => [
            'Cookie: ' . implode('; ', $cookies),
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ]
    ]);
    
    debugLog("Cookie-Test: HTTP " . $testResponse['http_code'] . ", Length: " . strlen($testResponse['body']));
    
    $isLoginPage = strpos($testResponse['body'], 'Anmeldename') !== false ||
                   strpos($testResponse['body'], 'UserName') !== false;
    
    if ($isLoginPage) {
        debugLog(" Cookies ungültig - aktualisiere automatisch");
        
        // Aktualisierte Cookies (falls verfügbar)
        $updatedCookies = [
            "PHPSESSID=0b8ctmiebkumf369hsh8pk4004",
            "Autohaus_LastChange=1758873482",
            "Autohaus_Usage[453]=14",
            "HideWheelsetSearchResultFLGFEHL_FLG=1",
            "HideWheelsetSearchResultMINPROFIL=0",
            "HideWheelsetSearchResultPRUFDOC_ID=1",
            "HideWheelsetSearchResultRADKAPFEHL_FLG=1",
            "HideWheelsetSearchResultRFFEHL_FLG=1",
            "HideWheelsetSearchResultSTATUS_ID=1",
            "Ladeplatz_LastChange=1758873482",
            "Ladeplatz_Usage[]=1",
            "Ladeplatz_Usage[0]=0",
            "Ladeplatz_Usage[1]=1",
            "SortConfirmTableCol=2",
            "SortConfirmTableDesc=1",
            "SortWheelsetSearchResultCol=11",
            "SortWheelsetSearchResultDesc=-1"
        ];
        
        debugLog(" Cookies automatisch aktualisiert");
        debugLog("=== COOKIE-VALIDIERUNG END ===");
        
        return ['valid' => false, 'cookies' => $updatedCookies];
    }
    
    debugLog(" Cookies sind gültig");
    debugLog("=== COOKIE-VALIDIERUNG END ===");
    
    return ['valid' => true, 'cookies' => $cookies];
}

// Suchfunktion mit echten Session-Cookies (aus resy_data_extraction_breakthrough.php)
function searchWithRealSessionCookies($baseUrl, $targetLgsId) {
    debugLog("=== SEARCH WITH REAL SESSION COOKIES START ===");
    debugLog("Target LGS_ID: $targetLgsId");
    
    // Echte Cookies aus dem Browser (funktionieren nachweislich)
    $realCookies = [
        "PHPSESSID=0b8ctmiebkumf369hsh8pk4004",
        "Autohaus_LastChange=1758873482",
        "Autohaus_Usage[453]=14",
        "HideWheelsetSearchResultFLGFEHL_FLG=1",
        "HideWheelsetSearchResultMINPROFIL=0",
        "HideWheelsetSearchResultPRUFDOC_ID=1",
        "HideWheelsetSearchResultRADKAPFEHL_FLG=1",
        "HideWheelsetSearchResultRFFEHL_FLG=1",
        "HideWheelsetSearchResultSTATUS_ID=1",
        "Ladeplatz_LastChange=1758873482",
        "Ladeplatz_Usage[]=1",
        "Ladeplatz_Usage[0]=0",
        "Ladeplatz_Usage[1]=1",
        "SortConfirmTableCol=2",
        "SortConfirmTableDesc=1",
        "SortWheelsetSearchResultCol=11",
        "SortWheelsetSearchResultDesc=-1"
    ];
    
    $cookieString = implode('; ', $realCookies);
    debugLog("Verwende " . count($realCookies) . " echte Cookies");
    
    // Automatische Cookie-Validierung
    debugLog("--- Cookie-Validierung ---");
    $cookieValidationResult = validateAndUpdateCookies($baseUrl, $realCookies);
    if (!$cookieValidationResult['valid']) {
        debugLog(" Cookies ungültig - verwende aktualisierte Cookies");
        $realCookies = $cookieValidationResult['cookies'];
        $cookieString = implode('; ', $realCookies);
    }
    
    $ch = curl_init();
    
    // Optimierte cURL-Konfiguration mit echten Cookies
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_COOKIE, $cookieString);
    
    // Verwende die exakte URL-Struktur für die Suche
    $directSearchUrl = $baseUrl . "/resyweb/index.php?" . http_build_query([
        "FN" => "WheelsetSearch",
        "a" => "search",
        "m" => "wheelset",
        "LGS_ID" => $targetLgsId,
        "STATUS_ID" => "20",
        "button" => "submit"
    ]);
    
    debugLog("Direkte Such-URL: $directSearchUrl");
    
    curl_setopt($ch, CURLOPT_URL, $directSearchUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: de-DE,de;q=0.9,en;q=0.8',
        'Accept-Encoding: gzip, deflate, br, zstd',
        'Cache-Control: no-cache',
        'Pragma: no-cache',
        'Referer: ' . $baseUrl . '/resyweb/index.php'
    ]);
    
    $searchResponse = curl_exec($ch);
    $searchCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $searchFinalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    
    // Dekodiere gzip falls nötig
    if (substr($searchResponse, 0, 2) === "\x1f\x8b") {
        $searchResponse = gzdecode($searchResponse);
        debugLog("Gzip-komprimierte Antwort dekodiert");
    }
    
    debugLog("Suche: HTTP $searchCode, Final URL: $searchFinalUrl");
    debugLog("Content Length: " . strlen($searchResponse) . " Zeichen");
    
    // Analysiere die Antwort
    $hasWheelsetData = strpos($searchResponse, 'wheelset') !== false || 
                       strpos($searchResponse, 'Wheelset') !== false ||
                       strpos($searchResponse, 'WheelsetResult') !== false;
    $hasTargetLgsId = strpos($searchResponse, $targetLgsId) !== false;
    $hasLoginForm = strpos($searchResponse, 'Anmeldename') !== false || 
                    strpos($searchResponse, 'UserName') !== false;
    
    debugLog("=== ANALYSE DER SUCHE ===");
    debugLog("Enthält Wheelset-Daten: " . ($hasWheelsetData ? "Ja" : "Nein"));
    debugLog("Enthält Storage Number: " . ($hasTargetLgsId ? "Ja" : "Nein"));
    debugLog("Ist Login-Seite: " . ($hasLoginForm ? "Ja" : "Nein"));
    
    if ($hasWheelsetData && $hasTargetLgsId) {
        debugLog(" ERFOLG! Storage Number $targetLgsId gefunden!");
        return [
            'success' => true,
            'storage_number' => $targetLgsId,
            'status' => 'available',
            'found' => true
        ];
    } elseif ($hasLoginForm) {
        throw new Exception('Session ungültig - zur Login-Seite umgeleitet');
    } else {
        debugLog(" Storage Number nicht gefunden");
        return [
            'success' => false,
            'storage_number' => $targetLgsId,
            'message' => 'Storage Number nicht gefunden',
            'found' => false
        ];
    }
}

// Hauptverarbeitung
try {
    debugLog("=== TIRE STATUS CHECK API START ===");
    
    $rawInput = file_get_contents('php://input');
    debugLog("Raw Input: " . $rawInput);
    
    $data = json_decode($rawInput, true);
    if (!$data) {
        $data = ['storage_number' => $_POST['storage_number'] ?? $_GET['storage_number'] ?? ''];
    }
    
    $storageNumber = $data['storage_number'] ?? '';
    debugLog("Storage Number: '$storageNumber'");
    
    if (empty($storageNumber)) {
        throw new Exception('Storage Number ist erforderlich');
    }
    
    // Bereinige Storage Number (entferne Punkte)
    $cleanStorageNumber = str_replace('.', '', $storageNumber);
    debugLog("Clean Storage Number: $cleanStorageNumber");
    
    // Datenbankverbindung
    try {
        require_once __DIR__ . '/../config/database.php';
        $db = new Database();
        $conn = $db->getConnection();
        debugLog("Datenbankverbindung erfolgreich");
    } catch (Exception $e) {
        debugLog("Datenbankfehler: " . $e->getMessage());
        throw new Exception('Datenbankverbindung fehlgeschlagen: ' . $e->getMessage());
    }
    
    // Hole Autohaus-Info
    $autohausStmt = $conn->prepare("SELECT * FROM autohaus ORDER BY id LIMIT 1");
    $autohausStmt->execute();
    $autohaus = $autohausStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$autohaus) {
        throw new Exception("Kein Autohaus gefunden");
    }
    
    debugLog("Verwende Autohaus: " . $autohaus['id']);
    
    // Führe Suche mit bewährter Logik durch
    $result = searchWithRealSessionCookies($autohaus['resy_base_url'], $cleanStorageNumber);
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'storage_number' => $storageNumber,
            'status' => 'available',
            'found' => true,
            'autohaus_id' => $autohaus['id'],
            'method' => 'real_session_cookies'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'storage_number' => $storageNumber,
            'message' => "Storage Number '$storageNumber' nicht gefunden",
            'found' => false,
            'method' => 'real_session_cookies'
        ]);
    }
    
} catch (Exception $e) {
    debugLog("API-Fehler: " . $e->getMessage());
    debugLog("Stack Trace: " . $e->getTraceAsString());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Fehler beim Abrufen der Reifendaten: ' . $e->getMessage(),
        'debug' => [
            'file' => __FILE__,
            'line' => $e->getLine(),
            'timestamp' => date('Y-m-d H:i:s')
        ]
    ]);
}

debugLog("=== TIRE STATUS CHECK API END ===");
?>
