<?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 ?>

<?php if (session('error')) : ?>
    <div class="alert alert-danger">
        <?= esc(session('error')) ?>
    </div>
<?php endif ?>

<?php if (session('success')) : ?>
    <div class="alert alert-success">
        <?= esc(session('success')) ?>
    </div>
<?php endif ?>

<?= $this->extend('admin/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">Add New Tip</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <a href="<?= site_url('admin/tips') ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> Back to Tips
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <form action="<?= site_url('admin/saveTip') ?>" 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" required>
                            <label for="title">Title</label>
                            <small class="text-muted">The tip ID will be automatically appended to your title</small>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-floating mb-3">
                            <select class="form-select" id="tag" name="tag" required>
                                <option value="free">Free</option>
                                <option value="paid">Paid</option>
                            </select>
                            <label for="tag">Tag</label>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="category" name="category" placeholder="Category">
                            <label for="category">Category (VIP, VVIP...)</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" required>
                            <label for="amount">Amount (UGX)</label>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="author" name="author" placeholder="Author">
                            <label for="author">Author</label>
                        </div>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-md-6">
                        <div class="form-floating">
                            <input type="text" class="form-control" name="odds_source" placeholder="Odds Source" required>
                            <label>Odds Source (e.g. Betway, Bet365)</label>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-floating">
                            <input type="datetime-local" class="form-control" name="match_time" placeholder="Match Time">
                            <label>Match Time (Optional)</label>
                        </div>
                        <small class="text-muted">Set this to prevent purchases after matches start</small>
                    </div>
                </div>

                <p class="text-muted small mb-3">For each match: choose country, league, and fixture (cached daily). Then enter prediction and odds from your bookmaker.</p>

                <div id="matches-container" class="mb-4">
                    <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 1</h6>
                            <button type="button" class="btn btn-sm btn-outline-danger remove-match" disabled>
                                <i class="bi bi-trash"></i> Remove
                            </button>
                        </div>
                        <div class="card-body">
                            <?= view('partials/football_match_picker') ?>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="form-floating">
                                        <input type="text" class="form-control" name="matches[0][team1]" placeholder="Team 1" required>
                                        <label>Team 1</label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-floating">
                                        <input type="text" class="form-control" name="matches[0][team2]" placeholder="Team 2" required>
                                        <label>Team 2</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-floating">
                                        <input type="text" class="form-control" name="matches[0][league]" placeholder="League/Competition" required>
                                        <label>League/Competition</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-floating">
                                        <input type="text" class="form-control" name="matches[0][prediction]" placeholder="Prediction" required>
                                        <label>Prediction</label>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-floating">
                                        <input type="number" class="form-control" name="matches[0][odds]" placeholder="Odds" step="0.01" min="1" required>
                                        <label>Odds</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </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 class="row g-3">
                    <div class="col-md-6">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" id="is_hot" name="is_hot" value="1">
                            <label class="form-check-label" for="is_hot">HOT (Highlight this tip)</label>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" id="is_subscriber_only" name="is_subscriber_only" value="1">
                            <label class="form-check-label" for="is_subscriber_only">Available for Subscribers Only</label>
                        </div>
                    </div>
                </div>
                <div id="booking-codes-container" class="mb-4">
                    <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)</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</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </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>Save Tip
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const container = document.getElementById('matches-container');
        const titleInput = document.getElementById('title');
        let nextTipId = <?= $nextTipId ?>;
        let originalTitle = '';
        
        // Function to format title with tip ID
        function formatTitleWithId(input) {
            const value = input.value.trim();
            if (value) {
                // Remove any existing ID format
                const baseTitle = value.replace(/\s*#\d+$/, '');
                input.value = `${baseTitle} #${nextTipId}`;
            }
        }
        
        // Function to remove ID when user starts typing
        function removeId(input) {
            const value = input.value.trim();
            if (value) {
                // Remove any existing ID format
                input.value = value.replace(/\s*#\d+$/, '');
            }
        }
        
        // Remove ID when user starts typing
        titleInput.addEventListener('focus', function() {
            removeId(this);
        });
        
        // Add ID when user leaves the field
        titleInput.addEventListener('blur', function() {
            formatTitleWithId(this);
        });
        
        // Add match
        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</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</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</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</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</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();
                }
            }
        });
        
        window.renumberTipMatches = 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();
        }
        
        window.updateTipRemoveButtons = function updateRemoveButtons() {
            const removeButtons = container.querySelectorAll('.remove-match');
            removeButtons.forEach(button => {
                button.disabled = removeButtons.length <= 1;
            });
        }
        
        // Booking Codes functionality
        const bookingCodesContainer = document.getElementById('booking-codes-container');
        
        // 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)</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</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() ?>

<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/js/football-fixture-picker.js') ?>"></script>
<script>
    FootballMatchPicker.init({
        baseUrl: '<?= site_url('admin/football') ?>',
        mode: 'tip',
        matchesContainer: '#matches-container'
    });
</script>
<?= $this->endSection() ?>