@extends('layouts.admin')

@section('title', 'Gestion MLM')

@section('content')
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0">Gestion du Système MLM</h1>
    </div>

    <!-- ÉTAPE 2-3: Messages d'alerte pour feedback utilisateur -->
    <div id="feedback-container"></div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Niveaux de Commission ({{ $levels->count() }} niveau(x) actif(s))</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Niveau</th>
                                    <th>Nom</th>
                                    <th>Taux (%)</th>
                                    <th>Statut</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($levels as $level)
                                <tr class="level-row-{{ $level->id }}">
                                    <td><strong>{{ $level->level }}</strong></td>
                                    <td>{{ $level->name }}</td>
                                    <td>
                                        <!-- ÉTAPE 2: Bouton avec loading state et AJAX -->
                                        <form class="ajaxLevelForm d-inline" data-level-id="{{ $level->id }}" action="{{ route('admin.mlm.update-level', $level) }}" method="POST">
                                            @csrf
                                            @method('PUT')
                                            <div class="input-group input-group-sm" style="width: 120px;">
                                                <input type="number" name="commission_rate" value="{{ $level->commission_rate }}" 
                                                       step="0.01" min="0" max="100" class="form-control" required>
                                                <input type="hidden" name="name" value="{{ $level->name }}">
                                                <button type="submit" class="btn btn-primary submitBtn">
                                                    <span class="btnText">OK</span>
                                                    <span class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                                                </button>
                                            </div>
                                        </form>
                                    </td>
                                    <td>
                                        @if($level->is_active)
                                            <span class="badge bg-success">Actif</span>
                                        @else
                                            <span class="badge bg-secondary">Inactif</span>
                                        @endif
                                    </td>
                                    <td>
                                        <form class="ajaxStatusForm d-inline" data-level-id="{{ $level->id }}" action="{{ route('admin.mlm.update-level', $level) }}" method="POST">
                                            @csrf
                                            @method('PUT')
                                            <input type="hidden" name="name" value="{{ $level->name }}">
                                            <input type="hidden" name="commission_rate" value="{{ $level->commission_rate }}">
                                            <input type="hidden" name="is_active" value="{{ $level->is_active ? 0 : 1 }}">
                                            <button type="submit" class="btn btn-sm {{ $level->is_active ? 'btn-warning' : 'btn-success' }} submitBtn">
                                                <span class="btnText">{{ $level->is_active ? 'Désactiver' : 'Activer' }}</span>
                                                <span class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Rangs</h5>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addRankModal">
                        + Ajouter
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Rang</th>
                                    <th>Ventes Perso</th>
                                    <th>Ventes Équipe</th>
                                    <th>Filleuls</th>
                                    <th>Bonus %</th>
                                    <th>Prime (FCFA)</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($ranks as $rank)
                                <tr>
                                    <td>
                                        <span class="badge" style="background-color: {{ $rank->badge_color ?? '#6c757d' }}">
                                            {{ $rank->name }}
                                        </span>
                                    </td>
                                    <td>{{ number_format($rank->min_personal_sales, 0, ',', ' ') }}</td>
                                    <td>{{ number_format($rank->min_team_sales, 0, ',', ' ') }}</td>
                                    <td>{{ $rank->min_direct_referrals }}</td>
                                    <td>{{ $rank->commission_bonus }}%</td>
                                    <td>{{ number_format($rank->bonus_amount ?? 0, 0, ',', ' ') }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editRank({{ json_encode($rank) }})">
                                            Modifier
                                        </button>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addRankModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="addRankForm" action="{{ route('admin.mlm.store-rank') }}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Ajouter un Rang</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="addRankErrors"></div>
                    <div class="mb-3">
                        <label class="form-label">Nom</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" name="slug" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Niveau</label>
                            <input type="number" name="level" class="form-control" min="0" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Couleur</label>
                            <input type="color" name="badge_color" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Ventes Perso Min</label>
                            <input type="number" name="min_personal_sales" class="form-control" min="0" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Ventes Équipe Min</label>
                            <input type="number" name="min_team_sales" class="form-control" min="0" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Filleuls Directs Min</label>
                            <input type="number" name="min_direct_referrals" class="form-control" min="0" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Bonus (%)</label>
                            <input type="number" name="commission_bonus" class="form-control" min="0" max="100" step="0.01" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Prime (FCFA)</label>
                            <input type="number" name="bonus_amount" class="form-control" min="0" value="0" placeholder="Ex: 50000">
                            <small class="text-muted">Prime à l'atteinte du rang</small>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Taille d'équipe minimale</label>
                            <input type="number" name="min_team_size" class="form-control" min="0" value="0">
                        </div>
                    </div>
                    <div class="form-check form-switch mb-3">
                        <input type="hidden" name="is_active" value="0">
                        <input class="form-check-input" type="checkbox" name="is_active" value="1" id="rankActiveCreate" checked>
                        <label class="form-check-label" for="rankActiveCreate">Rang actif</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-primary submitBtn">
                        <span class="btnText">Créer</span>
                        <span class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editRankModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="#" method="POST" id="editRankForm">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title">Modifier le Rang</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="editRankErrors"></div>
                    <div class="mb-3">
                        <label class="form-label">Nom</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Ventes Perso Min</label>
                            <input type="number" name="min_personal_sales" class="form-control" min="0" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Ventes Équipe Min</label>
                            <input type="number" name="min_team_sales" class="form-control" min="0" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Filleuls Directs Min</label>
                            <input type="number" name="min_direct_referrals" class="form-control" min="0" value="0">
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Bonus (%)</label>
                            <input type="number" name="commission_bonus" class="form-control" min="0" max="100" step="0.01" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Prime (FCFA)</label>
                            <input type="number" name="bonus_amount" class="form-control" min="0" value="0" placeholder="Ex: 50000">
                            <small class="text-muted">Prime à l'atteinte du rang</small>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Taille d'équipe minimale</label>
                            <input type="number" name="min_team_size" class="form-control" min="0" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Couleur</label>
                        <input type="color" name="badge_color" class="form-control" value="#6c757d">
                    </div>
                    <div class="form-check form-switch mb-2">
                        <input type="hidden" name="is_active" value="0">
                        <input class="form-check-input" type="checkbox" name="is_active" value="1" id="rankActiveEdit">
                        <label class="form-check-label" for="rankActiveEdit">Rang actif</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-primary submitBtn">
                        <span class="btnText">Mettre à jour</span>
                        <span class="spinner-border spinner-border-sm d-none ms-2" role="status" aria-hidden="true"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
// ÉTAPE 2-3: Gestion AJAX des formulaires MLM avec feedback utilisateur

function editRank(rank) {
    const form = document.getElementById('editRankForm');
    const actionTemplate = "{{ route('admin.mlm.update-rank', '__ID__') }}";
    form.action = actionTemplate.replace('__ID__', rank.id);

    form.querySelector('[name="name"]').value = rank.name || '';
    form.querySelector('[name="min_personal_sales"]').value = rank.min_personal_sales ?? 0;
    form.querySelector('[name="min_team_sales"]').value = rank.min_team_sales ?? 0;
    form.querySelector('[name="min_direct_referrals"]').value = rank.min_direct_referrals ?? 0;
    form.querySelector('[name="commission_bonus"]').value = rank.commission_bonus ?? 0;
    form.querySelector('[name="bonus_amount"]').value = rank.bonus_amount ?? 0;
    form.querySelector('[name="min_team_size"]').value = rank.min_team_size ?? 0;
    form.querySelector('[name="badge_color"]').value = rank.badge_color || '#6c757d';
    form.querySelector('#rankActiveEdit').checked = !!rank.is_active;
    document.getElementById('editRankErrors').innerHTML = '';

    const editModal = new bootstrap.Modal(document.getElementById('editRankModal'));
    editModal.show();
}

function showFeedback(type, message) {
    const container = document.getElementById('feedback-container');
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertHtml = `<div class="alert ${alertClass} alert-dismissible fade show" role="alert">
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>`;
    container.innerHTML = alertHtml;
    
    setTimeout(() => {
        const alert = document.querySelector('#feedback-container .alert');
        if (alert) {
            alert.remove();
        }
    }, 5000);
}

// Gérer les formulaires de niveau AJAX
document.querySelectorAll('.ajaxLevelForm').forEach(form => {
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const submitBtn = form.querySelector('.submitBtn');
        const spinner = submitBtn.querySelector('.spinner-border');
        const btnText = submitBtn.querySelector('.btnText');
        
        submitBtn.disabled = true;
        spinner.classList.remove('d-none');
        
        try {
            const formData = new FormData(form);
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                body: formData
            });
            
            if (!response.ok) {
                const data = await response.json();
                if (data.errors) {
                    let errorMsg = '<ul>';
                    Object.values(data.errors).forEach(errors => {
                        errors.forEach(error => {
                            errorMsg += '<li>' + error + '</li>';
                        });
                    });
                    errorMsg += '</ul>';
                    showFeedback('error', 'Erreur: ' + errorMsg);
                } else {
                    showFeedback('error', data.message || 'Erreur lors de la mise à jour');
                }
            } else {
                const data = await response.json();
                showFeedback('success', data.message || 'Mise à jour réussie!');
                
                setTimeout(() => {
                    location.reload();
                }, 1500);
            }
        } catch (error) {
            showFeedback('error', 'Erreur: ' + error.message);
        } finally {
            submitBtn.disabled = false;
            spinner.classList.add('d-none');
        }
    });
});

// Gérer les formulaires de statut AJAX
document.querySelectorAll('.ajaxStatusForm').forEach(form => {
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const submitBtn = form.querySelector('.submitBtn');
        const spinner = submitBtn.querySelector('.spinner-border');
        
        submitBtn.disabled = true;
        spinner.classList.remove('d-none');
        
        try {
            const formData = new FormData(form);
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                body: formData
            });
            
            if (!response.ok) {
                showFeedback('error', 'Erreur lors de la mise à jour');
            } else {
                const data = await response.json();
                showFeedback('success', data.message || 'Mise à jour réussie!');
                
                setTimeout(() => {
                    location.reload();
                }, 1500);
            }
        } catch (error) {
            showFeedback('error', 'Erreur: ' + error.message);
        } finally {
            submitBtn.disabled = false;
            spinner.classList.add('d-none');
        }
    });
});

// Gérer le formulaire d'ajout de rang
document.getElementById('addRankForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const form = e.target;
    const submitBtn = form.querySelector('.submitBtn');
    const spinner = submitBtn.querySelector('.spinner-border');
    const errorContainer = document.getElementById('addRankErrors');
    
    submitBtn.disabled = true;
    spinner.classList.remove('d-none');
    errorContainer.innerHTML = '';
    
    try {
        const formData = new FormData(form);
        const response = await fetch(form.action, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            body: formData
        });
        
        if (!response.ok) {
            const data = await response.json();
            if (data.errors) {
                let errorHtml = '<div class="alert alert-danger"><ul>';
                Object.values(data.errors).forEach(errors => {
                    errors.forEach(error => {
                        errorHtml += '<li>' + error + '</li>';
                    });
                });
                errorHtml += '</ul></div>';
                errorContainer.innerHTML = errorHtml;
            }
        } else {
            const data = await response.json();
            showFeedback('success', data.message || 'Rang créé avec succès!');
            
            bootstrap.Modal.getInstance(document.getElementById('addRankModal')).hide();
            setTimeout(() => {
                location.reload();
            }, 1500);
        }
    } catch (error) {
        errorContainer.innerHTML = '<div class="alert alert-danger">Erreur: ' + error.message + '</div>';
    } finally {
        submitBtn.disabled = false;
        spinner.classList.add('d-none');
    }
});

// Gérer le formulaire d'édition de rang
document.getElementById('editRankForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const form = e.target;
    const submitBtn = form.querySelector('.submitBtn');
    const spinner = submitBtn.querySelector('.spinner-border');
    const errorContainer = document.getElementById('editRankErrors');
    
    submitBtn.disabled = true;
    spinner.classList.remove('d-none');
    errorContainer.innerHTML = '';
    
    try {
        const formData = new FormData(form);
        const response = await fetch(form.action, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            body: formData
        });
        
        if (!response.ok) {
            const data = await response.json();
            if (data.errors) {
                let errorHtml = '<div class="alert alert-danger"><ul>';
                Object.values(data.errors).forEach(errors => {
                    errors.forEach(error => {
                        errorHtml += '<li>' + error + '</li>';
                    });
                });
                errorHtml += '</ul></div>';
                errorContainer.innerHTML = errorHtml;
            }
        } else {
            const data = await response.json();
            showFeedback('success', data.message || 'Rang mis à jour avec succès!');
            
            bootstrap.Modal.getInstance(document.getElementById('editRankModal')).hide();
            setTimeout(() => {
                location.reload();
            }, 1500);
        }
    } catch (error) {
        errorContainer.innerHTML = '<div class="alert alert-danger">Erreur: ' + error.message + '</div>';
    } finally {
        submitBtn.disabled = false;
        spinner.classList.add('d-none');
    }
});
</script>
@endpush
@endsection
