<?php
// views/inventory.php - Material and clothing inventory control
require_once __DIR__ . '/../auth.php';
require_login();

$user = current_user();
$errors = [];
$success_msg = '';
$can_manage = can_manage_inventory();
$allow_requests = get_setting('allow_clothing_requests', '1') === '1';

// 1. Save Clothing Request (Member action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request_clothing' && $allow_requests) {
    $item_name = trim($_POST['item_name'] ?? '');
    $size = trim($_POST['size'] ?? '');

    if (empty($item_name) || empty($size)) {
        $errors[] = "Bitte Kleidungsstück und Größe auswählen.";
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO clothing_requests (user_id, item_name, size, status, payment_status) VALUES (:uid, :item, :size, 'requested', 'unpaid')");
            $stmt->execute([
                ':uid' => $user['id'],
                ':item' => $item_name,
                ':size' => $size
            ]);
            $success_msg = "Anforderung erfolgreich übermittelt!";
        } catch (PDOException $e) {
            $errors[] = "Fehler bei der Bestellung: " . $e->getMessage();
        }
    }
}

// 2. Manage Inventory Items (Add/Update - Manager action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_inventory' && $can_manage) {
    $name = trim($_POST['name'] ?? '');
    $category = $_POST['category'] ?? 'equipment';
    $total_qty = intval($_POST['total_qty'] ?? 0);
    $available_qty = intval($_POST['available_qty'] ?? 0);
    $sizes = trim($_POST['sizes'] ?? '');

    if (empty($name)) {
        $errors[] = "Name des Inventars darf nicht leer sein.";
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO inventory (name, category, total_qty, available_qty, sizes) VALUES (:name, :category, :total, :available, :sizes)");
            $stmt->execute([
                ':name' => $name,
                ':category' => $category,
                ':total' => $total_qty,
                ':available' => $available_qty,
                ':sizes' => $sizes
            ]);
            $success_msg = "Inventar-Eintrag erfolgreich hinzugefügt!";
        } catch (PDOException $e) {
            $errors[] = "Fehler beim Hinzufügen: " . $e->getMessage();
        }
    }
}

// 3. Update Request Status & Notify Member (Manager action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_request' && $can_manage) {
    $req_id = intval($_POST['request_id'] ?? 0);
    $status = $_POST['status'] ?? 'requested';
    $payment = $_POST['payment_status'] ?? 'unpaid';
    $send_alert = isset($_POST['send_alert']);

    if ($req_id > 0) {
        try {
            $pdo->beginTransaction();
            
            // Update request
            $stmt = $pdo->prepare("UPDATE clothing_requests SET status = :status, payment_status = :payment, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
            $stmt->execute([
                ':status' => $status,
                ':payment' => $payment,
                ':id' => $req_id
            ]);

            // Fetch request details for notification
            $stmt = $pdo->prepare("SELECT r.*, u.first_name, u.last_name FROM clothing_requests r JOIN users u ON r.user_id = u.id WHERE r.id = :id");
            $stmt->execute([':id' => $req_id]);
            $req_details = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($req_details && $send_alert) {
                $notif_title = "Kleidung & Ausrüstung Update";
                $notif_msg = "";
                
                if ($status === 'ready') {
                    $notif_msg = "Dein Kleidungsstück '" . $req_details['item_name'] . "' (Größe: " . $req_details['size'] . ") ist abholbereit!";
                } elseif ($status === 'ordered') {
                    $notif_msg = "Dein Kleidungsstück '" . $req_details['item_name'] . "' wurde bestellt.";
                } elseif ($status === 'delivered') {
                    $notif_msg = "Dein Kleidungsstück '" . $req_details['item_name'] . "' wurde dir übergeben.";
                }
                
                if ($payment === 'unpaid') {
                    $notif_msg .= " Bitte begleiche noch den offenen Betrag beim Kassenwart.";
                }

                if (!empty($notif_msg)) {
                    $stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message) VALUES (:uid, :title, :msg)");
                    $stmt->execute([
                        ':uid' => $req_details['user_id'],
                        ':title' => $notif_title,
                        ':msg' => $notif_msg
                    ]);
                }
            }

            $pdo->commit();
            $success_msg = "Bestellung aktualisiert und Benachrichtigung gesendet!";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = "Fehler beim Aktualisieren: " . $e->getMessage();
        }
    }
}

// 4. Delete Inventory Item (Manager action)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_inventory' && $can_manage) {
    $inv_id = intval($_POST['inventory_id'] ?? 0);
    if ($inv_id > 0) {
        $stmt = $pdo->prepare("DELETE FROM inventory WHERE id = :id");
        $stmt->execute([':id' => $inv_id]);
        $success_msg = "Inventar-Eintrag erfolgreich gelöscht!";
    }
}

// Fetch Inventory Lists
$equipment_stmt = $pdo->query("SELECT * FROM inventory WHERE category = 'equipment' ORDER BY name ASC");
$equipment = $equipment_stmt->fetchAll(PDO::FETCH_ASSOC);

$clothing_stmt = $pdo->query("SELECT * FROM inventory WHERE category = 'clothing' ORDER BY name ASC");
$clothing_stock = $clothing_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Requests
if ($can_manage) {
    // Managers see all requests
    $requests_stmt = $pdo->query("SELECT r.*, u.first_name, u.last_name, u.email FROM clothing_requests r JOIN users u ON r.user_id = u.id ORDER BY r.updated_at DESC");
    $requests = $requests_stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    // Members see only their own requests
    $requests_stmt = $pdo->prepare("SELECT * FROM clothing_requests WHERE user_id = :uid ORDER BY updated_at DESC");
    $requests_stmt->execute([':uid' => $user['id']]);
    $requests = $requests_stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
    <div>
        <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Inventar & Vereinskleidung</h1>
        <p style="color: var(--text-muted); font-size: 14px;">Materialbestände und Kleiderausgaben im Überblick</p>
    </div>
    <?php if ($can_manage): ?>
        <div style="display: flex; gap: 10px;">
            <a href="https://team-mania.de/shop" target="_blank" class="btn btn-primary btn-sm">👕 Vereinskleidung nachbestellen</a>
        </div>
    <?php endif; ?>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

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

<!-- Managers Section -->
<?php if ($can_manage): ?>
    <div class="grid" style="grid-template-columns: 2fr 1fr; gap: 24px; margin-bottom: 30px;">
        <!-- Clothing Requests Manager -->
        <div class="card">
            <h3 class="card-title">🧥 Kleiderbestellungen & Anforderungen</h3>
            <div class="table-responsive" style="margin-top: 15px;">
                <table>
                    <thead>
                        <tr>
                            <th>Mitglied</th>
                            <th>Kleidung</th>
                            <th>Größe</th>
                            <th>Status</th>
                            <th>Bezahlung</th>
                            <th>Aktionen</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($requests)): ?>
                            <?php foreach ($requests as $r): ?>
                                <tr>
                                    <td style="font-weight: 600;">
                                        <?= htmlspecialchars($r['first_name'] . ' ' . $r['last_name']) ?><br>
                                        <span style="font-size: 11px; color: var(--text-muted);"><?= htmlspecialchars($r['email']) ?></span>
                                    </td>
                                    <td><?= htmlspecialchars($r['item_name']) ?></td>
                                    <td><span style="font-family: monospace; font-weight: bold; background: #e2e8f0; padding: 2px 6px; border-radius: 4px;"><?= htmlspecialchars($r['size']) ?></span></td>
                                    <form method="POST" action="">
                                        <input type="hidden" name="action" value="update_request">
                                        <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                                        <td>
                                            <select name="status" style="padding: 4px; font-size: 12px;">
                                                <option value="requested" <?= $r['status'] === 'requested' ? 'selected' : '' ?>>Angefordert</option>
                                                <option value="ordered" <?= $r['status'] === 'ordered' ? 'selected' : '' ?>>Bestellt</option>
                                                <option value="ready" <?= $r['status'] === 'ready' ? 'selected' : '' ?>>Abholbereit</option>
                                                <option value="delivered" <?= $r['status'] === 'delivered' ? 'selected' : '' ?>>Ausgegeben</option>
                                            </select>
                                        </td>
                                        <td>
                                            <select name="payment_status" style="padding: 4px; font-size: 12px;">
                                                <option value="unpaid" <?= $r['payment_status'] === 'unpaid' ? 'selected' : '' ?>>Unbezahlt</option>
                                                <option value="paid" <?= $r['payment_status'] === 'paid' ? 'selected' : '' ?>>Bezahlt</option>
                                                <option value="n/a" <?= $r['payment_status'] === 'n/a' ? 'selected' : '' ?>>Kostenlos</option>
                                            </select>
                                        </td>
                                        <td>
                                            <div style="display: flex; gap: 5px; align-items: center;">
                                                <button type="submit" class="btn btn-secondary btn-sm" style="padding: 4px 8px; font-size: 11px;">Speichern</button>
                                                <label style="font-size: 11px; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 0;">
                                                    <input type="checkbox" name="send_alert" value="1" checked> Notif. senden
                                                </label>
                                            </div>
                                        </td>
                                    </form>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 35px;">Keine Anforderungen vorhanden.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Inventory Creator Form -->
        <div class="card">
            <h3 class="card-title">➕ Inventar-Eintrag anlegen</h3>
            <form method="POST" action="" style="margin-top: 15px;">
                <input type="hidden" name="action" value="add_inventory">
                
                <div class="form-group">
                    <label for="inv_name">Artikelname</label>
                    <input type="text" id="inv_name" name="name" placeholder="z. B. Trainingsball Derbystar" required>
                </div>

                <div class="form-group">
                    <label for="inv_cat">Kategorie</label>
                    <select id="inv_cat" name="category">
                        <option value="equipment">Material / Trainingsgerät (Bälle, Tore...)</option>
                        <option value="clothing">Kleidungsstück (Trikot, Hütchen...)</option>
                    </select>
                </div>

                <div class="grid" style="grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 0;">
                    <div class="form-group">
                        <label for="tot_qty">Gesamtbestand</label>
                        <input type="number" id="tot_qty" name="total_qty" value="10" min="0" required>
                    </div>
                    <div class="form-group">
                        <label for="av_qty">Verfügbar</label>
                        <input type="number" id="av_qty" name="available_qty" value="10" min="0" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="sizes">Verfügbare Größen (Für Kleidung)</label>
                    <input type="text" id="sizes" name="sizes" placeholder="S, M, L, XL oder Einheitsgröße">
                </div>

                <button type="submit" class="btn btn-primary btn-sm" style="width: 100%; margin-top: 10px;">Artikel eintragen</button>
            </form>
        </div>
    </div>
<?php endif; ?>

<!-- Members & Public Section -->
<div class="grid">
    <!-- Equipment List -->
    <div class="card">
        <h3 class="card-title">⚽ Vereinsmaterial & Trainingsgerät</h3>
        <div class="table-responsive" style="margin-top: 15px;">
            <table>
                <thead>
                    <tr>
                        <th>Gegenstand</th>
                        <th>Gesamtbestand</th>
                        <th>Verfügbar</th>
                        <?php if ($can_manage): ?><th>Aktionen</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($equipment)): ?>
                        <?php foreach ($equipment as $eq): ?>
                            <tr>
                                <td style="font-weight: 600;"><?= htmlspecialchars($eq['name']) ?></td>
                                <td><?= intval($eq['total_qty']) ?> Stk.</td>
                                <td>
                                    <span style="font-weight: 600; color: <?= intval($eq['available_qty']) > 2 ? 'var(--success)' : 'var(--danger)' ?>;">
                                        <?= intval($eq['available_qty']) ?> Stk.
                                    </span>
                                </td>
                                <?php if ($can_manage): ?>
                                    <td>
                                        <form method="POST" action="" onsubmit="return confirm('Möchten Sie diesen Eintrag löschen?')">
                                            <input type="hidden" name="action" value="delete_inventory">
                                            <input type="hidden" name="inventory_id" value="<?= $eq['id'] ?>">
                                            <button type="submit" class="btn btn-danger btn-sm" style="padding: 2px 6px; font-size: 11px;">Löschen</button>
                                        </form>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 25px;">Keine Materialien registriert.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Clothing List & Ordering -->
    <div class="card">
        <h3 class="card-title">👕 Vereinskleidung (Bestellbare Ware)</h3>
        
        <?php if (!$can_manage): ?>
            <!-- Regular Member: Request Clothing Form -->
            <?php if ($allow_requests): ?>
                <form method="POST" action="" style="margin-top: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 20px; margin-bottom: 20px;">
                    <input type="hidden" name="action" value="request_clothing">
                    
                    <div class="form-group">
                        <label for="req_item">Kleidungsstück wählen</label>
                        <select id="req_item" name="item_name" required>
                            <option value="">-- Kleidung wählen --</option>
                            <?php foreach ($clothing_stock as $cs): ?>
                                <option value="<?= htmlspecialchars($cs['name']) ?>"><?= htmlspecialchars($cs['name']) ?> (Größen: <?= htmlspecialchars($cs['sizes']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="req_size">Deine Wunschgröße</label>
                        <select id="req_size" name="size" required>
                            <option value="XS">XS</option>
                            <option value="S">S</option>
                            <option value="M">M</option>
                            <option value="L">L</option>
                            <option value="XL">XL</option>
                            <option value="XXL">XXL</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary btn-sm" style="width: 100%;">Kleidungsstück anfordern</button>
                </form>
            <?php else: ?>
                <div class="alert alert-danger" style="margin-top: 15px; font-size: 13px;">
                    ℹ️ Der Online-Bestellservice für Kleidung ist derzeit vom Verein deaktiviert worden.
                </div>
            <?php endif; ?>

            <!-- Member: View their own request history -->
            <h4 style="font-size: 14px; font-weight: 700; margin-top: 20px; color: var(--secondary);">Meine Anforderungen</h4>
            <div class="table-responsive" style="margin-top: 10px;">
                <table>
                    <thead>
                        <tr>
                            <th>Kleidung</th>
                            <th>Größe</th>
                            <th>Status</th>
                            <th>Zahlung</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($requests)): ?>
                            <?php foreach ($requests as $r): 
                                $status_labels = [
                                    'requested' => 'Angefordert',
                                    'ordered' => 'Bestellt',
                                    'ready' => 'Abholbereit 🎁',
                                    'delivered' => 'Ausgegeben'
                                ];
                                $pay_labels = [
                                    'unpaid' => 'Unbezahlt ❌',
                                    'paid' => 'Bezahlt ✅',
                                    'n/a' => 'Kostenfrei'
                                ];
                            ?>
                                <tr>
                                    <td style="font-weight: 600;"><?= htmlspecialchars($r['item_name']) ?></td>
                                    <td><span style="font-family: monospace;"><?= htmlspecialchars($r['size']) ?></span></td>
                                    <td><strong><?= $status_labels[$r['status']] ?? $r['status'] ?></strong></td>
                                    <td><?= $pay_labels[$r['payment_status']] ?? $r['payment_status'] ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 15px; font-size: 13px;">Noch keine Bestellungen aufgegeben.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <!-- Manager: View stock levels -->
            <div class="table-responsive" style="margin-top: 15px;">
                <table>
                    <thead>
                        <tr>
                            <th>Bezeichnung</th>
                            <th>Größen</th>
                            <th>Bestand</th>
                            <th>Aktionen</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($clothing_stock)): ?>
                            <?php foreach ($clothing_stock as $cs): ?>
                                <tr>
                                    <td style="font-weight: 600;"><?= htmlspecialchars($cs['name']) ?></td>
                                    <td><span style="font-size: 13px; color: var(--text-muted);"><?= htmlspecialchars($cs['sizes']) ?></span></td>
                                    <td><?= intval($cs['total_qty']) ?> Stk.</td>
                                    <td>
                                        <form method="POST" action="" onsubmit="return confirm('Möchten Sie diesen Artikel löschen?')">
                                            <input type="hidden" name="action" value="delete_inventory">
                                            <input type="hidden" name="inventory_id" value="<?= $cs['id'] ?>">
                                            <button type="submit" class="btn btn-danger btn-sm" style="padding: 2px 6px; font-size: 11px;">Löschen</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 25px;">Keine Kleidungsstücke auf Lager.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>
