<?php
// backpacks.php - Verwaltung der Rucksäcke
$page_title = "Rucksäcke";
require_once 'db_connect.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'header.php';

$user_id = $_SESSION['user_id'];
$message = '';

// Delete Action
if (isset($_POST['delete_backpack_id'])) {
    $delete_id = intval($_POST['delete_backpack_id']);
    // Check ownership
    $stmt = $conn->prepare("SELECT id FROM backpacks WHERE id = ? AND user_id = ?");
    $stmt->bind_param("ii", $delete_id, $user_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows > 0) {
        $stmt_del = $conn->prepare("DELETE FROM backpacks WHERE id = ?");
        $stmt_del->bind_param("i", $delete_id);
        if ($stmt_del->execute()) {
            $message = '<div class="alert alert-success">Rucksack gelöscht.</div>';
        } else {
            $message = '<div class="alert alert-danger">Fehler beim Löschen: ' . $conn->error . '</div>';
        }
    } else {
        $message = '<div class="alert alert-danger">Keine Berechtigung.</div>';
    }
}

// AUTO-MIGRATION: Check columns to prevent SQL errors
$check_col = $conn->query("SHOW COLUMNS FROM backpacks LIKE 'product_url'");
if ($check_col && $check_col->num_rows == 0) {
    $conn->query("ALTER TABLE backpacks ADD COLUMN product_url VARCHAR(255) DEFAULT NULL AFTER image_url");
}
$check_col_c = $conn->query("SHOW COLUMNS FROM backpack_compartments LIKE 'linked_article_id'");
if ($check_col_c && $check_col_c->num_rows == 0) {
    $conn->query("ALTER TABLE backpack_compartments ADD COLUMN linked_article_id INT DEFAULT NULL");
    $conn->query("ALTER TABLE backpack_compartments ADD CONSTRAINT fk_bc_article FOREIGN KEY (linked_article_id) REFERENCES articles(id) ON DELETE SET NULL");
}

// Fetch Backpacks (Personal + Household)
$household_id = null;
$stmt_hh = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_hh->bind_param("i", $user_id);
$stmt_hh->execute();
$res_hh = $stmt_hh->get_result();
if ($row = $res_hh->fetch_assoc()) {
    $household_id = $row['household_id'];
}

$backpacks = [];

$sql = "SELECT b.*, u.username as owner_name,
        (SELECT SUM(a.weight_grams) 
         FROM backpack_compartments bc 
         JOIN articles a ON bc.linked_article_id = a.id 
         WHERE bc.backpack_id = b.id) as extra_weight
        FROM backpacks b 
        JOIN users u ON b.user_id = u.id 
        WHERE b.user_id = ?";

if ($household_id) {
    $sql .= " OR (b.household_id = ?)";
}
$sql .= " ORDER BY b.name ASC";

$stmt = $conn->prepare($sql);
if ($household_id) {
    $stmt->bind_param("ii", $user_id, $household_id);
} else {
    $stmt->bind_param("i", $user_id);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $backpacks[] = $row;
}
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0"><i class="fas fa-hiking me-2"></i>Rucksäcke</h2>
        <a href="edit_backpack.php" class="btn btn-sm btn-outline-light"><i class="fas fa-plus me-2"></i>Neuen Rucksack anlegen</a>
    </div>
    <div class="card-body">
        <?php echo $message; ?>
        
        <?php if (empty($backpacks)): ?>
            <div class="alert alert-info text-center">
                Du hast noch keine Rucksäcke definiert. <a href="edit_backpack.php" class="alert-link">Lege jetzt deinen ersten Rucksack an!</a>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($backpacks as $bp): 
                    $total_bp_weight = $bp['weight_grams'] + ($bp['extra_weight'] ?? 0);
                ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-3">
                                    <h5 class="card-title mb-0"><?php echo htmlspecialchars($bp['name']); ?></h5>
                                    <?php if ($bp['user_id'] == $user_id): ?>
                                        <span class="badge bg-primary">Meiner</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">von <?php echo htmlspecialchars($bp['owner_name']); ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if(!empty($bp['image_url'])): ?>
                                    <div class="mb-3 text-center" style="height: 150px; overflow: hidden; background-color: #f8f9fa; border-radius: 5px; display: flex; align-items: center; justify-content: center;">
                                        <img src="<?php echo htmlspecialchars($bp['image_url']); ?>" alt="Rucksackbild" style="max-width: 100%; max-height: 100%; object-fit: contain;">
                                    </div>
                                <?php endif; ?>
                                
                                <p class="card-text text-muted small mb-2">
                                    <?php echo htmlspecialchars($bp['manufacturer'] . ' ' . $bp['model']); ?>
                                </p>
                                
                                <div class="d-flex justify-content-between mb-3">
                                    <span>
                                        <i class="fas fa-weight-hanging text-muted me-1"></i> 
                                        <?php echo $total_bp_weight; ?> g
                                        <?php if(($bp['extra_weight'] ?? 0) > 0): ?>
                                            <small class="text-muted" title="Basis: <?php echo $bp['weight_grams']; ?>g + Taschen: <?php echo $bp['extra_weight']; ?>g">(+<?php echo $bp['extra_weight']; ?>)</small>
                                        <?php endif; ?>
                                    </span>
                                    <span><i class="fas fa-box-open text-muted me-1"></i> <?php echo $bp['volume_liters']; ?> L</span>
                                </div>

                                <!-- Compartments Preview -->
                                <?php
                                $stmt_c = $conn->prepare("SELECT COUNT(*) as cnt FROM backpack_compartments WHERE backpack_id = ?");
                                $stmt_c->bind_param("i", $bp['id']);
                                $stmt_c->execute();
                                $cnt = $stmt_c->get_result()->fetch_assoc()['cnt'];
                                ?>
                                <p class="small text-muted"><i class="fas fa-layer-group me-1"></i> <?php echo $cnt; ?> Fächer definiert</p>

                            </div>
                            <div class="card-footer bg-transparent border-top-0 d-flex justify-content-between align-items-center gap-2">
                                <div>
                                    <?php if (!empty($bp['product_url'])): ?>
                                        <a href="<?php echo htmlspecialchars($bp['product_url']); ?>" target="_blank" class="btn btn-sm btn-outline-success" title="Herstellerseite öffnen"><i class="fas fa-external-link-alt"></i> Info</a>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="d-flex gap-1">
                                    <?php if ($bp['user_id'] == $user_id): ?>
                                        <a href="edit_backpack.php?id=<?php echo $bp['id']; ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i></a>
                                        <form method="post" onsubmit="return confirm('Rucksack wirklich löschen?');" class="d-inline">
                                            <input type="hidden" name="delete_backpack_id" value="<?php echo $bp['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                        </form>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-outline-secondary" disabled><i class="fas fa-lock"></i></button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php require_once 'footer.php'; ?>