<?php
// add_packing_list.php - Neue Packliste hinzufügen
// VALIDIERUNG: Verhindert doppelte Rucksack-Zuweisung (Server & Client)

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

require_once 'db_connect.php';
require_once 'household_actions.php';
require_once 'backpack_utils.php';
require_once 'packing_list_utils.php';

$current_user_id = $_SESSION['user_id'];
$message = '';
$name = '';
$description = '';

// Fetch data for UI (Household & Users)
$stmt_household = $conn->prepare("SELECT household_id FROM users WHERE id = ?");
$stmt_household->bind_param("i", $current_user_id);
$stmt_household->execute();
$household_id_for_user = $stmt_household->get_result()->fetch_assoc()['household_id'];
$stmt_household->close();

// Fetch available templates
$templates = [];
$sql_templates = "SELECT id, name FROM packing_lists WHERE is_template = 1 AND (user_id = ? OR household_id = ?)";
$stmt_templates = $conn->prepare($sql_templates);
// Falls household_id NULL ist, binden wir trotzdem User ID als Dummy oder handeln es anders.
// Einfacher: Wir nutzen current_user_id zweimal, wenn household NULL, oder Logik im SQL.
// Da household_id INT ist, kann es NULL sein.
// Besser:
$h_id = $household_id_for_user ?: 0; // 0 matches nothing usually, safe
$stmt_templates->bind_param("ii", $current_user_id, $h_id);
$stmt_templates->execute();
$res_templates = $stmt_templates->get_result();
while ($row = $res_templates->fetch_assoc()) {
    $templates[] = $row;
}
$stmt_templates->close();

// Fetch Users for Backpack Assignment UI
$available_users = [];
if ($household_id_for_user) {
    $stmt_u = $conn->prepare("SELECT id, username FROM users WHERE household_id = ?");
    $stmt_u->bind_param("i", $household_id_for_user);
} else {
    $stmt_u = $conn->prepare("SELECT id, username FROM users WHERE id = ?");
    $stmt_u->bind_param("i", $current_user_id);
}
$stmt_u->execute();
$res_u = $stmt_u->get_result();
while ($r = $res_u->fetch_assoc()) $available_users[] = $r;
$stmt_u->close();


// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
    $household_id = isset($_POST['is_household_list']) && $household_id_for_user ? $household_id_for_user : NULL;

    // Server-Side Validation for duplicate backpacks (ONLY if no template is selected)
    $has_duplicate_backpacks = false;
    
    if ($template_id == 0) {
        $selected_backpacks = [];
        if (isset($_POST['participate']) && is_array($_POST['participate'])) {
            foreach ($_POST['participate'] as $uid => $val) {
                if ($val) {
                    $bid = isset($_POST['backpacks'][$uid]) ? intval($_POST['backpacks'][$uid]) : 0;
                    if ($bid > 0) {
                        if (in_array($bid, $selected_backpacks)) {
                            $has_duplicate_backpacks = true;
                            break;
                        }
                        $selected_backpacks[] = $bid;
                    }
                }
            }
        }
    }

    if (empty($name)) {
        $message = '<div class="alert alert-danger" role="alert">Der Packlistenname darf nicht leer sein.</div>';
    } elseif ($has_duplicate_backpacks) {
        $message = '<div class="alert alert-danger" role="alert">Fehler: Ein Rucksack kann nicht mehreren Personen zugewiesen werden. Bitte korrigieren Sie die Auswahl.</div>';
    } else {
        $stmt = $conn->prepare("INSERT INTO packing_lists (user_id, household_id, name, description, is_template) VALUES (?, ?, ?, ?, 0)");
        if ($stmt === false) {
            $message .= '<div class="alert alert-danger" role="alert">SQL Prepare-Fehler: ' . $conn->error . '</div>';
        } else {
            $stmt->bind_param("isss", $current_user_id, $household_id, $name, $description);
            if ($stmt->execute()) {
                $new_list_id = $conn->insert_id;
                
                if ($template_id > 0) {
                    // Option A: Aus Template erstellen
                    try {
                        copyPackingListContent($template_id, $new_list_id, $conn);
                        $_SESSION['message'] = '<div class="alert alert-success" role="alert">Packliste erfolgreich aus Vorlage erstellt!</div>';
                    } catch (Exception $e) {
                         // Rollback oder Warnung? Wir lassen die Liste da, aber warnen.
                         $_SESSION['message'] = '<div class="alert alert-warning" role="alert">Liste erstellt, aber Fehler beim Kopieren der Vorlage: ' . $e->getMessage() . '</div>';
                    }

                } else {
                    // Option B: Leere Liste mit manuellen Trägern
                    if (isset($_POST['participate']) && is_array($_POST['participate'])) {
                        foreach ($_POST['participate'] as $uid => $val) {
                            $uid = intval($uid);
                            if ($val) {
                                $bid = isset($_POST['backpacks'][$uid]) ? intval($_POST['backpacks'][$uid]) : 0;
                                $bid_to_insert = ($bid > 0) ? $bid : NULL;
                                
                                $stmt_in = $conn->prepare("INSERT INTO packing_list_carriers (packing_list_id, user_id, backpack_id) VALUES (?, ?, ?)");
                                $stmt_in->bind_param("iii", $new_list_id, $uid, $bid_to_insert);
                                $stmt_in->execute();
                                $stmt_in->close();
                                
                                if ($bid > 0) {
                                    sync_backpack_items($conn, $new_list_id, $uid, $bid);
                                }
                            }
                        }
                    }
                    $_SESSION['message'] = '<div class="alert alert-success" role="alert">Packliste erfolgreich erstellt!</div>';
                }

                if ($household_id_for_user) {
                    $log_message = htmlspecialchars($_SESSION['username']) . " hat die Packliste '" . htmlspecialchars($name) . "' erstellt.";
                    log_household_action($conn, $household_id_for_user, $current_user_id, $log_message);
                }
                
                header("Location: manage_packing_list_items.php?id=" . $new_list_id);
                exit;
            } else {
                $message .= '<div class="alert alert-danger" role="alert">Fehler beim Hinzufügen der Packliste: ' . $stmt->error . '</div>';
            }
            $stmt->close();
        }
    }
}

require_once 'header.php';
?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="h4 mb-0"><i class="fas fa-plus-circle me-2"></i>Neue Packliste erstellen</h2>
         <a href="packing_lists.php" class="btn btn-sm btn-outline-light"><i class="fas fa-arrow-left me-2"></i>Zur Übersicht</a>
    </div>
    <div class="card-body p-4">
        <?php if(!empty($message)) echo $message; ?>

        <form action="add_packing_list.php" method="post" id="createListForm">
            <div class="row">
                <div class="col-md-7">
                    <div class="mb-3">
                        <label for="name" class="form-label"><i class="fas fa-file-signature me-2 text-muted"></i>Name der Packliste</label>
                        <input type="text" class="form-control" id="name" value="<?php echo htmlspecialchars($name); ?>" name="name" required>
                    </div>
                    
                    <!-- Template Selection -->
                    <div class="mb-3">
                        <label for="template_id" class="form-label"><i class="fas fa-copy me-2 text-muted"></i>Vorlage verwenden (Optional)</label>
                        <select class="form-select" id="template_id" name="template_id">
                            <option value="0" selected>Keine Vorlage (Leere Liste starten)</option>
                            <?php foreach ($templates as $tpl): ?>
                                <option value="<?php echo $tpl['id']; ?>">
                                    <?php echo htmlspecialchars($tpl['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">Wenn du eine Vorlage wählst, werden Artikel, Träger und Rucksäcke daraus übernommen.</div>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label"><i class="fas fa-align-left me-2 text-muted"></i>Beschreibung (optional)</label>
                        <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($description); ?></textarea>
                        <div class="form-text">Eine kurze Beschreibung, worum es bei dieser Packliste geht.</div>
                    </div>

                    <?php if ($household_id_for_user): ?>
                    <div class="form-check form-switch mb-4">
                        <input class="form-check-input" type="checkbox" role="switch" id="is_household_list" name="is_household_list" value="1" checked>
                        <label class="form-check-label" for="is_household_list">Für den gesamten Haushalt freigeben</label>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="col-md-5">
                    <h5 class="mb-3"><i class="fas fa-users me-2 text-muted"></i>Teilnehmer & Rucksäcke</h5>
                    <div id="participants-section">
                        <div class="card bg-light border-0">
                            <div class="card-body">
                                <p class="small text-muted">Wähle aus, wer mitkommt und wer welchen Rucksack trägt.</p>
                                <div id="backpack-warning" class="alert alert-warning d-none small p-2 mb-2">
                                    <i class="fas fa-exclamation-triangle me-1"></i> Achtung: Ein Rucksack wurde mehrfach ausgewählt!
                                </div>
                                
                                <?php 
                                $user_backpacks_json = [];
                                $all_assigned_backpack_ids = []; 

                                foreach ($available_users as $user): 
                                    $user_backpacks = get_available_backpacks_for_user($conn, $user['id'], $household_id_for_user);
                                    $current_bp_id = 0;
                                    
                                    $user_backpacks_json[$user['id']] = [
                                        'current_id' => $current_bp_id,
                                        'backpacks' => $user_backpacks
                                    ];
                                ?>
                                    <div class="mb-3 pb-3 border-bottom">
                                        <div class="form-check mb-2">
                                            <input class="form-check-input participation-check" type="checkbox" name="participate[<?php echo $user['id']; ?>]" value="1" checked id="part_<?php echo $user['id']; ?>">
                                            <label class="form-check-label fw-bold" for="part_<?php echo $user['id']; ?>">
                                                <?php echo htmlspecialchars($user['username']); ?>
                                            </label>
                                        </div>
                                        <div class="ms-4">
                                            <!-- Pass class for JS validation -->
                                            <?php echo render_backpack_card_selector($user, $current_bp_id, $user_backpacks); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <div id="template-notice" class="alert alert-info d-none">
                        <i class="fas fa-info-circle me-2"></i> Da eine Vorlage gewählt wurde, werden die Träger und Rucksäcke aus der Vorlage übernommen. Du kannst diese später in der Listenansicht bearbeiten.
                    </div>
                </div>
            </div>

            <hr>

            <div class="d-flex justify-content-between mt-4">
                <button type="submit" class="btn btn-primary" id="submitBtn"><i class="fas fa-plus-circle me-2"></i>Packliste erstellen</button>
                <a href="packing_lists.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-2"></i>Abbrechen</a>
            </div>
        </form>
    </div>
</div>

<!-- Custom Script for Validation & Template Logic -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('createListForm');
    const submitBtn = document.getElementById('submitBtn');
    const warning = document.getElementById('backpack-warning');
    const templateSelect = document.getElementById('template_id');
    const participantsSection = document.getElementById('participants-section');
    const templateNotice = document.getElementById('template-notice');
    
    // Toggle participants section based on template selection
    function toggleParticipants() {
        if (templateSelect.value !== "0") {
            participantsSection.classList.add('d-none');
            templateNotice.classList.remove('d-none');
            // Disable validation logic effectively by hiding warning
            warning.classList.add('d-none');
            submitBtn.disabled = false;
        } else {
            participantsSection.classList.remove('d-none');
            templateNotice.classList.add('d-none');
            validateBackpacks(); // Re-validate
        }
    }

    templateSelect.addEventListener('change', toggleParticipants);

    // Helper function to check duplicates
    function validateBackpacks() {
        if (templateSelect.value !== "0") return; // Skip if template is selected

        const selected = [];
        let hasDuplicate = false;
        
        // Find all hidden inputs that store the backpack ID
        const inputs = document.querySelectorAll('input[name^="backpacks["]');
        
        inputs.forEach(input => {
            const userIdMatch = input.name.match(/backpacks\[(\d+)\]/);
            if (userIdMatch) {
                const userId = userIdMatch[1];
                const partCheck = document.getElementById('part_' + userId);
                
                if (partCheck && partCheck.checked) {
                    const val = parseInt(input.value);
                    if (val > 0) {
                        if (selected.includes(val)) {
                            hasDuplicate = true;
                        }
                        selected.push(val);
                    }
                }
            }
        });
        
        if (hasDuplicate) {
            warning.classList.remove('d-none');
            submitBtn.disabled = true;
        } else {
            warning.classList.add('d-none');
            submitBtn.disabled = false;
        }
    }
    
    // Also listen to participation checkboxes
    document.querySelectorAll('.participation-check').forEach(chk => {
        chk.addEventListener('change', validateBackpacks);
    });
    
    document.body.addEventListener('hidden.bs.modal', function (event) {
        validateBackpacks();
    });

    // Initial check
    toggleParticipants();
});
</script>

<?php echo render_backpack_modal_script($user_backpacks_json, $all_assigned_backpack_ids); ?>
                                
<?php require_once 'footer.php'; ?>