@extends('front_end.layouts.home')

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

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

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- 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="{{ route('bloodbank.index') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Donate Blood</h4>
                                    <p class="mb-0 text-white">Schedule a blood donation and save lives</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Eligibility Status -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Your Donation Eligibility</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center mb-3">
                            <div class="icon-md bg-{{ $isEligible ? 'success' : 'danger' }} bg-opacity-10 rounded-circle text-{{ $isEligible ? 'success' : 'danger' }} me-3">
                                <i class="fas fa-{{ $isEligible ? 'check' : 'times' }}"></i>
                            </div>
                            <div>
                                <h5 class="mb-1">{{ $isEligible ? 'You are eligible to donate' : 'You are not eligible to donate right now' }}</h5>
                                @if(!$isEligible && $nextEligibleDate)
                                <p class="mb-0 text-muted">You will be eligible from {{ $nextEligibleDate->format('F d, Y') }}</p>
                                @endif
                            </div>
                        </div>
                        
                        @if(!Auth::user()->blood_type)
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Please set your blood type</strong>
                            <p class="mb-0 small">Please update your donor profile to include your blood type before scheduling a donation.</p>
                        </div>
                        @endif
                        
                        <div class="mb-4">
                            <h6 class="mb-2">Your Details</h6>
                            <div class="row g-3">
                                <div class="col-6">
                                    <div class="card bg-light border-0 h-100">
                                        <div class="card-body p-3">
                                            <h6 class="card-title small text-muted">Blood Type</h6>
                                            <p class="mb-0 fw-bold">{{ Auth::user()->blood_type ?: 'Not set' }}</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="card bg-light border-0 h-100">
                                        <div class="card-body p-3">
                                            <h6 class="card-title small text-muted">Last Donation</h6>
                                            <p class="mb-0">{{ Auth::user()->last_donation_date ? Auth::user()->last_donation_date->format('M d, Y') : 'Never' }}</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="card bg-light border-0 h-100">
                                        <div class="card-body p-3">
                                            <h6 class="card-title small text-muted">Total Donations</h6>
                                            <p class="mb-0">{{ Auth::user()->donation_count ?: '0' }}</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="card bg-light border-0 h-100">
                                        <div class="card-body p-3">
                                            <h6 class="card-title small text-muted">Days Since Last</h6>
                                            <p class="mb-0">{{ Auth::user()->days_since_last_donation ?: 'N/A' }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <a href="{{ route('bloodbank.profile') }}" class="btn btn-outline-primary">
                                <i class="fas fa-user me-2"></i>Update Donor Profile
                            </a>
                            @if($isEligible && Auth::user()->blood_type)
                            <button id="scheduleNowBtn" class="btn btn-primary">
                                <i class="fas fa-calendar-plus me-2"></i>Schedule Now
                            </button>
                            @endif
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <h6 class="mb-2">Eligibility Requirements</h6>
                        <div class="card bg-light border-0">
                            <div class="card-body">
                                <ul class="mb-0">
                                    <li>Must be between 17-65 years old</li>
                                    <li>Weight at least 50kg (110 lbs)</li>
                                    <li>In good health condition</li>
                                    <li>No alcohol consumption within 24 hours before donation</li>
                                    <li>No tattoos or piercings within the last 3 months</li>
                                    <li>Not donated blood in the last 56 days (8 weeks)</li>
                                    <li>Had adequate sleep and meals before donation</li>
                                    <li>Must not be on antibiotics or certain medications</li>
                                </ul>
                            </div>
                        </div>
                        
                        <h6 class="mb-2 mt-3">Did You Know?</h6>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            A single blood donation can save up to 3 lives!
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Donation Scheduling -->
            <div class="col-lg-8">
                <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">Schedule a Donation</h5>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="showCompatibleOnly" checked>
                            <label class="form-check-label small" for="showCompatibleOnly">Show compatible requests only</label>
                        </div>
                    </div>
                    <div class="card-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 {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                    <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" {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                    <option value="">Donate to General Inventory</option>
                                    @foreach($compatibleRequests as $request)
                                        @php
                                            $urgencyLabel = $request->urgency == 'emergency' ? '🔴 EMERGENCY' : ($request->urgency == 'urgent' ? '🟠 Urgent' : 'Normal');
                                        @endphp
                                        <option value="{{ $request->id }}">{{ $request->blood_type }} - {{ $urgencyLabel }} - {{ $request->hospital_name }}</option>
                                    @endforeach
                                </select>
                                <div class="form-text">Your blood type {{ Auth::user()->blood_type }} is compatible with the requests shown above.</div>
                            </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 {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                        <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 {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                    <option value="1">1 Unit</option>
                                    <option value="2">2 Units</option>
                                </select>
                                <div class="form-text">Most donations are 1 unit. Please consult with the blood bank staff if you're considering donating 2 units.</div>
                            </div>
                            
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="donationTerms" required {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                <label class="form-check-label" for="donationTerms">
                                    I confirm that I meet all eligibility requirements and the information provided is correct.
                                </label>
                            </div>
                            
                            <button type="submit" id="scheduleDonation" class="btn btn-primary" {{ !$isEligible || !Auth::user()->blood_type ? 'disabled' : '' }}>
                                <i class="fas fa-calendar-check me-2"></i>Schedule Donation
                            </button>
                        </form>
                    </div>
                </div>
                
                <!-- Blood Request Details (initially hidden) -->
                <div id="requestDetailsCard" class="card border-0 shadow-sm rounded-3 mb-4" style="display: none;">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Request Details</h5>
                    </div>
                    <div class="card-body" id="requestDetails">
                        <!-- Request details will be loaded here via JavaScript -->
                    </div>
                </div>
            </div>
            
            <!-- Upcoming Donations & History -->
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm rounded-3 mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Upcoming Donations</h5>
                    </div>
                    <div class="card-body p-0">
                        @if(count($donationHistory->where('status', 'scheduled')->where('donation_date', '>=', now())) > 0)
                            <div class="list-group list-group-flush">
                                @foreach($donationHistory->where('status', 'scheduled')->where('donation_date', '>=', now())->sortBy('donation_date') as $donation)
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0">{{ $donation->bloodBank ? $donation->bloodBank->name : 'Unknown Blood Bank' }}</h6>
                                        <span class="badge bg-info">{{ \Carbon\Carbon::parse($donation->donation_date)->format('M d, Y') }}</span>
                                    </div>
                                    <p class="small text-muted mb-2">
                                        {{ $donation->blood_type }} • {{ $donation->units }} unit(s)
                                        @if($donation->request)
                                        • For: {{ Str::limit($donation->request->reason ?: 'Blood Request', 30) }}
                                        @endif
                                    </p>
                                    <div>
                                        <button class="btn btn-sm btn-outline-danger cancel-donation" data-id="{{ $donation->id }}">
                                            <i class="fas fa-times-circle me-1"></i>Cancel
                                        </button>
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-4">
                                <p class="text-muted mb-0">No upcoming donations</p>
                            </div>
                        @endif
                    </div>
                </div>
                
                <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">Donation History</h5>
                        <a href="{{ route('bloodbank.profile') }}" class="btn btn-sm btn-outline-primary">View All</a>
                    </div>
                    <div class="card-body p-0">
                        @if(count($donationHistory->where('status', 'completed')) > 0)
                            <div class="list-group list-group-flush">
                                @foreach($donationHistory->where('status', 'completed')->take(5) as $donation)
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <h6 class="mb-0">{{ $donation->bloodBank ? $donation->bloodBank->name : 'Unknown Blood Bank' }}</h6>
                                        <span class="badge bg-success">{{ \Carbon\Carbon::parse($donation->donation_date)->format('M d, Y') }}</span>
                                    </div>
                                    <p class="small text-muted mb-0">
                                        {{ $donation->blood_type }} • {{ $donation->units }} unit(s)
                                        @if($donation->request)
                                        • For: {{ Str::limit($donation->request->reason ?: 'Blood Request', 30) }}
                                        @endif
                                    </p>
                                </div>
                                @endforeach
                            </div>
                        @else
                            <div class="text-center py-4">
                                <p class="text-muted mb-0">No donation history</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cancellation Modal -->
<div class="modal fade" id="cancellationModal" tabindex="-1" aria-labelledby="cancellationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancellationModalLabel">Cancel Donation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Are you sure you want to cancel this donation?</strong>
                </div>
                <p>Please consider rescheduling instead if possible.</p>
                <input type="hidden" id="cancelDonationId" value="">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Keep Donation</button>
                <button type="button" id="confirmCancellation" class="btn btn-danger">Cancel Donation</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('extra-js')
<script>
    $(document).ready(function() {
        // Donation form submission
        $('#donationForm').on('submit', function(e) {
            e.preventDefault();
            scheduleDonation();
        });
        
        // Schedule Now button
        $('#scheduleNowBtn').on('click', function() {
            $('html, body').animate({
                scrollTop: $('#donationForm').offset().top - 100
            }, 500);
        });
        
        // Cancel donation buttons
        $('.cancel-donation').on('click', function() {
            const donationId = $(this).data('id');
            $('#cancelDonationId').val(donationId);
            $('#cancellationModal').modal('show');
        });
        
        // Confirm cancellation
        $('#confirmCancellation').on('click', function() {
            const donationId = $('#cancelDonationId').val();
            
            // Show loading state
            const submitBtn = $('#confirmCancellation');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Cancelling...').prop('disabled', true);
            
            // Submit cancellation
            axios.post(`${base_url}/webapi/bloodbank/donations/${donationId}/cancel`)
                .then(response => {
                    if (response.data.code === 200) {
                        showSuccess('Donation cancelled successfully');
                        $('#cancellationModal').modal('hide');
                        
                        // Reload page after a brief delay
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    }
                })
                .catch(error => {
                    console.error('Error cancelling donation:', error);
                    showError(error.response?.data?.message || 'Error cancelling donation. Please try again.');
                })
                .finally(() => {
                    submitBtn.html(originalText).prop('disabled', false);
                });
        });
        
        // Show request details when a request is selected
        $('#requestSelect').on('change', function() {
            const requestId = $(this).val();
            
            // Hide request details if no request selected
            if (!requestId) {
                $('#requestDetailsCard').hide();
                return;
            }
            
            // Show loading in request details
            $('#requestDetailsCard').show();
            $('#requestDetails').html(`
                <div class="text-center py-3">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <span class="ms-2">Loading request details...</span>
                </div>
            `);
            
            // Fetch request details
            axios.get(`${base_url}/webapi/bloodbank/requests/${requestId}`)
                .then(response => {
                    if (response.data.code === 200) {
                        const request = response.data.data;
                        displayRequestDetails(request);
                    }
                })
                .catch(error => {
                    console.error('Error loading request details:', error);
                    $('#requestDetails').html(`
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Error loading request details. Please try again.
                        </div>
                    `);
                });
        });
        
        // Display request details
        function displayRequestDetails(request) {
            const urgencyBadge = request.urgency === 'emergency' ? 'danger' : 
                               request.urgency === 'urgent' ? 'warning' : 'primary';
            
            const donationProgress = Math.min(100, (request.donations_count / request.units_needed) * 100);
            
            const html = `
                <div class="d-flex align-items-center mb-3">
                    <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">
                            <h5 class="mb-0">${request.reason || 'Blood Requirement'}</h5>
                            <span class="badge bg-${urgencyBadge}">${request.urgency_label}</span>
                        </div>
                        <p class="text-muted small mb-0">
                            ${request.units_needed} units needed at ${request.hospital_name}
                        </p>
                    </div>
                </div>
                
                <div class="row g-3 mb-3">
                    <div class="col-md-6">
                        <div class="card bg-light border-0 h-100">
                            <div class="card-body p-3">
                                <h6 class="card-title small text-muted">Contact Information</h6>
                                <p class="mb-0">
                                    <i class="fas fa-phone me-2"></i>${request.contact_phone}
                                </p>
                                ${request.user.email ? `
                                <p class="mb-0 small">
                                    <i class="fas fa-envelope me-2"></i>${request.user.email}
                                </p>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card bg-light border-0 h-100">
                            <div class="card-body p-3">
                                <h6 class="card-title small text-muted">Timeline</h6>
                                <p class="mb-0">
                                    <i class="fas fa-calendar me-2"></i>Needed by: ${moment(request.needed_by).format('MMM D, YYYY')}
                                </p>
                                <p class="mb-0 small text-${moment(request.needed_by).isBefore(moment()) ? 'danger' : 'success'}">
                                    ${moment(request.needed_by).fromNow()}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mb-3">
                    <h6 class="mb-2">Donation Progress</h6>
                    <div class="d-flex align-items-center mb-2">
                        <div class="progress flex-grow-1" style="height: 10px;">
                            <div class="progress-bar bg-success" role="progressbar" style="width: ${donationProgress}%" aria-valuenow="${donationProgress}" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <span class="ms-2 text-muted">${request.donations_count}/${request.units_needed} units</span>
                    </div>
                    <p class="small text-muted mb-0">
                        ${request.units_needed - request.donations_count} more units needed
                    </p>
                </div>
                
                <div class="alert alert-info mb-0">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Your donation matters!</strong>
                    <p class="mb-0 small">By donating to this specific request, you are directly helping someone in need.</p>
                </div>
            `;
            
            $('#requestDetails').html(html);
        }
        
        // Schedule donation
        function scheduleDonation() {
            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 (!$('#donationTerms').is(':checked')) {
                showError('Please confirm that you meet the eligibility requirements');
                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');
                    
                    // Reload page after a brief delay
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            })
            .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);
            });
        }
        
        // Show/hide compatible requests only
        $('#showCompatibleOnly').on('change', function() {
            const showCompatible = $(this).is(':checked');
            
            // Reload requests based on filter
            if (showCompatible) {
                // Show only compatible requests (already loaded)
            } else {
                // Show all requests (need to load)
                loadAllRequests();
            }
        });
        
        // Load all blood requests regardless of compatibility
        function loadAllRequests() {
            // Only load if checkbox is unchecked
            if ($('#showCompatibleOnly').is(':checked')) {
                return;
            }
            
            // Show loading in select
            const select = $('#requestSelect');
            select.html('<option value="">Loading all requests...</option>').prop('disabled', true);
            
            // Fetch all active requests
            axios.get(`${base_url}/webapi/bloodbank/requests?status=pending,in_progress`)
                .then(response => {
                    if (response.data.code === 200) {
                        const requests = response.data.data;
                        
                        select.html('<option value="">Donate to General Inventory</option>');
                        
                        if (requests.length === 0) {
                            select.append('<option disabled>No active requests found</option>');
                        } else {
                            requests.forEach(request => {
                                const urgencyLabel = request.urgency === 'emergency' ? '🔴 EMERGENCY' : 
                                                   request.urgency === 'urgent' ? '🟠 Urgent' : 'Normal';
                                                   
                                const isCompatible = isBloodCompatible(
                                    '{{ Auth::user()->blood_type }}', 
                                    request.blood_type
                                );
                                
                                select.append(`
                                    <option value="${request.id}" ${!isCompatible ? 'class="text-muted"' : ''}>
                                        ${request.blood_type} - ${urgencyLabel} - ${request.hospital_name}
                                        ${!isCompatible ? ' (Not compatible)' : ''}
                                    </option>
                                `);
                            });
                            
                            select.prop('disabled', false);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading all requests:', error);
                    select.html('<option value="">Error loading requests</option>');
                    setTimeout(() => {
                        select.html('<option value="">Donate to General Inventory</option>');
                        select.prop('disabled', false);
                    }, 2000);
                });
        }
        
        // Check blood type compatibility
        function isBloodCompatible(donorType, recipientType) {
            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+']
            };
            
            if (!donorType || !recipientType || !compatibility[donorType]) {
                return false;
            }
            
            return compatibility[donorType].includes(recipientType);
        }
        
        // Utility Functions
        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;
            }
            
            // Show days from today and update UI
            const timeDiff = selectedDate.getTime() - today.getTime();
            const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
            
            // Remove existing classes and hints
            $('#donationDate').removeClass('border-warning border-info');
            $('.donation-hint').remove();
            
            // Add visual indicators for donation timing
            if (daysDiff >= 1 && daysDiff <= 3) {
                $('#donationDate').addClass('border-warning');
                addDonationHint('warning', `📅 Donation scheduled for ${daysDiff} day(s) from today - Please ensure availability`);
            } else if (daysDiff >= 4 && daysDiff <= 7) {
                $('#donationDate').addClass('border-info');
                addDonationHint('info', `📅 Donation scheduled for ${daysDiff} day(s) from today - Good timing`);
            }
            
            return true;
        }
        
        // Add donation hint below the date input
        function addDonationHint(type, message) {
            const hintClass = type === 'warning' ? 'text-warning' : 'text-info';
            const hintHtml = `<div class="donation-hint mt-1"><small class="${hintClass}"><i class="fas fa-info-circle me-1"></i>${message}</small></div>`;
            $('#donationDate').closest('.bloodbank-date-input').append(hintHtml);
        }
        

    });
</script>
@endsection