<?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 form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action']) && $_POST['action'] === 'update_settings') {
            // Update settings
            $settings = [
                'price_wheel_change' => $_POST['price_wheel_change'],
                'price_storage' => $_POST['price_storage'],
                'price_wiper_blades' => $_POST['price_wiper_blades'],
                'price_spring_check' => $_POST['price_spring_check'],
                'price_winter_check' => $_POST['price_winter_check'],
                'company_name' => $_POST['company_name'],
                'company_phone' => $_POST['company_phone'],
                'company_email' => $_POST['company_email'],
                'company_address' => $_POST['company_address'],
            ];
            
            foreach ($settings as $key => $value) {
                $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
                $stmt->execute([$key, $value, $value]);
            }
            
            
            // Handle logo upload
            if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = '../assets/images/';
                $fileName = 'company-logo-' . time() . '.' . pathinfo($_FILES['company_logo']['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['company_logo']['tmp_name'], $uploadPath)) {
                    $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value) VALUES ('company_logo', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
                    $stmt->execute([$uploadPath, $uploadPath]);
                }
            }
            
            $_SESSION['success_message'] = 'Einstellungen erfolgreich gespeichert';
            header('Location: settings.php');
            exit;
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Fehler: ' . $e->getMessage();
    }
}

// Get current settings
$settings = [];
$stmt = $conn->prepare("SELECT setting_key, setting_value FROM settings");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Set defaults if not exists
$defaults = [
    'price_wheel_change' => '49.99',
    'price_storage' => '89.00',
    'price_wiper_blades' => 'auf_anfrage',
    'price_spring_check' => '39.00',
    'price_winter_check' => '39.00',
    'company_name' => 'Volvo Autohaus',
    'company_logo' => 'assets/images/volvo-logo.png',
    'company_phone' => '+49 123 456789',
    'company_email' => 'info@volvo-autohaus.de',
    'company_address' => 'Musterstraße 123, 12345 Musterstadt'
];

$settings = array_merge($defaults, $results);

?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Einstellungen - Boxenstop Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/volvo-theme.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="admin-body">
    <div class="admin-container">
        <!-- Sidebar -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <img src="../assets/images/volvo-logo.png" alt="Volvo" class="logo-img">
                <h2>Boxenstop Admin</h2>
            </div>
            
            <nav class="sidebar-nav">
                <a href="index.php" class="nav-item">
                    <i class="fas fa-tachometer-alt"></i>
                    <span>Dashboard</span>
                </a>
                <a href="events.php" class="nav-item">
                    <i class="fas fa-calendar-alt"></i>
                    <span>Events</span>
                </a>
                <a href="appointments.php" class="nav-item">
                    <i class="fas fa-calendar-check"></i>
                    <span>Termine</span>
                </a>
                <a href="storage.php" class="nav-item">
                    <i class="fas fa-warehouse"></i>
                    <span>Einlagerungen</span>
                </a>
                <a href="settings.php" class="nav-item active">
                    <i class="fas fa-cog"></i>
                    <span>Einstellungen</span>
                </a>
                <a href="logout.php" class="nav-item logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Abmelden</span>
                </a>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <!-- Header -->
            <header class="admin-header">
                <div class="header-content">
                    <h1><i class="fas fa-cog"></i> Einstellungen</h1>
                    <div class="header-actions">
                        <span class="admin-user">
                            <i class="fas fa-user-circle"></i>
                            <?php echo htmlspecialchars($_SESSION['admin_username'] ?? 'Admin'); ?>
                        </span>
                    </div>
                </div>
            </header>

            <!-- Content -->
            <div class="admin-content">

                <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                    </div>
                <?php endif; ?>

                <!-- Kategorien-Navigation -->
                <div class="settings-nav">
                    <button type="button" class="nav-btn active" data-section="preise">
                        <i class="fas fa-euro-sign"></i> Preise
                    </button>
                    <button type="button" class="nav-btn" data-section="company">
                        <i class="fas fa-building"></i> Unternehmen
                    </button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="settings-form">
                    <input type="hidden" name="action" value="update_settings">
                    
                    <!-- Preise -->
                    <div class="settings-section" id="preise">
                        <h2><i class="fas fa-euro-sign"></i> Preise</h2>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="price_wheel_change">Räderwechsel (€)</label>
                                <input type="number" id="price_wheel_change" name="price_wheel_change" 
                                       value="<?php echo htmlspecialchars($settings['price_wheel_change']); ?>" 
                                       step="0.01" min="0" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="price_storage">Einlagerung (€)</label>
                                <input type="number" id="price_storage" name="price_storage" 
                                       value="<?php echo htmlspecialchars($settings['price_storage']); ?>" 
                                       step="0.01" min="0" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="price_wiper_blades">Scheibenwischerblätter</label>
                                <input type="text" id="price_wiper_blades" name="price_wiper_blades" 
                                       value="<?php echo htmlspecialchars($settings['price_wiper_blades']); ?>" 
                                       placeholder="z.B. auf Anfrage oder 15,99">
                            </div>
                            
                            <div class="form-group">
                                <label for="price_spring_check">Frühjahres-Check (€)</label>
                                <input type="number" id="price_spring_check" name="price_spring_check" 
                                       value="<?php echo htmlspecialchars($settings['price_spring_check']); ?>" 
                                       step="0.01" min="0" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="price_winter_check">Winter-Check (€)</label>
                                <input type="number" id="price_winter_check" name="price_winter_check" 
                                       value="<?php echo htmlspecialchars($settings['price_winter_check']); ?>" 
                                       step="0.01" min="0" required>
                            </div>
                        </div>
                    </div>

                    <!-- Logo -->
                    <div class="settings-section">
                        <h2><i class="fas fa-image"></i> Logo</h2>
                        <div class="form-group">
                            <label for="company_logo">Logo hochladen</label>
                            <div class="logo-upload">
                                <div class="current-logo">
                                    <img src="../<?php echo htmlspecialchars($settings['company_logo']); ?>" 
                                         alt="Aktuelles Logo" id="logo-preview">
                                    <p>Aktuelles Logo</p>
                                </div>
                                <input type="file" id="company_logo" name="company_logo" 
                                       accept="image/*" onchange="previewLogo(this)">
                                <label for="company_logo" class="upload-btn">
                                    <i class="fas fa-upload"></i> Neues Logo auswählen
                                </label>
                            </div>
                        </div>
                    </div>

                        
                        <!-- SMTP Test Button -->
                        <div class="smtp-test-section">
                            <button type="button" id="test-smtp" class="btn btn-secondary">
                                <i class="fas fa-paper-plane"></i> SMTP-Verbindung testen
                            </button>
                            <a href="smtp_outlook_config.php" class="btn btn-primary">
                                <i class="fab fa-microsoft"></i> Outlook SMTP konfigurieren
                            </a>
                            <div id="smtp-test-result" class="test-result"></div>
                        </div>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="email_smtp_host">SMTP Server</label>
                                <input type="text" id="email_smtp_host" name="email_smtp_host" 
                                       value="<?php echo htmlspecialchars($settings['email_smtp_host'] ?? 'localhost'); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="email_smtp_port">SMTP Port</label>
                                <input type="number" id="email_smtp_port" name="email_smtp_port" 
                                       value="<?php echo htmlspecialchars($settings['email_smtp_port'] ?? '587'); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="email_smtp_username">SMTP Benutzername</label>
                                <input type="text" id="email_smtp_username" name="email_smtp_username" 
                                       value="<?php echo htmlspecialchars($settings['email_smtp_username'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="email_smtp_password">SMTP Passwort</label>
                                <input type="password" id="email_smtp_password" name="email_smtp_password" 
                                       value="<?php echo htmlspecialchars($settings['email_smtp_password'] ?? ''); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="email_from">Absender E-Mail</label>
                                <input type="email" id="email_from" name="email_from" 
                                       value="<?php echo htmlspecialchars($settings['email_from'] ?? 'noreply@boxenstop.de'); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="email_from_name">Absender Name</label>
                                <input type="text" id="email_from_name" name="email_from_name" 
                                       value="<?php echo htmlspecialchars($settings['email_from_name'] ?? 'Boxenstop'); ?>" required>
                            </div>
                        </div>
                    </div>

                    <!-- E-Mail-Templates -->
                    <div class="settings-section" id="email-templates">
                        <h2><i class="fas fa-file-text"></i> E-Mail-Templates</h2>
                        <div class="email-templates">
                            <?php
                            $templates = [
                                'appointment_confirmation' => 'Terminbestätigung',
                                'appointment_approved' => 'Termin genehmigt',
                                'appointment_reminder' => 'Erinnerung (1 Tag vorher)',
                                'appointment_rejected' => 'Termin abgelehnt'
                            ];
                            
                            foreach ($templates as $key => $title):
                                $template = getEmailTemplate($conn, $key);
                            ?>
                            <div class="template-group">
                                <h3><?php echo $title; ?></h3>
                                <div class="form-group">
                                    <label for="template_<?php echo $key; ?>_subject">Betreff</label>
                                    <input type="text" id="template_<?php echo $key; ?>_subject" 
                                           name="template_<?php echo $key; ?>_subject" 
                                           value="<?php echo htmlspecialchars($template['subject'] ?? ''); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label for="template_<?php echo $key; ?>_body">Nachricht</label>
                                    <textarea id="template_<?php echo $key; ?>_body" 
                                              name="template_<?php echo $key; ?>_body" 
                                              rows="8" required><?php echo htmlspecialchars($template['body'] ?? ''); ?></textarea>
                                    <small class="template-help">
                                        Verfügbare Platzhalter: {{customer_name}}, {{event_name}}, {{appointment_date}}, {{appointment_time}}, {{license_plate}}, {{services}}
                                    </small>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>


                    <!-- Server-Status -->
                    <div class="settings-section">
                        <h2><i class="fas fa-heartbeat"></i> Server-Status</h2>
                        <div class="server-status-grid">
                            <div class="status-card">
                                <div class="status-header">
                                    <i class="fas fa-server"></i>
                                    <h3>Server-Info</h3>
                                </div>
                                <div class="status-content">
                                    <div class="status-item">
                                        <span class="label">PHP Version:</span>
                                        <span class="value"><?php echo PHP_VERSION; ?></span>
                                    </div>
                                    <div class="status-item">
                                        <span class="label">Server Software:</span>
                                        <span class="value"><?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'Unbekannt'; ?></span>
                                    </div>
                                    <div class="status-item">
                                        <span class="label">Betriebssystem:</span>
                                        <span class="value"><?php echo PHP_OS; ?></span>
                                    </div>
                                    <div class="status-item">
                                        <span class="label">Speicher Limit:</span>
                                        <span class="value"><?php echo ini_get('memory_limit'); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="status-card">
                                <div class="status-header">
                                    <i class="fas fa-database"></i>
                                    <h3>Datenbank</h3>
                                </div>
                                <div class="status-content">
                                    <?php
                                    try {
                                        $db = new Database();
                                        $conn = $db->getConnection();
                                        $status = 'connected';
                                        $status_text = 'Verbunden';
                                        $status_class = 'success';
                                        
                                        // Test query
                                        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM events");
                                        $stmt->execute();
                                        $event_count = $stmt->fetch()['count'];
                                        
                                        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments");
                                        $stmt->execute();
                                        $appointment_count = $stmt->fetch()['count'];
                                        
                                    } catch (Exception $e) {
                                        $status = 'error';
                                        $status_text = 'Fehler: ' . $e->getMessage();
                                        $status_class = 'error';
                                        $event_count = 0;
                                        $appointment_count = 0;
                                    }
                                    ?>
                                    <div class="status-item">
                                        <span class="label">Status:</span>
                                        <span class="value status-<?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                    </div>
                                    <div class="status-item">
                                        <span class="label">Events:</span>
                                        <span class="value"><?php echo $event_count; ?></span>
                                    </div>
                                    <div class="status-item">
                                        <span class="label">Termine:</span>
                                        <span class="value"><?php echo $appointment_count; ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            
                        </div>
                    </div>


                    <!-- Unternehmensdaten -->
                    <div class="settings-section" id="company">
                        <h2><i class="fas fa-building"></i> Unternehmensdaten</h2>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="company_name">Firmenname</label>
                                <input type="text" id="company_name" name="company_name" 
                                       value="<?php echo htmlspecialchars($settings['company_name']); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="company_phone">Telefon</label>
                                <input type="tel" id="company_phone" name="company_phone" 
                                       value="<?php echo htmlspecialchars($settings['company_phone']); ?>" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="company_email">E-Mail</label>
                                <input type="email" id="company_email" name="company_email" 
                                       value="<?php echo htmlspecialchars($settings['company_email']); ?>" required>
                            </div>
                            
                            <div class="form-group full-width">
                                <label for="company_address">Adresse</label>
                                <textarea id="company_address" name="company_address" rows="3" required><?php echo htmlspecialchars($settings['company_address']); ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Einstellungen speichern
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <style>
        /* Kategorien-Navigation */
        .settings-nav {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        
        .nav-btn {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
            color: #666;
        }
        
        .nav-btn:hover {
            background: #e9ecef;
            border-color: #dee2e6;
        }
        
        .nav-btn.active {
            background: var(--volvo-blue);
            color: white;
            border-color: var(--volvo-blue);
        }
        
        .nav-btn i {
            font-size: 1rem;
        }
        
        /* Sektionen verstecken/zeigen */
        .settings-section {
            display: none;
        }
        
        .settings-section.active {
            display: block;
        }
        
        /* SMTP Test */
        .smtp-test-section {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            margin-bottom: 2rem;
        }
        
        .test-result {
            margin-top: 1rem;
            padding: 1rem;
            border-radius: 6px;
            display: none;
        }
        
        .test-result.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            display: block;
        }
        
        .test-result.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            display: block;
        }
        
        .test-result.loading {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
            display: block;
        }
        
        .email-templates {
            display: grid;
            gap: 2rem;
        }
        
        .template-group {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .template-group h3 {
            margin: 0 0 1rem 0;
            color: var(--volvo-blue);
            font-size: 1.1rem;
        }
        
        .template-help {
            color: #666;
            font-size: 0.85rem;
            margin-top: 0.5rem;
            font-style: italic;
        }
        
        .template-group textarea {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
        }
        
        .server-status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 1rem;
        }
        
        .status-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .status-header {
            background: #f8f9fa;
            padding: 1rem;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .status-header i {
            color: var(--volvo-blue);
            font-size: 1.2rem;
        }
        
        .status-header h3 {
            margin: 0;
            color: var(--volvo-blue);
            font-size: 1rem;
        }
        
        .status-content {
            padding: 1rem;
        }
        
        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f8f9fa;
        }
        
        .status-item:last-child {
            border-bottom: none;
        }
        
        .status-item .label {
            font-weight: 600;
            color: #666;
            font-size: 0.9rem;
        }
        
        .status-item .value {
            color: #333;
            font-size: 0.9rem;
            text-align: right;
            max-width: 60%;
            word-break: break-all;
        }
        
        .status-success {
            color: #28a745;
            font-weight: 600;
        }
        
        .status-error {
            color: #dc3545;
            font-weight: 600;
        }
        
        .status-warning {
            color: #ffc107;
            font-weight: 600;
        }
        
        .status-available {
            color: #17a2b8;
            font-weight: 600;
        }
        
        .text-muted {
            color: #6c757d;
            font-size: 0.85rem;
            margin-top: 0.25rem;
        }
        
        .form-grid .full-width {
            grid-column: 1 / -1;
        }
        
        @media (max-width: 768px) {
            .server-status-grid {
                grid-template-columns: 1fr;
            }
            
            .status-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.25rem;
            }
            
            .status-item .value {
                text-align: left;
                max-width: 100%;
            }
        }
    </style>

    <script>
        // Kategorien-Navigation
        document.addEventListener('DOMContentLoaded', function() {
            const navButtons = document.querySelectorAll('.nav-btn');
            const sections = document.querySelectorAll('.settings-section');
            
            // Erste Sektion aktivieren
            sections[0].classList.add('active');
            
            navButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const targetSection = this.getAttribute('data-section');
                    
                    // Alle Buttons deaktivieren
                    navButtons.forEach(btn => btn.classList.remove('active'));
                    // Aktuellen Button aktivieren
                    this.classList.add('active');
                    
                    // Alle Sektionen verstecken
                    sections.forEach(section => section.classList.remove('active'));
                    
                    // Ziel-Sektion zeigen
                    const targetElement = document.getElementById(targetSection);
                    if (targetElement) {
                        targetElement.classList.add('active');
                    }
                });
            });
        });
        
        // SMTP Test
        document.getElementById('test-smtp').addEventListener('click', function() {
            const resultDiv = document.getElementById('smtp-test-result');
            const button = this;
            
            // Loading state
            resultDiv.className = 'test-result loading';
            resultDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Teste SMTP-Verbindung...';
            button.disabled = true;
            
            // Test-E-Mail senden mit PHPMailer
            fetch('../api/test_smtp_phpmailer.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    smtp_host: document.getElementById('email_smtp_host').value,
                    smtp_port: document.getElementById('email_smtp_port').value,
                    smtp_username: document.getElementById('email_smtp_username').value,
                    smtp_password: document.getElementById('email_smtp_password').value,
                    from_email: document.getElementById('email_from').value,
                    from_name: document.getElementById('email_from_name').value
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    resultDiv.className = 'test-result success';
                    resultDiv.innerHTML = '<i class="fas fa-check-circle"></i> ' + data.message;
                } else {
                    resultDiv.className = 'test-result error';
                    resultDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + data.message;
                }
            })
            .catch(error => {
                resultDiv.className = 'test-result error';
                resultDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> Fehler: ' + error.message;
            })
            .finally(() => {
                button.disabled = false;
            });
        });
        
        function previewLogo(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('logo-preview').src = e.target.result;
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
