<?php
/**
 * RESY Tire Status Check API - Real Data Extraction
 * Basiert auf resy_data_extraction_breakthrough.php ohne Termin-Logik
 */

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);

require_once '../config/database.php';

// Debug-Logging-Funktion
function debugLog($message) {
    $logFile = __DIR__ . '/../logs/tire_status_real.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);
}

// Cache-Funktionen für Performance-Optimierung
function getCachedData($storageNumber) {
    global $conn;
    
    try {
        $sql = "SELECT vehicle_data, tire_data FROM resy_data_cache 
                WHERE einlagerungsnummer = ? 
                AND expires_at > NOW() 
                ORDER BY updated_at DESC LIMIT 1";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([$storageNumber]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            debugLog("Cache-Hit für Storage Number: $storageNumber");
            return [
                'vehicle_data' => json_decode($result['vehicle_data'], true),
                'tire_data' => json_decode($result['tire_data'], true)
            ];
        }
        
        debugLog("Cache-Miss für Storage Number: $storageNumber");
        return null;
        
    } catch (Exception $e) {
        debugLog("Cache-Fehler: " . $e->getMessage());
        return null;
    }
}

function saveCachedData($storageNumber, $vehicleData, $tireData) {
    global $conn;
    
    try {
        $sql = "INSERT INTO resy_data_cache (einlagerungsnummer, vehicle_data, tire_data, created_at, updated_at, expires_at) 
                VALUES (?, ?, ?, NOW(), NOW(), DATE_ADD(NOW(), INTERVAL 30 DAY))
                ON DUPLICATE KEY UPDATE 
                vehicle_data = VALUES(vehicle_data), 
                tire_data = VALUES(tire_data), 
                updated_at = NOW(),
                expires_at = DATE_ADD(NOW(), INTERVAL 30 DAY)";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            $storageNumber, 
            json_encode($vehicleData), 
            json_encode($tireData)
        ]);
        
        debugLog("Daten für Storage Number $storageNumber im Cache gespeichert");
        
    } catch (Exception $e) {
        debugLog("Cache-Speicher-Fehler: " . $e->getMessage());
    }
}

// HTTP Request Funktion
function httpRequest($url, $options = []) {
    $ch = curl_init();
    
    $defaultOptions = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        CURLOPT_HTTPHEADER => [
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language: de-DE,de;q=0.9,en;q=0.8',
            'Accept-Encoding: gzip, deflate',
            'Connection: keep-alive',
            'Upgrade-Insecure-Requests: 1'
        ]
    ];
    
    curl_setopt_array($ch, array_merge($defaultOptions, $options));
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    $curlInfo = curl_getinfo($ch);
    
    curl_close($ch);
    
    // Prüfe auf Timeout
    if ($curlInfo['total_time'] >= 10) {
        $error = 'Request timeout after 10 seconds';
    }
    
    return [
        'response' => $response,
        'http_code' => $httpCode,
        'error' => $error,
        'total_time' => $curlInfo['total_time']
    ];
}

// RESY Login Funktion
function performBreakthroughLogin($baseUrl, $username, $password) {
    $cookieFile = __DIR__ . '/../resy_cookies_tire_status_real.txt';
    
    try {
        debugLog("Versuche RESY Login für: $baseUrl");
        
        $loginData = [
            'username' => $username,
            'password' => $password
        ];
        
        $result = httpRequest($baseUrl . '/index.php?m=login', [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($loginData),
            CURLOPT_COOKIEJAR => $cookieFile,
            CURLOPT_COOKIEFILE => $cookieFile
        ]);
        
        debugLog("Login Response - HTTP Code: " . $result['http_code'] . ", Time: " . $result['total_time'] . "s");
        
        if ($result['error']) {
            debugLog("Login-Fehler: " . $result['error']);
            return ['success' => false, 'error' => 'Login fehlgeschlagen: ' . $result['error']];
        }
        
        if ($result['http_code'] !== 200) {
            debugLog("Login HTTP-Fehler: " . $result['http_code']);
            return ['success' => false, 'error' => 'Login HTTP-Fehler: ' . $result['http_code']];
        }
        
        if (empty($result['response'])) {
            debugLog("Login Response ist leer");
            return ['success' => false, 'error' => 'Login Response ist leer'];
        }
        
        // Prüfe, ob Login erfolgreich war
        if (strpos($result['response'], 'login') !== false && strpos($result['response'], 'password') !== false) {
            debugLog("Login fehlgeschlagen - Login-Seite zurückgegeben");
            return ['success' => false, 'error' => 'Login fehlgeschlagen - Ungültige Anmeldedaten'];
        }
        
        debugLog("RESY Login erfolgreich");
        return ['success' => true, 'message' => 'Login erfolgreich'];
        
    } catch (Exception $e) {
        debugLog("Login Exception: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// Suche Funktion mit verschiedenen LGS_ID-Formaten
function searchWithWorkingLgsIds($baseUrl, $targetLgsId) {
    $cookieFile = __DIR__ . '/../resy_cookies_tire_status_real.txt';
    
    try {
        debugLog("Suche nach LGS_ID: $targetLgsId");
        
        // Verschiedene Suchformate versuchen
        $searchTerms = [
            $targetLgsId,
            str_replace('.', '', $targetLgsId),
            str_replace('.', ' ', $targetLgsId),
            str_replace('.', '-', $targetLgsId)
        ];
        
        foreach ($searchTerms as $index => $term) {
            debugLog("Suche Versuch " . ($index + 1) . " mit Term: '$term'");
            
            $result = httpRequest($baseUrl . '/index.php?m=search&term=' . urlencode($term), [
                CURLOPT_COOKIEJAR => $cookieFile,
                CURLOPT_COOKIEFILE => $cookieFile
            ]);
            
            if ($result['error']) {
                debugLog("Suche-Fehler für Term '$term': " . $result['error']);
                continue;
            }
            
            if ($result['http_code'] !== 200) {
                debugLog("Suche HTTP-Fehler für Term '$term': " . $result['http_code']);
                continue;
            }
            
            // Prüfe verschiedene LGS_ID-Patterns
            $patterns = [
                '/lgs_id[^>]*>(\d+)/i',
                '/lgs_id["\']?\s*[:=]\s*["\']?(\d+)/i',
                '/lgs_id["\']?\s*=\s*["\']?(\d+)/i',
                '/lgs_id\s*:\s*(\d+)/i',
                '/lgs_id\s*=\s*(\d+)/i'
            ];
            
            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $result['response'], $matches)) {
                    $lgsId = $matches[1];
                    debugLog("LGS_ID gefunden mit Pattern '$pattern': $lgsId");
                    return ['success' => true, 'lgs_id' => $lgsId];
                }
            }
            
            // Zusätzliche Suche nach der ursprünglichen LGS_ID im HTML
            if (strpos($result['response'], $targetLgsId) !== false) {
                debugLog("Original LGS_ID '$targetLgsId' im HTML gefunden");
                return ['success' => true, 'lgs_id' => $targetLgsId];
            }
        }
        
        debugLog("Keine LGS_ID gefunden für: $targetLgsId");
        return ['success' => false, 'error' => 'Keine LGS_ID gefunden'];
        
    } catch (Exception $e) {
        debugLog("Suche Exception: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// Navigation zur Detailseite
function navigateToDetailPageBreakthrough($baseUrl, $lgsId) {
    $cookieFile = __DIR__ . '/../resy_cookies_tire_status_real.txt';
    
    try {
        debugLog("Navigiere zur Detailseite für LGS_ID: $lgsId");
        
        $result = httpRequest($baseUrl . '/index.php?m=detail&lgs_id=' . $lgsId, [
            CURLOPT_COOKIEJAR => $cookieFile,
            CURLOPT_COOKIEFILE => $cookieFile
        ]);
        
        if ($result['error']) {
            debugLog("Detail-Navigation-Fehler: " . $result['error']);
            return ['success' => false, 'error' => 'Navigation fehlgeschlagen: ' . $result['error']];
        }
        
        if ($result['http_code'] !== 200) {
            debugLog("Detail-Navigation HTTP-Fehler: " . $result['http_code']);
            return ['success' => false, 'error' => 'Navigation HTTP-Fehler: ' . $result['http_code']];
        }
        
        debugLog("Detailseite erfolgreich abgerufen");
        return ['success' => true, 'html' => $result['response']];
        
    } catch (Exception $e) {
        debugLog("Detail-Navigation Exception: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// HTML-Parsing für Reifendaten
function extractTireDataFromHtml($html, $resyBaseUrl = '', $appointmentId = '') {
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    
    $tireData = [];
    $positions = ['VL', 'VR', 'HL', 'HR'];
    
    debugLog("Extrahiere Reifendaten aus HTML");
    
    // Suche nach der WheelsetViewWheels Tabelle
    $tableRows = $xpath->query('//table[@id="WheelsetViewWheels"]//tbody/tr');
    
    if ($tableRows->length === 0) {
        debugLog("Keine WheelsetViewWheels Tabelle gefunden");
        return $tireData;
    }
    
    debugLog("Gefunden: " . $tableRows->length . " Reifen-Zeilen");
    
    foreach ($tableRows as $row) {
        $cells = $xpath->query('.//td', $row);
        if ($cells->length >= 14) {
            $position = trim($cells->item(0)->textContent);
            $size = trim($cells->item(1)->textContent);
            $loadIndex1 = trim($cells->item(2)->textContent);
            $loadIndex2 = trim($cells->item(3)->textContent);
            $speedIndex = trim($cells->item(4)->textContent);
            $brand = trim($cells->item(5)->textContent);
            $model = trim($cells->item(6)->textContent);
            $dot = trim($cells->item(8)->textContent);
            $type = trim($cells->item(11)->textContent);
            $condition = trim($cells->item(13)->textContent);
            
            // Bestimme den Zustand basierend auf CSS-Klasse und Text
            $rowClass = $row->getAttribute('class');
            $finalCondition = determineTireCondition($rowClass, $condition);
            
            if (in_array($position, $positions)) {
                $tireData[$position] = [
                    'brand' => $brand,
                    'model' => $model,
                    'size' => $size . ' ' . $loadIndex1 . $speedIndex,
                    'dot' => $dot,
                    'type' => $type,
                    'condition' => $finalCondition,
                    'load_index_1' => $loadIndex1,
                    'load_index_2' => $loadIndex2,
                    'speed_index' => $speedIndex
                ];
                
                debugLog("Reifen $position: $brand $model - $finalCondition");
            }
        }
    }
    
    debugLog("Extrahiert: " . count($tireData) . " Reifen");
    return $tireData;
}

// Bestimme den Reifenzustand
function determineTireCondition($rowClass, $conditionText) {
    $conditionLower = strtolower($conditionText);
    
    if (strpos($rowClass, 'WheelsGood') !== false || 
        strpos($conditionLower, 'keine fehler') !== false) {
        return 'keine Fehler';
    } elseif (strpos($rowClass, 'WheelsWarn') !== false || 
              strpos($rowClass, 'WheelsYellow') !== false ||
              strpos($conditionLower, 'leichte fehler') !== false ||
              strpos($conditionLower, 'warnung') !== false) {
        return 'leichte Fehler';
    } elseif (strpos($rowClass, 'WheelsBad') !== false || 
              strpos($conditionLower, 'austausch notwendig') !== false) {
        return 'Austausch notwendig';
    }
    
    return $conditionText ?: 'Unbekannt';
}

// Hauptfunktion für RESY-Extraktion
function extractTireDataFromResy($resyBaseUrl, $resyUsername, $resyPassword, $storageNumber) {
    try {
        debugLog("Starte RESY-Extraktion für Storage Number: $storageNumber");
        debugLog("RESY URL: $resyBaseUrl");
        debugLog("RESY Username: $resyUsername");
        
        // Login zu RESY
        debugLog("Versuche RESY Login...");
        $loginResult = performBreakthroughLogin($resyBaseUrl, $resyUsername, $resyPassword);
        if (!$loginResult['success']) {
            debugLog("RESY Login fehlgeschlagen: " . $loginResult['error']);
            throw new Exception('RESY Login fehlgeschlagen: ' . $loginResult['error']);
        }
        debugLog("RESY Login erfolgreich");
        
        // Suche nach der Einlagerungsnummer
        debugLog("Suche nach Einlagerungsnummer: $storageNumber");
        $searchResult = searchWithWorkingLgsIds($resyBaseUrl, $storageNumber);
        if (!$searchResult['success']) {
            debugLog("RESY Suche fehlgeschlagen: " . $searchResult['error']);
            throw new Exception('RESY Suche fehlgeschlagen: ' . $searchResult['error']);
        }
        
        $lgsId = $searchResult['lgs_id'];
        debugLog("Gefundene LGS_ID: $lgsId");
        
        // Navigiere zur Detailseite
        debugLog("Navigiere zur Detailseite...");
        $detailResult = navigateToDetailPageBreakthrough($resyBaseUrl, $lgsId);
        if (!$detailResult['success']) {
            debugLog("Navigation zur Detailseite fehlgeschlagen: " . $detailResult['error']);
            throw new Exception('Navigation zur Detailseite fehlgeschlagen: ' . $detailResult['error']);
        }
        
        $detailHtml = $detailResult['html'];
        debugLog("Detailseite erfolgreich abgerufen (Länge: " . strlen($detailHtml) . " Zeichen)");
        
        // Extrahiere Reifendaten
        debugLog("Extrahiere Reifendaten aus HTML...");
        $tireData = extractTireDataFromHtml($detailHtml, $resyBaseUrl, '');
        
        if (empty($tireData)) {
            debugLog("Keine Reifendaten in der HTML gefunden");
            throw new Exception('Keine Reifendaten in der HTML gefunden');
        }
        
        debugLog("RESY-Extraktion erfolgreich abgeschlossen - " . count($tireData) . " Reifen gefunden");
        return $tireData;
        
    } catch (Exception $e) {
        debugLog("RESY-Extraktion fehlgeschlagen: " . $e->getMessage());
        debugLog("Stack Trace: " . $e->getTraceAsString());
        return null;
    }
}

// Hauptlogik
try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Unterstütze sowohl POST als auch GET
    $rawInput = file_get_contents('php://input');
    $data = json_decode($rawInput, true);
    $storageNumber = $data['storage_number'] ?? $_POST['storage_number'] ?? $_GET['storage_number'] ?? '';
    
    debugLog("Tire Status Check für Storage Number: $storageNumber");
    debugLog("Raw input: " . $rawInput);
    debugLog("POST data: " . json_encode($_POST));
    debugLog("GET data: " . json_encode($_GET));
    
    if (empty($storageNumber)) {
        echo json_encode(['success' => false, 'error' => 'Einlagerungsnummer ist erforderlich.']);
        exit;
    }
    
    // Prüfe Cache zuerst
    $cachedData = getCachedData($storageNumber);
    if ($cachedData && !empty($cachedData['tire_data'])) {
        debugLog("Verwende gecachte Daten für Storage Number: $storageNumber");
        echo json_encode([
            'success' => true,
            'tire_data' => $cachedData['tire_data'],
            'source' => 'cache',
            'message' => 'Reifenzustand aus Cache abgerufen'
        ]);
        exit;
    }
    
    // Hole alle Autohäuser mit RESY-Konfiguration
    $stmt = $conn->prepare("
        SELECT id, resy_base_url, resy_username, resy_password
        FROM autohaus 
        WHERE resy_base_url IS NOT NULL 
        AND resy_username IS NOT NULL 
        AND resy_password IS NOT NULL
        AND resy_base_url != ''
        AND resy_username != ''
        AND resy_password != ''
    ");
    $stmt->execute();
    $autohäuser = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($autohäuser)) {
        echo json_encode(['success' => false, 'error' => 'Keine RESY-Konfiguration verfügbar.']);
        exit;
    }
    
    debugLog("Gefunden: " . count($autohäuser) . " Autohäuser mit RESY-Konfiguration");
    
    // Versuche bei jedem Autohaus
    foreach ($autohäuser as $autohaus) {
        debugLog("Versuche Autohaus ID: " . $autohaus['id']);
        
        try {
            $resyData = extractTireDataFromResy(
                $autohaus['resy_base_url'], 
                $autohaus['resy_username'], 
                $autohaus['resy_password'], 
                $storageNumber
            );
            
            if ($resyData && !empty($resyData)) {
                debugLog("Erfolgreich Daten von Autohaus " . $autohaus['id'] . " abgerufen");
                
                // Speichere die Daten im Cache
                saveCachedData($storageNumber, [], $resyData);
                
                echo json_encode([
                    'success' => true,
                    'tire_data' => $resyData,
                    'source' => 'resy',
                    'message' => 'Reifenzustand erfolgreich abgerufen'
                ]);
                exit;
            } else {
                debugLog("Autohaus " . $autohaus['id'] . " lieferte keine Reifendaten");
            }
        } catch (Exception $e) {
            debugLog("Fehler bei Autohaus " . $autohaus['id'] . ": " . $e->getMessage());
        }
    }
    
    // Keine RESY-Daten gefunden
    debugLog("Keine RESY-Daten von allen Autohäusern gefunden");
    echo json_encode([
        'success' => false,
        'error' => 'Keine Reifendaten für diese Einlagerungsnummer gefunden. Bitte überprüfen Sie die Einlagerungsnummer oder versuchen Sie es später erneut.'
    ]);
    
} catch (Exception $e) {
    debugLog("Fehler: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Fehler beim Abrufen der Reifendaten: ' . $e->getMessage()]);
}
?>
