<?php
// sales/shop.php - Clothing Shop storefront for Admins (team-mania.de/shop)
require_once __DIR__ . '/config.php';

$checkout_error = '';

$products = [
    'hoodie' => ['name' => 'Team Mania PRO - Premium Vereins-Hoodie', 'price' => 39.90, 'desc' => 'Kuscheliger Hoodie mit Vereinswappen-Aufdruck (On-Demand-Druck)'],
    'jersey' => ['name' => 'Team Mania PRO - Offizielles Heimtrikot', 'price' => 29.90, 'desc' => 'Atmungsaktives Vereinstrikot mit Wunschnummer (On-Demand-Druck)'],
    'shorts' => ['name' => 'Team Mania PRO - Trainingsshorts', 'price' => 19.90, 'desc' => 'Robuste Trainingshose mit elastischem Bund (On-Demand-Druck)'],
    'socks'  => ['name' => 'Team Mania PRO - Sportsocken', 'price' => 9.90, 'desc' => 'Polstersocken mit Vereinsfarben (On-Demand-Druck)'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'buy_clothing') {
    $email = trim($_POST['email'] ?? '');
    $selected_items = $_POST['items'] ?? [];
    
    $line_items = [];
    $item_idx = 0;
    
    foreach ($selected_items as $p_key => $details) {
        $qty = intval($details['qty'] ?? 0);
        $size = $details['size'] ?? 'M';
        
        if ($qty > 0 && isset($products[$p_key])) {
            $price_cents = round($products[$p_key]['price'] * 100);
            
            $line_items["line_items[$item_idx][price_data][currency]"] = 'eur';
            $line_items["line_items[$item_idx][price_data][unit_amount]"] = $price_cents;
            $line_items["line_items[$item_idx][price_data][product_data][name]"] = $products[$p_key]['name'] . ' (' . $size . ')';
            $line_items["line_items[$item_idx][price_data][product_data][description]"] = $products[$p_key]['desc'];
            $line_items["line_items[$item_idx][quantity]"] = $qty;
            
            $item_idx++;
        }
    }

    if (empty($line_items)) {
        $checkout_error = 'Bitte wählen Sie mindestens ein Kleidungsstück aus.';
    } elseif (empty($email)) {
        $checkout_error = 'Bitte geben Sie Ihre E-Mail-Adresse ein.';
    } else {
        $success_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/success.php?session_id={CHECKOUT_SESSION_ID}';
        $cancel_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/shop.php';

        $post_fields = array_merge([
            'mode' => 'payment',
            'success_url' => $success_url,
            'cancel_url' => $cancel_url,
            'customer_email' => $email,
            'metadata[type]' => 'clothing_order',
            'metadata[email]' => $email
        ], $line_items);

        $ch = curl_init('https://api.stripe.com/v1/checkout/sessions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERPWD, STRIPE_SECRET_KEY . ':');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code === 200) {
            $session = json_decode($response, true);
            if (isset($session['url'])) {
                header("Location: " . $session['url']);
                exit;
            }
        }
        $checkout_error = 'Stripe-Verbindung fehlgeschlagen. Bitte überprüfen Sie Ihre API-Schlüssel.';
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vereinskleidung On-Demand Shop - Team Mania</title>
    <style>
        :root {
            --bg: #0f172a;
            --card: #1e293b;
            --primary: #0284c7;
            --primary-hover: #0369a1;
            --text: #f8fafc;
            --text-muted: #94a3b8;
            --border: #334155;
        }
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', system-ui, sans-serif;
        }
        body {
            background-color: var(--bg);
            color: var(--text);
            padding: 40px 20px;
        }
        .shop-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        h1 {
            font-size: 32px;
            font-weight: 800;
            text-align: center;
            color: var(--primary);
            margin-bottom: 5px;
        }
        .subtitle {
            text-align: center;
            color: var(--text-muted);
            font-size: 14px;
            margin-bottom: 40px;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }
        .product-card {
            background-color: var(--card);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .product-name {
            font-size: 16px;
            font-weight: 700;
            margin-bottom: 8px;
        }
        .product-desc {
            font-size: 12px;
            color: var(--text-muted);
            margin-bottom: 15px;
            line-height: 1.4;
        }
        .product-price {
            font-size: 20px;
            font-weight: 800;
            color: #fff;
            margin-bottom: 15px;
        }
        .selector-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 15px;
        }
        select, input[type="number"] {
            width: 100%;
            padding: 8px;
            background: #0f172a;
            border: 1px solid var(--border);
            border-radius: 4px;
            color: #fff;
            font-size: 12px;
        }
        .cart-card {
            background-color: var(--card);
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 30px;
            max-width: 500px;
            margin: 0 auto;
        }
        .btn {
            display: block;
            width: 100%;
            padding: 14px;
            background-color: var(--primary);
            color: #fff;
            border: none;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            text-align: center;
            transition: background-color 0.2s;
            margin-top: 15px;
        }
        .btn:hover {
            background-color: var(--primary-hover);
        }
        .alert {
            background-color: rgba(239, 68, 68, 0.1);
            border: 1px solid #ef4444;
            color: #fca5a5;
            padding: 12px;
            border-radius: 6px;
            font-size: 13px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="shop-container">
    <h1>Vereinskleidung On-Demand Shop</h1>
    <p class="subtitle">Bestellen Sie fertige Kollektionen für Ihren Verein im Sammelauftrag oder Einzelversand.</p>

    <?php if (!empty($checkout_error)): ?>
        <div class="alert"><?= htmlspecialchars($checkout_error) ?></div>
    <?php endif; ?>

    <form method="POST" action="">
        <input type="hidden" name="action" value="buy_clothing">

        <div class="grid">
            <?php foreach ($products as $key => $p): ?>
                <div class="product-card">
                    <div>
                        <div style="font-size: 32px; margin-bottom: 10px;">👕</div>
                        <h3 class="product-name"><?= htmlspecialchars($p['name']) ?></h3>
                        <p class="product-desc"><?= htmlspecialchars($p['desc']) ?></p>
                    </div>
                    <div>
                        <div class="product-price"><?= number_format($p['price'], 2, ',', '.') ?> €</div>
                        <div class="selector-row">
                            <div>
                                <label style="font-size: 10px; text-align: left; display: block;">Größe</label>
                                <select name="items[<?= $key ?>][size]">
                                    <option value="S">S</option>
                                    <option value="M" selected>M</option>
                                    <option value="L">L</option>
                                    <option value="XL">XL</option>
                                </select>
                            </div>
                            <div>
                                <label style="font-size: 10px; text-align: left; display: block;">Anzahl</label>
                                <input type="number" name="items[<?= $key ?>][qty]" min="0" value="0">
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="cart-card">
            <h3 style="font-size: 18px; font-weight: 700; margin-bottom: 15px; text-align: center;">Bestellung absenden</h3>
            <div class="form-group">
                <label for="email">E-Mail-Adresse für die Bestellbestätigung</label>
                <input type="email" id="email" name="email" placeholder="admin@tsv-musterstadt.de" required>
            </div>
            <button type="submit" class="btn">Zur Kasse & Bezahlen (Stripe)</button>
        </div>
    </form>
</div>

</body>
</html>
