<?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 beim Speichern: ' . $e->getMessage();
    }
}

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

$defaults = [
    'price_wheel_change' => '25.00',
    'price_storage' => '15.00',
    'price_wiper_blades' => '35.00',
    'price_spring_check' => '45.00',
    'price_winter_check' => '45.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">
                        <button type="submit" form="settings-form" class="btn btn-primary">
                            <i class="fas fa-save"></i> Speichern
                        </button>
                    </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; ?>

                <form method="POST" enctype="multipart/form-data" id="settings-form" class="settings-form">
                    <input type="hidden" name="action" value="update_settings">

                    <!-- Preise -->
                    <div class="settings-section">
                        <h2><i class="fas fa-euro-sign"></i> Preise</h2>
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="price_wheel_change">Reifenwechsel (€)</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">Scheibenwischer (€)</label>
                                <input type="number" id="price_wiper_blades" name="price_wiper_blades" 
                                       value="<?php echo htmlspecialchars($settings['price_wiper_blades']); ?>" 
                                       step="0.01" min="0" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="price_spring_check">Frühjahrscheck (€)</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">Wintercheck (€)</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>

                    <!-- Unternehmensdaten -->
                    <div class="settings-section">
                        <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 class="form-group">
                                <label for="company_logo">Firmenlogo</label>
                                <input type="file" id="company_logo" name="company_logo" accept="image/*">
                                <?php if ($settings['company_logo']): ?>
                                    <div class="current-logo">
                                        <img src="../<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Aktuelles Logo" style="max-width: 200px; margin-top: 10px;">
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <script src="../assets/js/main.js"></script>
    <script src="assets/js/admin.js"></script>
</body>
</html>
