@extends('layouts.app')

@section('content')
<div class="container mx-auto p-6">
    <h2 class="text-2xl font-bold mb-6">Members Progress</h2>

    <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
        @foreach($members as $member)
        <div class="bg-white shadow p-4 rounded">
            <h3 class="text-lg font-bold">{{ $member->first_name }} {{ $member->surname }}</h3>
            <p class="text-gray-500">{{ $member->mobile }}</p>
            <div class="mt-4 flex justify-between">
                <button class="bg-blue-500 text-white px-3 py-1 rounded"
                        onclick="openProgressPopup({{ $member->id }}, '{{ $member->first_name }} {{ $member->surname }}')">
                    Add Today Progress
                </button>
                <a href="{{ route('progress.show', $member->id) }}"
                   class="bg-gray-500 text-white px-3 py-1 rounded">
                    View Progresses
                </a>
            </div>
        </div>
        @endforeach
    </div>
</div>

<!-- Progress Popup -->
<div id="progress-popup" class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center hidden z-50">
    <div class="bg-white p-6 rounded w-96 relative">
        <h3 id="member-name" class="text-xl font-bold mb-4"></h3>
        <button class="absolute top-2 right-2 text-red-500 text-lg font-bold" onclick="closePopup()">×</button>

        <form id="progress-form">
            <input type="hidden" name="member_id" id="member-id">

            <div class="mb-2">
                <label>Trainer Name</label>
                <input type="text" name="trainer" class="border p-2 w-full" required>
            </div>

            <div class="mb-2">
                <label>Weight (kg)</label>
                <input type="number" name="weight" id="weight" class="border p-2 w-full" required>
            </div>

            <div class="mb-2">
                <label>Height (cm)</label>
                <input type="number" name="height" id="height" class="border p-2 w-full" required>
            </div>

            <div class="mb-2">
                <label>Waist (cm)</label>
                <input type="number" name="waist" class="border p-2 w-full">
            </div>

            <div class="mb-2">
                <label>Hip (cm)</label>
                <input type="number" name="hip" class="border p-2 w-full">
            </div>

            <div class="mb-2">
                <label>Notes</label>
                <textarea name="notes" class="border p-2 w-full"></textarea>
            </div>

            <!-- BMI Display -->
            <div class="mb-2">
                <label>BMI: <span id="bmi-value">0</span></label>
                <div class="w-full bg-gray-200 h-4 rounded">
                    <div id="bmi-bar" class="h-4 bg-green-500 rounded" style="width:0%"></div>
                </div>
            </div>

            <div class="flex justify-between mt-4">
                <button type="button" class="bg-yellow-500 px-3 py-1 rounded" onclick="compareLastProgress()">Compare to Last</button>
                <button type="submit" class="bg-blue-500 px-3 py-1 rounded">Submit Progress</button>
            </div>
        </form>
    </div>
</div>

<script>
// Open and close popup
function openProgressPopup(id, name) {
    document.getElementById('progress-popup').classList.remove('hidden');
    document.getElementById('member-id').value = id;
    document.getElementById('member-name').textContent = name;
}

function closePopup() {
    document.getElementById('progress-popup').classList.add('hidden');
    document.getElementById('progress-form').reset();
    document.getElementById('bmi-value').textContent = 0;
    document.getElementById('bmi-bar').style.width = '0%';
}

// BMI calculation
document.getElementById('weight').addEventListener('input', calculateBMI);
document.getElementById('height').addEventListener('input', calculateBMI);

function calculateBMI() {
    const weight = parseFloat(document.getElementById('weight').value);
    const height = parseFloat(document.getElementById('height').value);
    if (weight && height) {
        const bmi = (weight / ((height/100)**2)).toFixed(1);
        document.getElementById('bmi-value').textContent = bmi;
        const width = Math.min(bmi*5, 100); // scale bar
        document.getElementById('bmi-bar').style.width = width + '%';
    }
}

// Compare to last progress
function compareLastProgress() {
    const memberId = document.getElementById('member-id').value;
    fetch(`/progress/last/${memberId}`)
        .then(res => res.json())
        .then(data => {
            const weightDiff = document.getElementById('weight').value - data.weight;
            alert(`Last weight: ${data.weight}kg\nToday weight diff: ${weightDiff}kg`);
        });
}

// Submit progress via AJAX
document.getElementById('progress-form').addEventListener('submit', function(e){
    e.preventDefault();
    const formData = new FormData(this);
    const memberId = formData.get('member_id');

    fetch(`/progress/store/${memberId}`, {
        method: 'POST',
        headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        alert('Progress submitted!');
        closePopup();
    })
    .catch(err => {
        console.error(err);
        alert('Error submitting progress!');
    });
});
</script>
@endsection
