<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$db = new Database();
$conn = $db->getConnection();

// Handle CSV import
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'import_csv') {
        try {
            if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('CSV-Datei konnte nicht hochgeladen werden');
            }
            
            $csvContent = file_get_contents($_FILES['csv_file']['tmp_name']);
            if (empty($csvContent)) {
                throw new Exception('CSV-Datei ist leer');
            }
            
            // API-Aufruf für CSV-Import
            $postData = http_build_query([
                'action' => 'import',
                'csv_content' => $csvContent
            ]);
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => 'http://localhost:8080/api/csv_import.php',
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $postData,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode !== 200) {
                throw new Exception('API-Fehler beim Import');
            }
            
            $result = json_decode($response, true);
            if ($result['success']) {
                $message = "✅ {$result['message']} ({$result['imported_count']} von {$result['total_rows']} Zeilen)";
                $messageType = 'success';
                
                if (!empty($result['errors'])) {
                    $message .= "<br><br>⚠️ Fehler:<br>" . implode('<br>', $result['errors']);
                    $messageType = 'warning';
                }
            } else {
                throw new Exception($result['error']);
            }
            
        } catch (Exception $e) {
            $message = "❌ Fehler beim Import: " . $e->getMessage();
            $messageType = 'error';
        }
    } elseif ($_POST['action'] === 'download_sample') {
        // Beispiel-CSV herunterladen
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'http://localhost:8080/api/csv_import.php',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query(['action' => 'sample']),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 200) {
            $result = json_decode($response, true);
            if ($result['success']) {
                header('Content-Type: text/csv; charset=utf-8');
                header('Content-Disposition: attachment; filename="resy_import_sample.csv"');
                echo $result['csv_content'];
                exit;
            }
        }
    }
}

// Get current user data
$current_user_id = $_SESSION['admin_user_id'] ?? null;
$current_user_name = 'Admin';
if ($current_user_id) {
    $stmt = $conn->prepare("SELECT full_name, username FROM admin_users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $current_user_name = $user_data['full_name'] ?? $user_data['username'] ?? 'Benutzer';
}

// Get import statistics
$stmt = $conn->prepare("
    SELECT 
        COUNT(*) as total_records,
        COUNT(DISTINCT einlagerungsnummer) as unique_storage_numbers,
        COUNT(DISTINCT kennzeichen) as unique_license_plates,
        MAX(created_at) as last_import
    FROM resy_tire_data
");
$stmt->execute();
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RESY Import - Boxxenstopp</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            color: #2c3e50;
            font-size: 2.5rem;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .header p {
            color: #7f8c8d;
            font-size: 1.1rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card i {
            font-size: 2.5rem;
            color: #3498db;
            margin-bottom: 15px;
        }

        .stat-card h3 {
            font-size: 2rem;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .stat-card p {
            color: #7f8c8d;
            font-size: 0.9rem;
        }

        .import-section {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .import-section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }

        .file-input-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .file-input {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-input-label {
            display: block;
            padding: 20px;
            border: 2px dashed #3498db;
            border-radius: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .file-input-label:hover {
            border-color: #2980b9;
            background: #e3f2fd;
        }

        .file-input-label i {
            font-size: 2rem;
            color: #3498db;
            margin-bottom: 10px;
        }

        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(52, 152, 219, 0.3);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
        }

        .btn-secondary:hover {
            box-shadow: 0 10px 20px rgba(149, 165, 166, 0.3);
        }

        .message {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .message.warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .help-section {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .help-section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
        }

        .help-section ul {
            list-style: none;
            padding: 0;
        }

        .help-section li {
            padding: 10px 0;
            border-bottom: 1px solid #ecf0f1;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .help-section li:last-child {
            border-bottom: none;
        }

        .help-section li i {
            color: #3498db;
            width: 20px;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #3498db;
            text-decoration: none;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .back-link:hover {
            color: #2980b9;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="index.php" class="back-link">
            <i class="fas fa-arrow-left"></i>
            Zurück zur Übersicht
        </a>

        <div class="header">
            <h1>
                <i class="fas fa-file-import"></i>
                RESY Import
            </h1>
            <p>Importieren Sie RESY-Daten aus CSV-Dateien für Offline-Zugriff</p>
        </div>

        <?php if ($message): ?>
            <div class="message <?php echo $messageType; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <div class="stats-grid">
            <div class="stat-card">
                <i class="fas fa-database"></i>
                <h3><?php echo number_format($stats['total_records']); ?></h3>
                <p>Gespeicherte Datensätze</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-tire"></i>
                <h3><?php echo number_format($stats['unique_storage_numbers']); ?></h3>
                <p>Einlagerungsnummern</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-car"></i>
                <h3><?php echo number_format($stats['unique_license_plates']); ?></h3>
                <p>Fahrzeuge</p>
            </div>
            <div class="stat-card">
                <i class="fas fa-clock"></i>
                <h3><?php echo $stats['last_import'] ? date('d.m.Y H:i', strtotime($stats['last_import'])) : 'Nie'; ?></h3>
                <p>Letzter Import</p>
            </div>
        </div>

        <div class="import-section">
            <h2>
                <i class="fas fa-upload"></i>
                CSV-Datei importieren
            </h2>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="import_csv">
                
                <div class="form-group">
                    <label for="csv_file">CSV-Datei auswählen:</label>
                    <div class="file-input-wrapper">
                        <input type="file" id="csv_file" name="csv_file" accept=".csv" class="file-input" required>
                        <label for="csv_file" class="file-input-label">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <div>CSV-Datei hier ablegen oder klicken zum Auswählen</div>
                            <small>Unterstützte Formate: .csv</small>
                        </label>
                    </div>
                </div>
                
                <button type="submit" class="btn">
                    <i class="fas fa-upload"></i>
                    Importieren
                </button>
            </form>
        </div>

        <div class="help-section">
            <h2>
                <i class="fas fa-question-circle"></i>
                Hilfe & Anleitung
            </h2>
            
            <ul>
                <li>
                    <i class="fas fa-download"></i>
                    <strong>Beispiel-CSV herunterladen:</strong> 
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="action" value="download_sample">
                        <button type="submit" class="btn btn-secondary" style="padding: 5px 15px; font-size: 0.9rem;">
                            <i class="fas fa-download"></i>
                            Sample CSV
                        </button>
                    </form>
                </li>
                <li>
                    <i class="fas fa-table"></i>
                    <strong>Erforderliche Spalten:</strong> Satznummer, Kennzeichen, FIN, Haltername, Eingangsdatum, Autohaus
                </li>
                <li>
                    <i class="fas fa-tire"></i>
                    <strong>Reifendaten:</strong> Optional - Reifenhersteller VL/VR/HL/HR, Reifenmodell, Profiltiefen, etc.
                </li>
                <li>
                    <i class="fas fa-calendar"></i>
                    <strong>Datum-Format:</strong> DD.MM.YYYY, YYYY-MM-DD, DD/MM/YYYY oder MM/DD/YYYY
                </li>
                <li>
                    <i class="fas fa-building"></i>
                    <strong>Autohaus:</strong> Muss mit den konfigurierten Autohäusern übereinstimmen
                </li>
                <li>
                    <i class="fas fa-sync"></i>
                    <strong>Offline-Zugriff:</strong> Importierte Daten werden für schnellen Offline-Zugriff gespeichert
                </li>
            </ul>
        </div>
    </div>

    <script>
        // File input styling
        document.getElementById('csv_file').addEventListener('change', function(e) {
            const label = document.querySelector('.file-input-label');
            const fileName = e.target.files[0]?.name || 'CSV-Datei hier ablegen oder klicken zum Auswählen';
            label.innerHTML = `
                <i class="fas fa-file-csv"></i>
                <div>${fileName}</div>
                <small>Unterstützte Formate: .csv</small>
            `;
        });

        // Drag and drop
        const fileInput = document.querySelector('.file-input-label');
        
        fileInput.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#2980b9';
            this.style.background = '#e3f2fd';
        });
        
        fileInput.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '#3498db';
            this.style.background = '#f8f9fa';
        });
        
        fileInput.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '#3498db';
            this.style.background = '#f8f9fa';
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                document.getElementById('csv_file').files = files;
                const fileName = files[0].name;
                this.innerHTML = `
                    <i class="fas fa-file-csv"></i>
                    <div>${fileName}</div>
                    <small>Unterstützte Formate: .csv</small>
                `;
            }
        });
    </script>
</body>
</html>
