<?php
/**
 * Professional Wheelsets API - Echte RESY-Integration
 * Lädt echte Daten aus dem RESY-System
 */

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

class ProfessionalWheelsetsAPI {
    private $autohausId;
    private $autohausName;
    private $dealerId;
    private $resyUsername;
    private $resyPassword;
    
    public function __construct($autohausId) {
        $this->autohausId = $autohausId;
        $this->loadAutohausData();
    }
    
    /**
     * Lädt Autohaus-Daten aus der Datenbank
     */
    private function loadAutohausData() {
        try {
            $pdo = getDatabaseConnection();
            $stmt = $pdo->prepare("SELECT name, resy_username, resy_password FROM autohaus WHERE id = ?");
            $stmt->execute([$this->autohausId]);
            $autohaus = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$autohaus) {
                throw new Exception("Autohaus nicht gefunden");
            }
            
            $this->autohausName = $autohaus['name'];
            $this->resyUsername = $autohaus['resy_username'];
            $this->resyPassword = $autohaus['resy_password'];
            $this->dealerId = $this->getResyKdId();
            
            error_log("Autohaus geladen: " . $this->autohausName . " (Dealer ID: " . $this->dealerId . ")");
            
        } catch (Exception $e) {
            error_log("Fehler beim Laden der Autohaus-Daten: " . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * Mappt Autohaus-Namen zu RESY Dealer IDs
     */
    private function getResyKdId() {
        $mapping = [
            'B & E Volvo Kiel' => '453',
            'B & E Volvo Norderstedt' => '452', 
            'B & E Volvo Glinde' => '454'
        ];
        
        return $mapping[$this->autohausName] ?? '453';
    }
    
    /**
     * Hauptfunktion: Lädt alle Reifensätze für ein Autohaus
     */
    public function getStoredWheelsets() {
        try {
            error_log("Starte RESY-Integration für Autohaus ID: " . $this->autohausId);
            
            // Schritt 1: Login ins RESY-System
            $loginResult = $this->loginToResy();
            if (!$loginResult['success']) {
                error_log("RESY-Login fehlgeschlagen: " . $loginResult['error']);
                return $this->getFallbackData('RESY-Login fehlgeschlagen: ' . $loginResult['error']);
            }
            
            // Schritt 2: Navigiere zur Suchseite
            $searchResult = $this->navigateToSearchPage();
            if (!$searchResult['success']) {
                error_log("Navigation zur Suchseite fehlgeschlagen: " . $searchResult['error']);
                return $this->getFallbackData('Navigation fehlgeschlagen: ' . $searchResult['error']);
            }
            
            // Schritt 3: Führe Suche durch
            $searchData = $this->performSearch();
            if (!$searchData['success']) {
                error_log("RESY-Suche fehlgeschlagen: " . $searchData['error']);
                return $this->getFallbackData('RESY-Suche fehlgeschlagen: ' . $searchData['error']);
            }
            
            // Schritt 4: Lade alle Reifensätze
            $wheelsets = $this->loadAllWheelsets($searchData['html']);
            if (empty($wheelsets)) {
                error_log("Keine Reifensätze aus RESY geladen");
                return $this->getFallbackData('Keine Reifensätze aus RESY geladen');
            }
            
            error_log("Erfolgreich " . count($wheelsets) . " Reifensätze aus RESY geladen");
            
            return [
                'success' => true,
                'wheelsets' => $wheelsets,
                'count' => count($wheelsets),
                'autohaus' => $this->autohausName,
                'autohaus_id' => $this->autohausId,
                'source' => 'RESY-System',
                'loaded_at' => date('Y-m-d H:i:s'),
                'error' => null
            ];
            
        } catch (Exception $e) {
            error_log("ProfessionalWheelsetsAPI Fehler: " . $e->getMessage());
            return $this->getFallbackData('Unerwarteter Fehler: ' . $e->getMessage());
        }
    }
    
    /**
     * Login ins RESY-System
     */
    private function loginToResy() {
        $ch = curl_init();
        
        // Schritt 1: Login-Seite laden
        curl_setopt($ch, CURLOPT_URL, 'https://resy.dtm-reifen.de/index.php?m=login&a=login');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIEJAR, sys_get_temp_dir() . '/resy_cookies_' . $this->autohausId . '.txt');
        curl_setopt($ch, CURLOPT_COOKIEFILE, sys_get_temp_dir() . '/resy_cookies_' . $this->autohausId . '.txt');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        ]);
        
        $response = curl_exec($ch);
        
        if (curl_error($ch)) {
            curl_close($ch);
            return ['success' => false, 'error' => 'Fehler beim Laden der Login-Seite: ' . curl_error($ch)];
        }
        
        // Schritt 2: Login-Daten senden
        $postData = http_build_query([
            'UserName' => $this->resyUsername,
            'Password' => $this->resyPassword,
            'button' => 'submit'
        ]);
        
        curl_setopt($ch, CURLOPT_URL, 'https://resy.dtm-reifen.de/index.php?m=login&a=login');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Content-Type: application/x-www-form-urlencoded',
            'Referer: https://resy.dtm-reifen.de/index.php?m=login&a=login'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        // Prüfe Login-Erfolg
        if (strpos($response, 'technisches Problem') !== false) {
            return ['success' => false, 'error' => 'Technisches Problem beim Login'];
        }
        
        if (strpos($response, 'Sätze / Rücklieferungen bestellen') !== false) {
            return ['success' => true];
        }
        
        return ['success' => false, 'error' => 'Login fehlgeschlagen - keine Erfolgs-Indikatoren gefunden'];
    }
    
    /**
     * Navigiert zur Suchseite
     */
    private function navigateToSearchPage() {
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, 'https://resy.dtm-reifen.de/index.php?m=wheelset&a=search');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIEFILE, sys_get_temp_dir() . '/resy_cookies_' . $this->autohausId . '.txt');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        if (curl_error($ch)) {
            return ['success' => false, 'error' => 'Fehler beim Laden der Suchseite: ' . curl_error($ch)];
        }
        
        return ['success' => true, 'html' => $response];
    }
    
    /**
     * Führt die Suche durch
     */
    private function performSearch() {
        $ch = curl_init();
        
        // Suche mit GET-Parameter
        $searchUrl = 'https://resy.dtm-reifen.de/index.php?m=wheelset&a=search&FN=WheelsetSearch&KD_ID=' . $this->dealerId . '&STATUS_ID=20';
        
        curl_setopt($ch, CURLOPT_URL, $searchUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIEFILE, sys_get_temp_dir() . '/resy_cookies_' . $this->autohausId . '.txt');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        if (curl_error($ch)) {
            return ['success' => false, 'error' => 'Fehler bei der Suche: ' . curl_error($ch)];
        }
        
        return ['success' => true, 'html' => $response];
    }
    
    /**
     * Lädt alle Reifensätze aus der RESY-HTML
     */
    private function loadAllWheelsets($html) {
        error_log("Starte Parsing der RESY-HTML");
        
        // Speichere HTML für Debugging
        file_put_contents(sys_get_temp_dir() . '/resy_response_' . $this->autohausId . '.html', $html);
        
        // Parse die HTML-Antwort
        $wheelsets = $this->parseWheelsetsFromHTML($html);
        
        error_log("Geparste " . count($wheelsets) . " Reifensätze aus HTML");
        
        return $wheelsets;
    }
    
    /**
     * Parst Reifensätze aus der RESY-HTML
     */
    private function parseWheelsetsFromHTML($html) {
        $wheelsets = [];
        
        // Suche nach der WheelsetSearchResult Tabelle
        if (preg_match('/<table[^>]*class="[^"]*WheelsetSearchResult[^"]*"[^>]*>(.*?)<\/table>/s', $html, $matches)) {
            $tableHtml = $matches[1];
            error_log("WheelsetSearchResult Tabelle gefunden");
            
            // Parse Tabellenzeilen
            if (preg_match_all('/<tr[^>]*>(.*?)<\/tr>/s', $tableHtml, $rowMatches)) {
                foreach ($rowMatches[1] as $index => $rowHtml) {
                    // Überspringe Header-Zeile
                    if ($index === 0) continue;
                    
                    // Parse Zellen
                    if (preg_match_all('/<td[^>]*>(.*?)<\/td>/s', $rowHtml, $cellMatches)) {
                        $cells = $cellMatches[1];
                        
                        // Mindestens 10 Zellen erwartet
                        if (count($cells) >= 10) {
                            $wheelset = $this->parseWheelsetRow($cells);
                            if ($wheelset) {
                                $wheelsets[] = $wheelset;
                            }
                        }
                    }
                }
            }
        } else {
            error_log("WheelsetSearchResult Tabelle nicht gefunden in HTML");
        }
        
        return $wheelsets;
    }
    
    /**
     * Parst eine einzelne Reifensatz-Zeile
     */
    private function parseWheelsetRow($cells) {
        try {
            // Bereinige Zellen-Inhalt
            $cleanCells = array_map(function($cell) {
                return trim(strip_tags($cell));
            }, $cells);
            
            // Validiere Satznummer (muss numerisch sein)
            $satznummer = $cleanCells[1] ?? '';
            if (!is_numeric(str_replace('.', '', $satznummer))) {
                return null; // Überspringe ungültige Zeilen
            }
            
            return [
                'satznummer' => $satznummer,
                'kennzeichen' => $cleanCells[2] ?? '',
                'fin' => $cleanCells[3] ?? '',
                'reifenmodell' => $cleanCells[4] ?? '',
                'autohaus' => $this->autohausName,
                'reifenart' => $cleanCells[5] ?? '',
                'saison' => $cleanCells[6] ?? '',
                'eingangsdatum' => $cleanCells[7] ?? '',
                'haltername' => $cleanCells[8] ?? '',
                'empfehlung' => $cleanCells[9] ?? '',
                'profiltiefe' => $cleanCells[10] ?? '',
                'status' => 'eingelagert',
                'autohaus_id' => $this->autohausId
            ];
            
        } catch (Exception $e) {
            error_log("Fehler beim Parsen der Reifensatz-Zeile: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Fallback-Daten wenn RESY-System nicht erreichbar ist
     */
    private function getFallbackData($error) {
        error_log("Verwende Fallback-Daten für Autohaus ID: " . $this->autohausId . " - " . $error);
        
        return [
            'success' => false,
            'wheelsets' => [],
            'count' => 0,
            'autohaus' => $this->autohausName,
            'autohaus_id' => $this->autohausId,
            'source' => 'Fallback',
            'loaded_at' => date('Y-m-d H:i:s'),
            'error' => $error
        ];
    }
}

// API-Handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $autohaus_id = $input['autohaus_id'] ?? null;
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $autohaus_id = $_GET['autohaus_id'] ?? null;
}

if (!$autohaus_id) {
    echo json_encode([
        'success' => false,
        'error' => 'Autohaus-ID ist erforderlich'
    ]);
    exit;
}

$api = new ProfessionalWheelsetsAPI($autohaus_id);
$result = $api->getStoredWheelsets();

echo json_encode($result);
?>
