<?php
$title = isset($order) ? 'Edytuj Zamówienie Tortu' : 'Nowe Zamówienie Tortu';
ob_start();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-birthday-cake me-2"></i><?= $title ?></h2>
    <a href="<?= url('cake-orders') ?>" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-1"></i>Powrót
    </a>
</div>

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

<form method="POST" action="<?= isset($order) ? url('cake-orders/edit/' . $order['id']) : url('cake-orders/create') ?>" enctype="multipart/form-data" id="cakeOrderForm">
    <div class="row">
        <!-- Left Column -->
        <div class="col-lg-8">
            <!-- Customer Details -->
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-user me-2"></i>Dane Klienta</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Klient *</label>
                            <select name="customer_id" id="customerSelect" class="form-select select2" required>
                                <option value="">-- wybierz klienta --</option>
                                <?php foreach($customers as $customer): ?>
                                    <option value="<?= $customer['id'] ?>" 
                                        data-phone="<?= htmlspecialchars($customer['phone']) ?>"
                                        data-email="<?= htmlspecialchars($customer['email']) ?>"
                                        <?= isset($order) && $order['customer_id'] == $customer['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($customer['name']) ?> - <?= htmlspecialchars($customer['phone']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Lub <a href="<?= url('customers/create') ?>" target="_blank">dodaj nowego klienta</a></small>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Telefon</label>
                            <input type="tel" id="customerPhone" class="form-control" readonly>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" id="customerEmail" class="form-control" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pickup/Delivery Details -->
            <div class="card mb-4">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0"><i class="fas fa-map-marker-alt me-2"></i>Odbiór / Dostawa</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Miejsce odbioru *</label>
                            <select name="pickup_location_id" id="pickupLocation" class="form-select" required>
                                <option value="">-- wybierz --</option>
                                <?php foreach($locations as $location): ?>
                                    <option value="<?= $location['id'] ?>" 
                                        <?= isset($order) && $order['pickup_location_id'] == $location['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($location['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Data odbioru *</label>
                            <input type="date" name="pickup_date" class="form-control" required 
                                value="<?= $order['pickup_date'] ?? '' ?>" 
                                min="<?= date('Y-m-d') ?>">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Godzina odbioru *</label>
                            <select name="pickup_time" class="form-select" required>
                                <option value="">-- wybierz --</option>
                                <?php 
                                for($h=7; $h<=18; $h++) {
                                    foreach(['00','30'] as $m) {
                                        $time = sprintf('%02d:%s', $h, $m);
                                        $selected = (isset($order) && $order['pickup_time'] == $time) ? 'selected' : '';
                                        echo "<option value='$time' $selected>$time</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    
                    <div id="deliveryAddress" style="display:none;">
                        <hr>
                        <h6 class="text-info">Adres dostawy</h6>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Pełny adres dostawy</label>
                                <textarea name="delivery_address" class="form-control" rows="2" 
                                    placeholder="Ulica, Numer, Kod pocztowy, Miasto"><?= $cakeDetails['delivery_address'] ?? $order['delivery_address'] ?? '' ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Cake Details -->
            <div class="card mb-4">
                <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                    <h5 class="mb-0"><i class="fas fa-birthday-cake me-2"></i>Szczegóły Tortu</h5>
                </div>
                <div class="card-body">
                    <!-- Flavor -->
                    <div class="mb-3">
                        <label class="form-label">Smak *</label>
                        <select name="flavor_id" id="flavorSelect" class="form-select" required>
                            <option value="">-- wybierz smak --</option>
                            <?php foreach($flavors as $flavor): ?>
                                <option value="<?= $flavor['id'] ?>" 
                                    <?= isset($cakeDetails) && $cakeDetails['flavor_id'] == $flavor['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($flavor['name']) ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="custom" <?= isset($cakeDetails) && $cakeDetails['flavor_id'] === null && !empty($cakeDetails['flavor_custom']) ? 'selected' : '' ?>>
                                Inny smak (wpisz poniżej)
                            </option>
                        </select>
                    </div>
                    <div class="mb-3" id="customFlavorDiv" style="display:none;">
                        <label class="form-label">Wpisz własny smak</label>
                        <input type="text" name="flavor_custom" class="form-control" 
                            value="<?= $cakeDetails['flavor_custom'] ?? '' ?>" 
                            placeholder="np. Czekoladowo-malinowy">
                    </div>

                    <!-- Size -->
                    <div class="mb-3">
                        <label class="form-label">Rozmiar *</label>
                        <select name="size_id" id="sizeSelect" class="form-select" required>
                            <option value="">-- wybierz rozmiar --</option>
                            <?php foreach($sizes as $size): ?>
                                <option value="<?= $size['id'] ?>" 
                                    <?= isset($cakeDetails) && $cakeDetails['size_id'] == $size['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($size['name']) ?>
                                </option>
                            <?php endforeach; ?>
                            <option value="custom" <?= isset($cakeDetails) && $cakeDetails['size_id'] === null && !empty($cakeDetails['size_custom']) ? 'selected' : '' ?>>
                                Inny rozmiar (wpisz poniżej)
                            </option>
                        </select>
                    </div>
                    <div class="mb-3" id="customSizeDiv" style="display:none;">
                        <label class="form-label">Wpisz własny rozmiar</label>
                        <input type="text" name="size_custom" class="form-control" 
                            value="<?= $cakeDetails['size_custom'] ?? '' ?>" 
                            placeholder="np. 30x40 cm">
                    </div>

                    <!-- Type -->
                    <div class="mb-3">
                        <label class="form-label">Rodzaj tortu</label>
                        <div class="row">
                            <?php 
                            $selectedTypes = isset($cakeDetails) && $cakeDetails['cake_type_ids'] ? 
                                explode(',', $cakeDetails['cake_type_ids']) : [];
                            foreach($types as $type): 
                            ?>
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="cake_types[]" 
                                            value="<?= $type['id'] ?>" id="type<?= $type['id'] ?>"
                                            <?= in_array($type['id'], $selectedTypes) ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="type<?= $type['id'] ?>">
                                            <?= htmlspecialchars($type['name']) ?>
                                        </label>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Inny rodzaj (jeśli nie ma na liście)</label>
                        <input type="text" name="cake_type_custom" class="form-control" 
                            value="<?= $cakeDetails['cake_type_custom'] ?? '' ?>" 
                            placeholder="np. Tort komunijny">
                    </div>
                </div>
            </div>

            <!-- Decorations -->
            <div class="card mb-4">
                <div class="card-header bg-warning">
                    <h5 class="mb-0"><i class="fas fa-star me-2"></i>Dodatki i Dekoracje</h5>
                </div>
                <div class="card-body">
                    <!-- Inscription -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_inscription" value="1" 
                                id="hasInscription" <?= isset($cakeDetails) && $cakeDetails['has_inscription'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasInscription">
                                Napis na torcie
                            </label>
                        </div>
                        <div id="inscriptionDiv" style="display:none;" class="mt-2">
                            <input type="text" name="inscription_text" class="form-control" 
                                value="<?= $cakeDetails['inscription_text'] ?? '' ?>" 
                                placeholder="Treść napisu">
                        </div>
                    </div>

                    <!-- Candles -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_candles" value="1" 
                                id="hasCandles" <?= isset($cakeDetails) && $cakeDetails['has_candles'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasCandles">
                                Świeczki
                            </label>
                        </div>
                        <div id="candlesDiv" style="display:none;" class="mt-2">
                            <label class="form-label">Liczba świeczek</label>
                            <input type="number" name="candles_count" class="form-control" min="0" 
                                value="<?= $cakeDetails['candles_count'] ?? 0 ?>">
                        </div>
                    </div>

                    <!-- Number Candle -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_number_candle" value="1" 
                                id="hasNumberCandle" <?= isset($cakeDetails) && $cakeDetails['has_number_candle'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasNumberCandle">
                                Świeczka cyferka
                            </label>
                        </div>
                        <div id="numberCandleDiv" style="display:none;" class="mt-2">
                            <input type="text" name="number_candle_value" class="form-control" 
                                value="<?= $cakeDetails['number_candle_value'] ?? '' ?>" 
                                placeholder="np. 18, 30, 50">
                        </div>
                    </div>

                    <!-- Sparkler -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_sparkler" value="1" 
                                id="hasSparkler" <?= isset($cakeDetails) && $cakeDetails['has_sparkler'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasSparkler">
                                Zimne ognie
                            </label>
                        </div>
                    </div>

                    <!-- Wafer Photo -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_wafer_photo" value="1" 
                                id="hasWaferPhoto" <?= isset($cakeDetails) && $cakeDetails['has_wafer_photo'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasWaferPhoto">
                                Zdjęcie na opłatku
                            </label>
                        </div>
                        <div id="waferPhotoDiv" style="display:none;" class="mt-2">
                            <?php if(isset($cakeDetails) && $cakeDetails['wafer_file']): ?>
                                <div class="mb-2">
                                    <a href="<?= $cakeDetails['wafer_file'] ?>" target="_blank" class="btn btn-sm btn-info">
                                        <i class="fas fa-eye me-1"></i>Zobacz obecny plik
                                    </a>
                                </div>
                            <?php endif; ?>
                            <input type="file" name="wafer_file" class="form-control" accept="image/*,.pdf">
                            <small class="text-muted">JPG, PNG, PDF (max 5MB)</small>
                        </div>
                    </div>

                    <!-- Card -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_card" value="1" 
                                id="hasCard" <?= isset($cakeDetails) && $cakeDetails['has_card'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasCard">
                                Kartka z życzeniami
                            </label>
                        </div>
                        <div id="cardDiv" style="display:none;" class="mt-2">
                            <label class="form-label">Tekst na kartce</label>
                            <textarea name="card_text" class="form-control" rows="3"><?= $cakeDetails['card_text'] ?? '' ?></textarea>
                            <label class="form-label mt-2">Wzór kartki</label>
                            <input type="text" name="card_pattern" class="form-control" 
                                value="<?= $cakeDetails['card_pattern'] ?? '' ?>" 
                                placeholder="np. Wzór urodzinowy, Wzór dziecięcy">
                        </div>
                    </div>

                    <!-- Figurine -->
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="has_figurine" value="1" 
                                id="hasFigurine" <?= isset($cakeDetails) && $cakeDetails['has_figurine'] ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="hasFigurine">
                                Figurka
                            </label>
                        </div>
                        <div id="figurineDiv" style="display:none;" class="mt-2">
                            <textarea name="figurine_description" class="form-control" rows="2" 
                                placeholder="Opis figurki"><?= $cakeDetails['figurine_description'] ?? '' ?></textarea>
                        </div>
                    </div>

                    <!-- Reference Photo -->
                    <div class="mb-3">
                        <label class="form-label">Zdjęcie inspiracji/wzoru</label>
                        <?php if(isset($cakeDetails) && $cakeDetails['reference_photo']): ?>
                            <div class="mb-2">
                                <a href="<?= $cakeDetails['reference_photo'] ?>" target="_blank" class="btn btn-sm btn-info">
                                    <i class="fas fa-eye me-1"></i>Zobacz obecne zdjęcie
                                </a>
                            </div>
                        <?php endif; ?>
                        <input type="file" name="reference_photo" class="form-control" accept="image/*">
                        <small class="text-muted">JPG, PNG (max 5MB)</small>
                    </div>

                    <!-- Notes -->
                    <div class="mb-3">
                        <label class="form-label">Uwagi dodatkowe</label>
                        <textarea name="notes" class="form-control" rows="4" 
                            placeholder="Wszelkie dodatkowe informacje, specjalne życzenia klienta"><?= $cakeDetails['notes'] ?? '' ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column -->
        <div class="col-lg-4">
            <!-- Order Status -->
            <div class="card mb-4">
                <div class="card-header bg-secondary text-white">
                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Status Zamówienia</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Status *</label>
                        <select name="status" class="form-select" required>
                            <option value="pending" <?= isset($order) && $order['status'] == 'pending' ? 'selected' : '' ?>>
                                Oczekujące
                            </option>
                            <option value="confirmed" <?= isset($order) && $order['status'] == 'confirmed' ? 'selected' : '' ?>>
                                Potwierdzone
                            </option>
                            <option value="in_production" <?= isset($order) && $order['status'] == 'in_production' ? 'selected' : '' ?>>
                                W produkcji
                            </option>
                            <option value="ready" <?= isset($order) && $order['status'] == 'ready' ? 'selected' : '' ?>>
                                Gotowe
                            </option>
                            <option value="completed" <?= isset($order) && $order['status'] == 'completed' ? 'selected' : '' ?>>
                                Zrealizowane
                            </option>
                            <option value="cancelled" <?= isset($order) && $order['status'] == 'cancelled' ? 'selected' : '' ?>>
                                Anulowane
                            </option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Payment -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-money-bill-wave me-2"></i>Płatność</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Sposób płatności</label>
                        <select name="payment_method" class="form-select">
                            <option value="on_pickup" <?= isset($order) && $order['payment_method'] == 'on_pickup' ? 'selected' : '' ?>>
                                Przy odbiorze
                            </option>
                            <option value="online" <?= isset($order) && $order['payment_method'] == 'online' ? 'selected' : '' ?>>
                                Online
                            </option>
                            <option value="transfer" <?= isset($order) && $order['payment_method'] == 'transfer' ? 'selected' : '' ?>>
                                Przelew
                            </option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Zadatek (opcjonalnie)</label>
                        <div class="input-group">
                            <input type="number" name="deposit_amount" class="form-control" step="0.01" min="0" 
                                value="<?= $order['deposit_amount'] ?? '' ?>" 
                                placeholder="0.00">
                            <span class="input-group-text">PLN</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Submit Buttons -->
            <div class="card">
                <div class="card-body">
                    <button type="submit" class="btn btn-primary w-100 mb-2">
                        <i class="fas fa-save me-1"></i>
                        <?= isset($order) ? 'Zapisz zmiany' : 'Utwórz zamówienie' ?>
                    </button>
                    <a href="<?= url('cake-orders') ?>" class="btn btn-secondary w-100">
                        <i class="fas fa-times me-1"></i>Anuluj
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

<?php
$content = ob_get_clean();

// Scripts for dynamic form behavior
ob_start();
?>
<script>
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });

    // Customer select - show phone/email
    $('#customerSelect').on('change', function() {
        const selected = $(this).find(':selected');
        $('#customerPhone').val(selected.data('phone') || '');
        $('#customerEmail').val(selected.data('email') || '');
    });

    // Pickup location - show/hide delivery address
    $('#pickupLocation').on('change', function() {
        const selectedText = $(this).find(':selected').text().toLowerCase();
        if (selectedText.includes('dostawa')) {
            $('#deliveryAddress').slideDown();
        } else {
            $('#deliveryAddress').slideUp();
        }
    }).trigger('change');

    // Flavor - show/hide custom input
    $('#flavorSelect').on('change', function() {
        if ($(this).val() === 'custom') {
            $('#customFlavorDiv').slideDown();
        } else {
            $('#customFlavorDiv').slideUp();
        }
    }).trigger('change');

    // Size - show/hide custom input
    $('#sizeSelect').on('change', function() {
        if ($(this).val() === 'custom') {
            $('#customSizeDiv').slideDown();
        } else {
            $('#customSizeDiv').slideUp();
        }
    }).trigger('change');

    // Checkbox toggles
    $('#hasInscription').on('change', function() {
        $('#inscriptionDiv').toggle(this.checked);
    }).trigger('change');

    $('#hasCandles').on('change', function() {
        $('#candlesDiv').toggle(this.checked);
    }).trigger('change');

    $('#hasNumberCandle').on('change', function() {
        $('#numberCandleDiv').toggle(this.checked);
    }).trigger('change');

    $('#hasWaferPhoto').on('change', function() {
        $('#waferPhotoDiv').toggle(this.checked);
    }).trigger('change');

    $('#hasCard').on('change', function() {
        $('#cardDiv').toggle(this.checked);
    }).trigger('change');

    $('#hasFigurine').on('change', function() {
        $('#figurineDiv').toggle(this.checked);
    }).trigger('change');
});
</script>
<?php
$scripts = ob_get_clean();

require_once __DIR__ . '/../layout.php';
?>
