<?php if (session('errors')) : ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach (session('errors') as $error) : ?>
                <li><?= esc($error) ?></li>
            <?php endforeach ?>
        </ul>
    </div>
<?php endif ?>

<?= $this->extend('tipster/layout') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Edit Tip</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <a href="<?= site_url('tipster/my-tips') ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> Back to My Tips
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <form action="<?= site_url('tipster/update-tip/' . $tip['id']) ?>" method="post">
                <?= csrf_field() ?>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="title" name="title" placeholder="Tip Title" value="<?= esc($tip['title']) ?>" required>
                            <label for="title">Title <span class="text-danger">*</span></label>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-floating mb-3">
                            <select class="form-select" id="tag" name="tag" required>
                                <option value="">Select Tag</option>
                                <option value="free" <?= $tip['tag'] === 'free' ? 'selected' : '' ?>>Free</option>
                                <option value="paid" <?= $tip['tag'] === 'paid' ? 'selected' : '' ?>>Paid</option>
                            </select>
                            <label for="tag">Tag <span class="text-danger">*</span></label>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-floating mb-3">
                            <select class="form-select" id="category" name="category" required>
                                <option value="">Select Category</option>
                                <option value="Free" <?= $tip['category'] === 'Free' ? 'selected' : '' ?>>Free</option>
                                <option value="Normal" <?= $tip['category'] === 'Normal' ? 'selected' : '' ?>>Normal</option>
                                <option value="Ordinary" <?= $tip['category'] === 'Ordinary' ? 'selected' : '' ?>>Ordinary</option>
                                <option value="VIP" <?= $tip['category'] === 'VIP' ? 'selected' : '' ?>>VIP</option>
                                <option value="VVIP" <?= $tip['category'] === 'VVIP' ? 'selected' : '' ?>>VVIP</option>
                                <option value="Cooperate" <?= $tip['category'] === 'Cooperate' ? 'selected' : '' ?>>Cooperate</option>
                                <option value="Elite" <?= $tip['category'] === 'Elite' ? 'selected' : '' ?>>Elite</option>
                                <option value="Kibimba" <?= $tip['category'] === 'Kibimba' ? 'selected' : '' ?>>Kibimba</option>
                                <option value="Rollover" <?= $tip['category'] === 'Rollover' ? 'selected' : '' ?>>Rollover</option>
                            </select>
                            <label for="category">Category <span class="text-danger">*</span></label>
                        </div>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="form-floating mb-3">
                            <input type="number" class="form-control" id="amount" name="amount" placeholder="Amount" step="0.01" min="0" value="<?= esc($tip['amount']) ?>" required>
                            <label for="amount">Amount (UGX) <span class="text-danger">*</span></label>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="odds_source" name="odds_source" placeholder="Odds Source" value="<?= esc($tip['odds_source'] ?? '') ?>" required>
                            <label for="odds_source">Odds Source (e.g. Betway, Bet365) <span class="text-danger">*</span></label>
                        </div>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="form-floating">
                            <input type="datetime-local" class="form-control" name="match_time" placeholder="Match Time" 
                                   value="<?= isset($tip['match_time']) ? date('Y-m-d\TH:i', strtotime($tip['match_time'])) : '' ?>" required>
                            <label>Match Time <span class="text-danger">*</span></label>
                        </div>
                    </div>
                </div>

                <div id="matches-container" class="mb-4">
                    <!-- Match fields will be dynamically inserted here by JavaScript -->
                </div>

                <div class="d-flex gap-2 mb-4">
                    <button type="button" id="add-match" class="btn btn-outline-primary">
                        <i class="bi bi-plus-circle me-2"></i>Add Another Match
                    </button>
                </div>

                <div id="booking-codes-container" class="mb-4">
                    <!-- Booking codes will be dynamically inserted here by JavaScript -->
                </div>

                <div class="d-flex gap-2 mb-4">
                    <button type="button" id="add-booking-code" class="btn btn-outline-success">
                        <i class="bi bi-plus-circle me-2"></i>Add Another Booking Code
                    </button>
                </div>

                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i>Update Tip
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Parse the JSON matches data
        const matchesData = <?= json_encode($tip['matches']) ?>;
        const container = document.getElementById('matches-container');

        // Clear any existing content
        container.innerHTML = '';

        // Add each match to the form
        matchesData.forEach((match, index) => {
            const matchHTML = `
                <div class="card mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="bi bi-trophy me-2"></i>Match ${index + 1}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-match" ${matchesData.length <= 1 ? 'disabled' : ''}>
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][team1]" placeholder="Team 1" value="${escapeHtml(match.team1)}" required>
                                    <label>Team 1 <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][team2]" placeholder="Team 2" value="${escapeHtml(match.team2)}" required>
                                    <label>Team 2 <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][league]" placeholder="League/Competition" value="${escapeHtml(match.league || '')}" required>
                                    <label>League/Competition <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][prediction]" placeholder="Prediction" value="${escapeHtml(match.prediction || '')}" required>
                                    <label>Prediction <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="number" class="form-control" name="matches[${index}][odds]" placeholder="Odds" step="0.01" min="1" value="${escapeHtml(match.odds || '')}" required>
                                    <label>Odds <span class="text-danger">*</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', matchHTML);
        });

        // Add event listener for adding new matches
        document.getElementById('add-match').addEventListener('click', function() {
            const index = container.children.length;

            const newMatchHTML = `
                <div class="card mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="bi bi-trophy me-2"></i>Match ${index + 1}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-match">
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][team1]" placeholder="Team 1" required>
                                    <label>Team 1 <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][team2]" placeholder="Team 2" required>
                                    <label>Team 2 <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][league]" placeholder="League/Competition" required>
                                    <label>League/Competition <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="matches[${index}][prediction]" placeholder="Prediction" required>
                                    <label>Prediction <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-floating">
                                    <input type="number" class="form-control" name="matches[${index}][odds]" placeholder="Odds" step="0.01" min="1" required>
                                    <label>Odds <span class="text-danger">*</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', newMatchHTML);
            updateRemoveButtons();
        });
        
        // Remove match
        container.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-match') || e.target.closest('.remove-match')) {
                const matchCard = e.target.closest('.card');
                if (matchCard) {
                    matchCard.remove();
                    renumberMatches();
                }
            }
        });
        
        function renumberMatches() {
            const matches = container.querySelectorAll('.card');
            matches.forEach((match, index) => {
                const header = match.querySelector('.card-header h6');
                if (header) {
                    header.innerHTML = `<i class="bi bi-trophy me-2"></i>Match ${index + 1}`;
                }
                
                // Update all input names with new index
                const inputs = match.querySelectorAll('input');
                inputs.forEach(input => {
                    const name = input.name.replace(/matches\[\d+\]/, `matches[${index}]`);
                    input.name = name;
                });
            });
            
            updateRemoveButtons();
        }
        
        function updateRemoveButtons() {
            const removeButtons = container.querySelectorAll('.remove-match');
            removeButtons.forEach(button => {
                button.disabled = removeButtons.length <= 1;
            });
        }

        // Simple HTML escape function for safety
        function escapeHtml(unsafe) {
            if (unsafe === undefined || unsafe === null) return '';
            return unsafe.toString()
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Booking Codes functionality
        const bookingCodesContainer = document.getElementById('booking-codes-container');
        
        // Parse existing booking codes data
        const bookingCodesData = <?= json_encode($tip['booking_codes'] ?? []) ?>;
        
        // Add existing booking codes to the form
        bookingCodesData.forEach((bookingCode, index) => {
            const bookingCodeHTML = `
                <div class="card mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="bi bi-qr-code me-2"></i>Booking Code ${index + 1}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-booking-code" ${bookingCodesData.length <= 1 ? 'disabled' : ''}>
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[${index}][provider]" placeholder="Betting Provider" value="${escapeHtml(bookingCode.provider || '')}" required>
                                    <label>Betting Provider (e.g. Bet365, Betway) <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[${index}][code]" placeholder="Booking Code" value="${escapeHtml(bookingCode.code || '')}" required>
                                    <label>Booking Code <span class="text-danger">*</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            bookingCodesContainer.insertAdjacentHTML('beforeend', bookingCodeHTML);
        });

        // If no booking codes exist, add one empty booking code field
        if (bookingCodesData.length === 0) {
            const emptyBookingCodeHTML = `
                <div class="card mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="bi bi-qr-code me-2"></i>Booking Code 1</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-booking-code" disabled>
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[0][provider]" placeholder="Betting Provider" required>
                                    <label>Betting Provider (e.g. Bet365, Betway) <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[0][code]" placeholder="Booking Code" required>
                                    <label>Booking Code <span class="text-danger">*</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            bookingCodesContainer.insertAdjacentHTML('beforeend', emptyBookingCodeHTML);
        }

        // Add booking code
        document.getElementById('add-booking-code').addEventListener('click', function() {
            const index = bookingCodesContainer.children.length;
            
            const newBookingCodeHTML = `
                <div class="card mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h6 class="mb-0"><i class="bi bi-qr-code me-2"></i>Booking Code ${index + 1}</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-booking-code">
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[${index}][provider]" placeholder="Betting Provider" required>
                                    <label>Betting Provider (e.g. Bet365, Betway) <span class="text-danger">*</span></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating">
                                    <input type="text" class="form-control" name="booking_codes[${index}][code]" placeholder="Booking Code" required>
                                    <label>Booking Code <span class="text-danger">*</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            bookingCodesContainer.insertAdjacentHTML('beforeend', newBookingCodeHTML);
            updateBookingCodeRemoveButtons();
        });
        
        // Remove booking code
        bookingCodesContainer.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-booking-code') || e.target.closest('.remove-booking-code')) {
                const bookingCodeCard = e.target.closest('.card');
                if (bookingCodeCard) {
                    bookingCodeCard.remove();
                    renumberBookingCodes();
                }
            }
        });
        
        function renumberBookingCodes() {
            const bookingCodeCards = bookingCodesContainer.querySelectorAll('.card');
            bookingCodeCards.forEach((card, index) => {
                const header = card.querySelector('.card-header h6');
                if (header) {
                    header.innerHTML = `<i class="bi bi-qr-code me-2"></i>Booking Code ${index + 1}`;
                }
                
                // Update input names
                const inputs = card.querySelectorAll('input');
                inputs.forEach(input => {
                    const name = input.getAttribute('name');
                    if (name) {
                        input.setAttribute('name', name.replace(/\[\d+\]/, `[${index}]`));
                    }
                });
            });
            
            updateBookingCodeRemoveButtons();
        }
        
        function updateBookingCodeRemoveButtons() {
            const removeButtons = bookingCodesContainer.querySelectorAll('.remove-booking-code');
            removeButtons.forEach((button, index) => {
                button.disabled = index === 0;
            });
        }
        
        // Initialize booking codes
        updateBookingCodeRemoveButtons();
    });
</script>
<?= $this->endSection() ?>

