@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'BloodBank')

@section('left_sidebar')
@include('front_end.pages.bloodbank.bloodbank_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- BloodBank Header -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <a href="{{ url('/') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">BloodBank</h4>
                                    <p class="mb-0 text-white">Donate or request blood to save lives</p>
                                </div>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                @auth
                                <a href="{{ route('bloodbank.donate') }}" class="btn btn-light text-primary">
                                    <i class="fas fa-hand-holding-medical me-2"></i>Donate
                                </a>
                                <a href="{{ route('bloodbank.request') }}" class="btn btn-danger">
                                    <i class="fas fa-plus-circle me-2"></i>Request Blood
                                </a>
                                @else
                                <a href="{{ route('login') }}?redirect={{ urlencode(route('bloodbank.index')) }}" class="btn btn-light text-primary">
                                    <i class="fas fa-sign-in-alt me-2"></i>Login to Donate
                                </a>
                                @endauth
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- BloodBank Content -->
    <div class="container mt-4">
        <!-- Emergency Banner -->
        <div id="emergencyBanner" class="alert alert-danger d-flex align-items-center rounded-3 mb-4" role="alert" style="display: none;">
            <div class="icon-lg bg-danger bg-opacity-25 rounded-circle me-3">
                <i class="fas fa-exclamation-triangle text-danger"></i>
            </div>
            <div class="flex-grow-1">
                <h6 class="mb-1">Urgent Blood Required!</h6>
                <p class="mb-0">Blood Type <span id="emergencyBloodType">O-</span> needed at <span id="emergencyHospital">City Hospital</span>. Contact: <span id="emergencyContact">+1-234-567-8900</span></p>
            </div>
            <input type="hidden" id="emergencyRequestId" value="">
            <button id="respondToEmergency" class="btn btn-sm btn-danger ms-3">Respond</button>
        </div>

        <!-- Quick Actions -->
        <div class="row g-3 mb-4">
            <div class="col-sm-6">
                <div class="card h-100 border-0 shadow-sm rounded-3">
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-3">
                            <div class="icon-md bg-primary bg-opacity-10 rounded-circle text-primary me-3">
                                <i class="fas fa-hand-holding-medical"></i>
                            </div>
                            <h5 class="ms-3 mb-0">Donate Blood</h5>
                        </div>
                        <p class="text-muted small mb-3">Ready to save lives? Schedule your blood donation appointment now.</p>
                        <a href="{{ route('bloodbank.donate') }}" class="btn btn-primary">Schedule Donation</a>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="card h-100 border-0 shadow-sm rounded-3">
                    <div class="card-body">
                        <div class="d-flex align-items-center mb-3">
                            <div class="icon-md bg-danger bg-opacity-10 rounded-circle text-danger me-3">
                                <i class="fas fa-search"></i>
                            </div>
                            <h5 class="ms-3 mb-0">Request Blood</h5>
                        </div>
                        <p class="text-muted small mb-3">Need blood urgently? Submit your request and find donors quickly.</p>
                        <a href="{{ route('bloodbank.request') }}" class="btn btn-danger">Submit Request</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Blood Availability -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Blood Availability</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    @php
                    $bloodTypes = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];
                    @endphp
                    
                    @foreach($bloodTypes as $type)
                    @php 
                    $typeId = str_replace('+', 'pos', str_replace('-', 'neg', $type));
                    @endphp
                    <div class="col-6 col-sm-4 col-lg-3">
                        <div id="availability-{{ $typeId }}" class="card bg-light border-0 rounded-3">
                            <div class="card-body text-center p-3">
                                <h3 class="mb-2">{{ $type }}</h3>
                                <p class="text-muted small mb-2">Available Units</p>
                                <h4 class="mb-0 units-count">--</h4>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Recent Blood Requests -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Recent Blood Requests</h5>
                <a href="{{ route('bloodbank.requests') }}" class="btn btn-sm btn-primary">View All</a>
            </div>
            <div id="recentRequests" class="card-body p-0">
                <div class="p-3 text-center">
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    <span class="ms-2">Loading requests...</span>
                </div>
            </div>
        </div>

        <!-- User Stats (If Authenticated) -->
        @auth
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Your Donor Status</h5>
                <a href="{{ route('bloodbank.profile') }}" class="btn btn-sm btn-primary">View Profile</a>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-sm-6 col-lg-3">
                        <div class="card bg-light border-0 rounded-3">
                            <div class="card-body p-3">
                                <p class="text-muted small mb-1">Status</p>
                                <div class="d-flex align-items-center">
                                    <span id="donorStatusBadge" class="badge bg-secondary me-2">
                                        <i class="fas fa-user-check"></i>
                                    </span>
                                    <h6 id="donorStatus" class="mb-0">--</h6>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <div class="card bg-light border-0 rounded-3">
                            <div class="card-body p-3">
                                <p class="text-muted small mb-1">Blood Type</p>
                                <h6 id="userBloodType" class="mb-0">--</h6>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <div class="card bg-light border-0 rounded-3">
                            <div class="card-body p-3">
                                <p class="text-muted small mb-1">Total Donations</p>
                                <h6 id="donationCount" class="mb-0">--</h6>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <div class="card bg-light border-0 rounded-3">
                            <div class="card-body p-3">
                                <p class="text-muted small mb-1">Last Donation</p>
                                <h6 id="lastDonationDate" class="mb-0">--</h6>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="alert alert-info mt-3 mb-0">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-info-circle me-2"></i>
                        <div>
                            <p class="mb-0 small">Eligibility Status: <span id="eligibilityStatus">--</span></p>
                            <p class="mb-0 small">Days since last donation: <span id="daysSinceLastDonation">--</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endauth

        <!-- Nearby Donors (If Authenticated) -->
        @auth
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Nearby Donors</h5>
                <a href="{{ route('bloodbank.donors') }}" class="btn btn-sm btn-primary">View All</a>
            </div>
            <div id="nearbyDonors" class="card-body">
                @if(!empty($nearbyDonors) && count($nearbyDonors) > 0)
                    <div class="row g-3">
                        @foreach($nearbyDonors as $donor)
                        <div class="col-md-6">
                            <div class="card h-100 border">
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="avatar avatar-md me-3">
                                            @if($donor->avatar)
                                                <img src="{{ asset('storage/' . $donor->avatar) }}" class="rounded-circle" alt="{{ $donor->name }}">
                                            @else
                                                <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                                    {{ strtoupper(substr($donor->name, 0, 1)) }}
                                                </div>
                                            @endif
                                        </div>
                                        <div>
                                            <h6 class="mb-1">{{ $donor->name }}</h6>
                                            <div>
                                                <span class="badge bg-primary me-2">{{ $donor->blood_type }}</span>
                                                <span class="badge bg-light text-dark">
                                                    @if($donor->last_donation_date)
                                                        Last donated: {{ \Carbon\Carbon::parse($donor->last_donation_date)->diffForHumans() }}
                                                    @else
                                                        No previous donations
                                                    @endif
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-center text-muted small mb-3">
                                        <i class="fas fa-map-marker-alt me-2"></i>
                                        <span>{{ number_format($donor->distance, 1) }} km away</span>
                                        @if($donor->donation_count > 0)
                                            <span class="mx-2">•</span>
                                            <i class="fas fa-trophy me-2"></i>
                                            <span>{{ $donor->donation_count }} donations</span>
                                        @endif
                                    </div>
                                    <div class="d-flex gap-2">
                                        @if($donor->phone)
                                            <a href="tel:{{ $donor->phone }}" class="btn btn-sm btn-primary flex-grow-1">
                                                <i class="fas fa-phone me-2"></i>Contact
                                            </a>
                                        @endif
                                        <a href="{{ route('profile.view', $donor->id) }}" class="btn btn-sm btn-light">
                                            <i class="fas fa-info-circle"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>
                @else
                    <div class="text-center py-3">
                        <p class="text-muted mb-0">No nearby donors found</p>
                        <a href="{{ route('bloodbank.profile') }}" class="btn btn-sm btn-primary mt-2">Update Your Location</a>
                    </div>
                @endif
            </div>
        </div>
        @endauth

        <!-- Blood Drive Events -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Upcoming Blood Drives</h5>
                <a href="{{ route('bloodbank.drives') }}" class="btn btn-sm btn-primary">View All</a>
            </div>
            <div id="upcomingDrives" class="card-body">
                <div class="text-center py-3">
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    <span class="ms-2">Loading blood drives...</span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Donation Modal -->
<div class="modal fade" id="donationModal" tabindex="-1" aria-labelledby="donationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="donationModalLabel">Schedule Blood Donation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="donationForm">
                    <div class="mb-3">
                        <label for="bloodBankSelect" class="form-label">Blood Bank/Hospital</label>
                        <select id="bloodBankSelect" class="form-select" required>
                            <option value="">Select Blood Bank</option>
                            @foreach($bloodBanks ?? [] as $bank)
                                <option value="{{ $bank->id }}">{{ $bank->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="requestSelect" class="form-label">For Specific Request (Optional)</label>
                        <select id="requestSelect" class="form-select">
                            <option value="">Donate to General Inventory</option>
                            @foreach($compatibleRequests ?? [] as $request)
                                <option value="{{ $request->id }}">{{ $request->blood_type }} - {{ $request->hospital_name }} - {{ $request->urgency }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="donationDate" class="form-label">Donation Date</label>
                        <div class="bloodbank-date-input">
                            <div class="input-group">
                                <input type="date" class="form-control" id="donationDate" required>
                                <span class="input-group-text">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                            <div class="form-text">Select your preferred donation date</div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="donationUnits" class="form-label">Units to Donate (1 unit = ~470ml)</label>
                        <select id="donationUnits" class="form-select" required>
                            <option value="1">1 Unit</option>
                            <option value="2">2 Units</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="scheduleDonation" class="btn btn-primary">Schedule Donation</button>
            </div>
        </div>
    </div>
</div>

<!-- Request Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1" aria-labelledby="responseModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="responseModalLabel">Respond to Blood Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="card bg-light mb-3">
                    <div class="card-body">
                        <h6 class="card-title">Request Details</h6>
                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <p class="small mb-1">Blood Type:</p>
                                <strong id="responseBloodType">A+</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Units Needed:</p>
                                <strong id="responseUnitsNeeded">2</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Hospital:</p>
                                <strong id="responseHospital">City Hospital</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Address:</p>
                                <strong id="responseAddress">123 Main St, City</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Contact:</p>
                                <strong id="responseContact">123-456-7890</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Urgency:</p>
                                <strong id="responseUrgency">Urgent</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Needed By:</p>
                                <strong id="responseNeededBy">Feb 15, 2025</strong>
                            </div>
                        </div>
                    </div>
                </div>
                <form id="responseForm">
                    <input type="hidden" id="responseRequestId" value="">
                    <div class="mb-3">
                        <label for="responseDonationDate" class="form-label">When can you donate?</label>
                        <div class="bloodbank-date-input">
                            <div class="input-group">
                                <input type="date" class="form-control" id="responseDonationDate" required>
                                <span class="input-group-text">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                            <div class="form-text">Select your preferred donation date</div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="responseUnits" class="form-label">Units to Donate (1 unit = ~470ml)</label>
                        <select id="responseUnits" class="form-select" required>
                            <option value="1">1 Unit</option>
                            <option value="2">2 Units</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="submitResponse" class="btn btn-primary">Submit Response</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment.min.js"></script>
<script>
    $(document).ready(function() {
        // Define global variable to check authenticated state
        const isAuthenticated = 1;//{{ Auth::check() ? 'true' : 'false' }};
        
        // Load dashboard stats
        loadDashboardStats();
        
        // Event Listeners
        $('#respondToEmergency').on('click', handleEmergencyResponse);
        $('#scheduleDonation').on('click', handleScheduleDonation);
        $('.respond-to-request').on('click', function() {
            const requestId = $(this).data('id');
            handleRequestResponse(requestId);
        });
        $('#submitResponse').on('click', handleSubmitResponse);
        
        // Blood request form validation
        $('#donationForm').on('submit', function(e) {
            e.preventDefault();
            handleScheduleDonation();
        });
        
        // Load dashboard statistics
        function loadDashboardStats() {
            axios.get(`${base_url}/webapi/bloodbank/dashboard-stats`)
                .then(response => {
                    if (response.data.code === 200) {
                        const stats = response.data.data;
                        updateBloodAvailability(stats.blood_availability);
                        updateEmergencyRequests(stats.emergency_request);
                        updateRecentRequests(stats.recent_requests);
                        updateUpcomingDrives(stats.upcoming_drives);
                        if (stats.user_stats) {
                            updateUserStats(stats.user_stats);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading dashboard stats:', error);
                });
        }
        
        // Update blood availability display
        function updateBloodAvailability(availability) {
            for (const [bloodType, data] of Object.entries(availability)) {
                const statusClass = data.status === 'critical' ? 'danger' : 
                                  data.status === 'low' ? 'warning' : 'success';
                
                $(`#availability-${bloodType.replace('+', 'pos').replace('-', 'neg')} .units-count`)
                    .text(data.units)
                    .removeClass('text-success text-warning text-danger')
                    .addClass(`text-${statusClass}`);
            }
        }
        
        // Update emergency requests section
        function updateEmergencyRequests(emergency) {
            if (!emergency) {
                $('#emergencyBanner').hide();
                return;
            }
            
            $('#emergencyBanner').show();
            $('#emergencyBloodType').text(emergency.blood_type);
            $('#emergencyHospital').text(emergency.hospital_name);
            $('#emergencyContact').text(emergency.contact_phone);
            $('#emergencyRequestId').val(emergency.id);
        }
        
        // Update recent requests section
        function updateRecentRequests(requests) {
            const container = $('#recentRequests');
            container.empty();
            
            if (requests.length === 0) {
                container.append(`
                    <div class="p-3 text-center">
                        <p class="text-muted mb-0">No recent blood requests</p>
                    </div>
                `);
                return;
            }
            
            requests.forEach(request => {
                const urgencyBadge = request.urgency === 'emergency' ? 'danger' : 
                                   request.urgency === 'urgent' ? 'warning' : 'primary';
                
                container.append(`
                    <div class="p-3 border-bottom">
                        <div class="d-flex">
                            <div class="icon-md bg-danger bg-opacity-10 rounded-circle text-danger me-3">
                                <span class="fw-bold">${request.blood_type}</span>
                            </div>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <h6 class="mb-0">${request.reason || 'Blood Requirement'}</h6>
                                    <span class="badge bg-${urgencyBadge}">${request.urgency_label}</span>
                                </div>
                                <p class="text-muted small mb-2">${request.units_needed} units needed at ${request.hospital_name}</p>
                                <div class="d-flex align-items-center text-muted small">
                                    <i class="fas fa-map-marker-alt me-2"></i>
                                    <span>${request.distance ? request.distance.toFixed(1) + ' km away' : 'Location unavailable'}</span>
                                    <span class="mx-2">•</span>
                                    <i class="fas fa-clock me-2"></i>
                                    <span>Posted ${moment(request.created_at).fromNow()}</span>
                                </div>
                            </div>
                            <button class="btn btn-sm btn-primary ms-3 respond-to-request" data-id="${request.id}">
                                Respond
                            </button>
                        </div>
                    </div>
                `);
            });
            
            // Add event listener to respond buttons
            $('.respond-to-request').on('click', function() {
                const requestId = $(this).data('id');
                handleRequestResponse(requestId);
            });
        }
        
        // Update upcoming drives section
        function updateUpcomingDrives(drives) {
            const container = $('#upcomingDrives');
            container.empty();
            
            if (drives.length === 0) {
                container.append(`
                    <div class="text-center py-3">
                        <p class="text-muted mb-0">No upcoming blood drives</p>
                    </div>
                `);
                return;
            }
            
            drives.forEach(drive => {
                const startDate = moment(drive.start_datetime).format('MMMM D, YYYY');
                const startTime = moment(drive.start_datetime).format('h:mm A');
                const endTime = moment(drive.end_datetime).format('h:mm A');
                const registeredCount = drive.registrations_count || 0;
                
                container.append(`
                    <div class="card bg-light border-0 rounded-3 mb-3">
                        <div class="card-body">
                            <div class="d-flex align-items-center mb-3">
                                <div class="icon-md bg-primary bg-opacity-10 rounded-circle text-primary me-3">
                                    <i class="fas fa-calendar-alt"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">${drive.title}</h6>
                                    <p class="text-muted small mb-0">
                                        ${startDate} • ${startTime} - ${endTime}
                                    </p>
                                </div>
                                <a href="{{ route('bloodbank.drives') }}/${drive.id}" class="btn btn-sm btn-primary">
                                    Details
                                </a>
                            </div>
                            <div class="d-flex align-items-center text-muted small">
                                <i class="fas fa-map-marker-alt me-2"></i>
                                <span>${drive.location}</span>
                                <span class="mx-2">•</span>
                                <i class="fas fa-user-friends me-2"></i>
                                <span>${registeredCount} registered</span>
                            </div>
                        </div>
                    </div>
                `);
            });
        }
        
        // Update user stats section
        function updateUserStats(stats) {
            if (!stats) return;
            
            if (stats.is_donor) {
                $('#donorStatus').text('Donor');
                $('#donorStatusBadge').removeClass('bg-secondary').addClass('bg-success');
            } else {
                $('#donorStatus').text('Not a Donor');
                $('#donorStatusBadge').removeClass('bg-success').addClass('bg-secondary');
            }
            
            $('#userBloodType').text(stats.blood_type || 'Not set');
            $('#donationCount').text(stats.donation_count || '0');
            
            if (stats.last_donation_date) {
                $('#lastDonationDate').text(moment(stats.last_donation_date).format('MMMM D, YYYY'));
                $('#daysSinceLastDonation').text(stats.days_since_last_donation);
            } else {
                $('#lastDonationDate').text('Never');
                $('#daysSinceLastDonation').text('N/A');
            }
            
            if (stats.is_eligible_to_donate) {
                $('#eligibilityStatus').text('Eligible to donate').addClass('text-success').removeClass('text-danger');
            } else {
                $('#eligibilityStatus').text('Not eligible until ' + moment(stats.eligible_date).format('MMMM D, YYYY'))
                    .addClass('text-danger').removeClass('text-success');
            }
        }
        
        // Handle emergency response
        function handleEmergencyResponse() {
            const requestId = $('#emergencyRequestId').val();
            if (!requestId) return;
            
            // Check if user is logged in
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            
            // Load request details and show response modal
            handleRequestResponse(requestId);
        }
        
        // Handle request response
        function handleRequestResponse(requestId) {
            // Check if user is logged in
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            
            // Get request details
            axios.get(`${base_url}/webapi/bloodbank/requests/${requestId}`)
                .then(response => {
                    if (response.data.code === 200) {
                        const request = response.data.data;
                        
                        // Display response modal
                        $('#responseModal').modal('show');
                        $('#responseRequestId').val(requestId);
                        $('#responseBloodType').text(request.blood_type);
                        $('#responseUnitsNeeded').text(request.units_needed);
                        $('#responseHospital').text(request.hospital_name);
                        $('#responseAddress').text(request.hospital_address);
                        $('#responseContact').text(request.contact_phone);
                        $('#responseUrgency').text(request.urgency_label);
                        $('#responseNeededBy').text(moment(request.needed_by).format('MMMM D, YYYY'));
                    }
                })
                .catch(error => {
                    console.error('Error getting request details:', error);
                    showError('Error loading request details. Please try again.');
                });
        }
        
        // Handle submit response to a request
        function handleSubmitResponse() {
            const requestId = $('#responseRequestId').val();
            const donationDate = $('#responseDonationDate').val();
            const units = $('#responseUnits').val();
            
            if (!requestId || !donationDate || !units) {
                showError('Please fill all required fields');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#submitResponse');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Submitting...').prop('disabled', true);
            
            // Submit response
            axios.post(`${base_url}/webapi/bloodbank/requests/${requestId}/respond`, {
                units: units,
                donation_date: donationDate
            })
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Response submitted successfully');
                    $('#responseModal').modal('hide');
                    $('#responseForm').trigger('reset');
                    
                    // Reload dashboard stats
                    loadDashboardStats();
                }
            })
            .catch(error => {
                console.error('Error submitting response:', error);
                showError(error.response?.data?.message || 'Error submitting response. Please try again.');
            })
            .finally(() => {
                submitBtn.html(originalText).prop('disabled', false);
            });
        }
        
        // Handle scheduling a donation
        function handleScheduleDonation() {
            // Check if user is logged in
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            
            // Validate form
            const bloodBankId = $('#bloodBankSelect').val();
            const requestId = $('#requestSelect').val();
            const donationDate = $('#donationDate').val();
            const units = $('#donationUnits').val();
            
            if (!bloodBankId) {
                showError('Please select a blood bank');
                return;
            }
            
            if (!donationDate) {
                showError('Please select a donation date');
                return;
            }
            
            if (!units) {
                showError('Please specify the number of units');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#scheduleDonation');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Scheduling...').prop('disabled', true);
            
            // Submit donation schedule
            axios.post(`${base_url}/webapi/bloodbank/donations/schedule`, {
                blood_bank_id: bloodBankId,
                request_id: requestId || null,
                donation_date: donationDate,
                units: units
            })
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Donation scheduled successfully');
                    $('#donationModal').modal('hide');
                    $('#donationForm').trigger('reset');
                    
                    // Reload dashboard stats
                    loadDashboardStats();
                }
            })
            .catch(error => {
                console.error('Error scheduling donation:', error);
                showError(error.response?.data?.message || 'Error scheduling donation. Please try again.');
            })
            .finally(() => {
                submitBtn.html(originalText).prop('disabled', false);
            });
        }
        
        // Utility Functions
        function showLoginPrompt() {
            myAlert.fire({
                title: 'Login Required',
                text: 'Please login to perform this action',
                icon: 'info',
                showCancelButton: true,
                confirmButtonText: 'Login',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `${base_url}/login?redirect=${encodeURIComponent(window.location.href)}`;
                }
            });
        }
        
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
        
        // Initialize date picker
        initializeDonationDatePicker();
        
        // Date picker change handler
        $('#donationDate').on('change', function() {
            validateDonationDate();
        });
        
        // Initialize donation date picker
        function initializeDonationDatePicker() {
            const today = new Date();
            const maxDate = new Date();
            maxDate.setDate(today.getDate() + 90); // Maximum 90 days from today
            
            const donationDateInput = $('#donationDate');
            donationDateInput.attr('min', today.toISOString().split('T')[0]);
            donationDateInput.attr('max', maxDate.toISOString().split('T')[0]);
            
            // Set default date to a week from today
            const nextWeek = new Date();
            nextWeek.setDate(today.getDate() + 7);
            donationDateInput.val(nextWeek.toISOString().split('T')[0]);
        }
        
        // Validate donation date
        function validateDonationDate() {
            const selectedDate = new Date($('#donationDate').val());
            const today = new Date();
            const maxDate = new Date();
            maxDate.setDate(today.getDate() + 90);
            
            if (selectedDate < today) {
                showError('Please select a future date for donation');
                $('#donationDate').val('');
                return false;
            }
            
            if (selectedDate > maxDate) {
                showError('Please select a date within 90 days from today');
                $('#donationDate').val('');
                return false;
            }
            
            return true;
        }

        // Initialize tooltips
        $('[data-bs-toggle="tooltip"]').tooltip();
        
        // Load blood banks for donation modal
        function loadBloodBanks() {
            axios.get(`${base_url}/webapi/bloodbank/banks`)
                .then(response => {
                    if (response.data.code === 200) {
                        const banks = response.data.data;
                        const select = $('#bloodBankSelect');
                        select.find('option:not(:first)').remove();
                        
                        banks.forEach(bank => {
                            select.append(`<option value="${bank.id}">${bank.name}</option>`);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading blood banks:', error);
                });
        }
        
        // Load compatible requests for donation modal
        function loadCompatibleRequests() {
            axios.get(`${base_url}/webapi/bloodbank/compatible-requests`)
                .then(response => {
                    if (response.data.code === 200) {
                        const requests = response.data.data;
                        const select = $('#requestSelect');
                        select.find('option:not(:first)').remove();
                        
                        if (requests.length === 0) {
                            select.append(`<option disabled>No compatible requests found</option>`);
                            return;
                        }
                        
                        requests.forEach(request => {
                            const urgency = request.urgency === 'emergency' ? '🔴 EMERGENCY' : 
                                          request.urgency === 'urgent' ? '🟠 Urgent' : 'Normal';
                                          
                            select.append(`<option value="${request.id}">${request.blood_type} - ${urgency} - ${request.hospital_name}</option>`);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading compatible requests:', error);
                });
        }
        
        // When donation modal opens, load blood banks and compatible requests
        $('#donationModal').on('show.bs.modal', function() {
            if (isAuthenticated) {
                loadBloodBanks();
                loadCompatibleRequests();
            }
        });
        
        // Load nearby donors if authenticated
        function loadNearbyDonors() {
            if (!isAuthenticated) return;
            
            axios.get(`${base_url}/webapi/bloodbank/donors/nearby?distance=10`)
                .then(response => {
                    if (response.data.code === 200) {
                        const donors = response.data.data;
                        const container = $('#nearbyDonors');
                        container.empty();
                        
                        if (donors.length === 0) {
                            container.append(`
                                <div class="text-center py-3">
                                    <p class="text-muted mb-0">No nearby donors found</p>
                                    <a href="{{ route('bloodbank.profile') }}" class="btn btn-sm btn-primary mt-2">Update Your Location</a>
                                </div>
                            `);
                            return;
                        }
                        
                        const donorsHtml = `<div class="row g-3">
                            ${donors.map(donor => {
                                const lastDonated = donor.last_donation_date ? 
                                    `Last donated: ${moment(donor.last_donation_date).fromNow()}` : 
                                    'No previous donations';
                                    
                                return `
                                <div class="col-md-6">
                                    <div class="card h-100 border">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-3">
                                                <div class="avatar avatar-md me-3">
                                                    ${donor.avatar ? 
                                                        `<img src="${base_url}/storage/${donor.avatar}" class="rounded-circle" alt="${donor.name}">` :
                                                        `<div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
                                                            ${donor.name.charAt(0).toUpperCase()}
                                                        </div>`
                                                    }
                                                </div>
                                                <div>
                                                    <h6 class="mb-1">${donor.name}</h6>
                                                    <div>
                                                        <span class="badge bg-primary me-2">${donor.blood_type}</span>
                                                        <span class="badge bg-light text-dark">${lastDonated}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center text-muted small mb-3">
                                                <i class="fas fa-map-marker-alt me-2"></i>
                                                <span>${donor.distance.toFixed(1)} km away</span>
                                                ${donor.donation_count > 0 ? `
                                                    <span class="mx-2">•</span>
                                                    <i class="fas fa-trophy me-2"></i>
                                                    <span>${donor.donation_count} donations</span>
                                                ` : ''}
                                            </div>
                                            <div class="d-flex gap-2">
                                                ${donor.phone ? `
                                                    <a href="tel:${donor.phone}" class="btn btn-sm btn-primary flex-grow-1">
                                                        <i class="fas fa-phone me-2"></i>Contact
                                                    </a>
                                                ` : ''}
                                                <a href="${base_url}/profile/view/${donor.id}" class="btn btn-sm btn-light">
                                                    <i class="fas fa-info-circle"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                `;
                            }).join('')}
                        </div>`;
                        
                        container.html(donorsHtml);
                    }
                })
                .catch(error => {
                    console.error('Error loading nearby donors:', error);
                    $('#nearbyDonors').html(`
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Error loading nearby donors. Please try again later.
                        </div>
                    `);
                });
        }
        
        // Load compatible blood types info
        function loadCompatibilityChart() {
            const compatibility = {
                'O-': ['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'],
                'O+': ['O+', 'A+', 'B+', 'AB+'],
                'A-': ['A-', 'A+', 'AB-', 'AB+'],
                'A+': ['A+', 'AB+'],
                'B-': ['B-', 'B+', 'AB-', 'AB+'],
                'B+': ['B+', 'AB+'],
                'AB-': ['AB-', 'AB+'],
                'AB+': ['AB+']
            };
            
            // Display donor compatibility in tooltip
            $('.blood-type-info').each(function() {
                const bloodType = $(this).data('blood-type');
                if (compatibility[bloodType]) {
                    const compatibleWith = compatibility[bloodType].join(', ');
                    $(this).attr('title', `${bloodType} can donate to: ${compatibleWith}`);
                    $(this).attr('data-bs-toggle', 'tooltip');
                    $(this).attr('data-bs-placement', 'top');
                }
            });
            
            // Reinitialize tooltips
            $('[data-bs-toggle="tooltip"]').tooltip();
        }
        
        // Check for URL parameters on load
        function checkUrlParams() {
            const urlParams = new URLSearchParams(window.location.search);
            
            // Check if there's a request to respond to
            const requestId = urlParams.get('respond_to');
            if (requestId) {
                handleRequestResponse(requestId);
            }
            
            // Check if donation modal should be shown
            const showDonate = urlParams.get('donate');
            if (showDonate === '1' && isAuthenticated) {
                $('#donationModal').modal('show');
            }
        }
        
        // Initialize compatibility chart
        loadCompatibilityChart();
        
        // Load nearby donors if section exists
        if ($('#nearbyDonors').length > 0) {
            loadNearbyDonors();
        }
        
        // Check URL parameters
        checkUrlParams();
    });

    // Function to handle request response
</script>
@endsection