@extends('front_end.layouts.home')

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

@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">Donor Profile</h4>
                                    <p class="mb-0 text-white">Manage your blood donation profile and history</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Profile Summary -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Your Donor Profile</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex align-items-center mb-4">
                            <div class="avatar avatar-lg me-1">
                                @if($user->avatar)
                                    <img src="{{ asset($user->avatar) }}" class="rounded-circle" alt="{{ $user->name }}">
                                @else
                                    <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        {{ strtoupper(substr($user->name, 0, 1)) }}
                                    </div>
                                @endif
                            </div>
                            <div>
                                <h5 class="mb-1">{{ $user->name }}</h5>
                                <p class="mb-0 text-muted">Member since {{ \Carbon\Carbon::parse($user->created_at)->format('F Y') }}</p>
                            </div>
                        </div>
                        
                        <form id="donorProfileForm">
                            <div class="mb-3">
                                <label for="bloodType" class="form-label">Your Blood Type</label>
                                <select id="bloodType" class="form-select" required>
                                    <option value="">Select Blood Type</option>
                                    <option value="A+" {{ $user->blood_type == 'A+' ? 'selected' : '' }}>A+</option>
                                    <option value="A-" {{ $user->blood_type == 'A-' ? 'selected' : '' }}>A-</option>
                                    <option value="B+" {{ $user->blood_type == 'B+' ? 'selected' : '' }}>B+</option>
                                    <option value="B-" {{ $user->blood_type == 'B-' ? 'selected' : '' }}>B-</option>
                                    <option value="AB+" {{ $user->blood_type == 'AB+' ? 'selected' : '' }}>AB+</option>
                                    <option value="AB-" {{ $user->blood_type == 'AB-' ? 'selected' : '' }}>AB-</option>
                                    <option value="O+" {{ $user->blood_type == 'O+' ? 'selected' : '' }}>O+</option>
                                    <option value="O-" {{ $user->blood_type == 'O-' ? 'selected' : '' }}>O-</option>
                                </select>
                                <div class="form-text">Your blood type is essential for matching with compatible recipients</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="isDonor" {{ $user->is_donor ? 'checked' : '' }}>
                                    <label class="form-check-label" for="isDonor">
                                        I want to be a blood donor
                                    </label>
                                </div>
                                <div class="form-text">You can receive notifications about blood donation opportunities</div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="showAsDonor" {{ $user->show_as_donor ? 'checked' : '' }}>
                                    <label class="form-check-label" for="showAsDonor">
                                        Show me in nearby donors list
                                    </label>
                                </div>
                                <div class="form-text">Other users can see you as a potential donor based on your location</div>
                            </div>
                            
                            @if(setting('google_map_enabled'))
                            <h6 class="mt-4 mb-3">Your Location</h6>
                            <div class="alert alert-info mb-3">
                                <i class="fas fa-info-circle me-2"></i>
                                <span>Your location helps us match you with nearby blood requests and blood drives</span>
                            </div>
                            
                            <div class="mb-3">
                                <div id="locationMap" style="height: 200px; border-radius: 0.5rem;" class="mb-2"></div>
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label for="latitude" class="form-label">Latitude</label>
                                        <input type="text" class="form-control" id="latitude" value="{{ $user->latitude }}" readonly>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="longitude" class="form-label">Longitude</label>
                                        <input type="text" class="form-control" id="longitude" value="{{ $user->longitude }}" readonly>
                                    </div>
                                </div>
                                <button type="button" id="detectLocationBtn" class="btn btn-sm btn-outline-primary mt-2">
                                    <i class="fas fa-map-marker-alt me-2"></i>Detect My Location
                                </button>
                            </div>
                            @endif
                            
                            <div class="d-grid">
                                <button type="button" id="saveDonorProfile" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>Save Profile
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card border shadow-sm h-100">
                            <div class="card-header bg-transparent">
                                <h6 class="mb-0">Donation Statistics</h6>
                            </div>
                            <div class="card-body">
                                <div class="row g-3 mb-4">
                                    <div class="col-sm-6">
                                        <div class="card bg-light border-0 h-100">
                                            <div class="card-body p-3 text-center">
                                                <p class="text-muted small mb-1">Total Donations</p>
                                                <h3 class="mb-0">{{ $totalDonations }}</h3>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="card bg-light border-0 h-100">
                                            <div class="card-body p-3 text-center">
                                                <p class="text-muted small mb-1">Units Donated</p>
                                                <h3 class="mb-0">{{ $totalUnits }}</h3>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="text-center mb-4">
                                    @if($totalDonations > 0 && $user->last_donation_date)
                                        <div class="mb-2">
                                            <span class="badge bg-{{ $isEligible ? 'success' : 'danger' }} py-2 px-3">
                                                {{ $isEligible ? 'Eligible to donate' : 'Not eligible to donate' }}
                                            </span>
                                        </div>
                                        
                                        <p class="mb-0 small">Last donation: {{ \Carbon\Carbon::parse($user->last_donation_date)->format('F d, Y') }}</p>
                                        
                                                                                    @if(!$isEligible && $nextEligibleDate)
                                                <p class="mb-0 small">Next eligible date: {{ $nextEligibleDate->format('F d, Y') }}</p>
                                                @php
                                                    $totalDays = 56; // 8 weeks waiting period
                                                    $daysElapsed = min($totalDays, $user->days_since_last_donation);
                                                    $progressPercentage = ($daysElapsed / $totalDays) * 100;
                                                @endphp
                                                <div class="progress mt-2" style="height: 6px;">
                                                    <div class="progress-bar bg-info" role="progressbar" style="width: {{ $progressPercentage }}%" aria-valuenow="{{ $progressPercentage }}" aria-valuemin="0" aria-valuemax="100"></div>
                                                </div>
                                                <p class="mt-1 mb-0 small text-muted">{{ $daysElapsed }} of {{ $totalDays }} days passed</p>
                                            @endif
                                    @else
                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <span>You haven't made any blood donations yet</span>
                                        </div>
                                    @endif
                                </div>
                                
                                <h6 class="mb-3">Blood Type Compatibility</h6>
                                @if($user->blood_type)
                                    <div class="table-responsive mb-3">
                                        <table class="table table-sm">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Your Blood Type</th>
                                                    <th>Can Donate To</th>
                                                    <th>Can Receive From</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>
                                                        <span class="badge bg-danger px-3 py-2">{{ $user->blood_type }}</span>
                                                    </td>
                                                    <td>
                                                        @php
                                                            $canDonateTo = [];
                                                            switch($user->blood_type) {
                                                                case 'O-':
                                                                    $canDonateTo = ['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'];
                                                                    break;
                                                                case 'O+':
                                                                    $canDonateTo = ['O+', 'A+', 'B+', 'AB+'];
                                                                    break;
                                                                case 'A-':
                                                                    $canDonateTo = ['A-', 'A+', 'AB-', 'AB+'];
                                                                    break;
                                                                case 'A+':
                                                                    $canDonateTo = ['A+', 'AB+'];
                                                                    break;
                                                                case 'B-':
                                                                    $canDonateTo = ['B-', 'B+', 'AB-', 'AB+'];
                                                                    break;
                                                                case 'B+':
                                                                    $canDonateTo = ['B+', 'AB+'];
                                                                    break;
                                                                case 'AB-':
                                                                    $canDonateTo = ['AB-', 'AB+'];
                                                                    break;
                                                                case 'AB+':
                                                                    $canDonateTo = ['AB+'];
                                                                    break;
                                                            }
                                                            
                                                            $canReceiveFrom = [];
                                                            switch($user->blood_type) {
                                                                case 'O-':
                                                                    $canReceiveFrom = ['O-'];
                                                                    break;
                                                                case 'O+':
                                                                    $canReceiveFrom = ['O-', 'O+'];
                                                                    break;
                                                                case 'A-':
                                                                    $canReceiveFrom = ['O-', 'A-'];
                                                                    break;
                                                                case 'A+':
                                                                    $canReceiveFrom = ['O-', 'O+', 'A-', 'A+'];
                                                                    break;
                                                                case 'B-':
                                                                    $canReceiveFrom = ['O-', 'B-'];
                                                                    break;
                                                                case 'B+':
                                                                    $canReceiveFrom = ['O-', 'O+', 'B-', 'B+'];
                                                                    break;
                                                                case 'AB-':
                                                                    $canReceiveFrom = ['O-', 'A-', 'B-', 'AB-'];
                                                                    break;
                                                                case 'AB+':
                                                                    $canReceiveFrom = ['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'];
                                                                    break;
                                                            }
                                                        @endphp
                                                        
                                                        @foreach($canDonateTo as $type)
                                                            <span class="badge bg-success me-1 mb-1">{{ $type }}</span>
                                                        @endforeach
                                                    </td>
                                                    <td>
                                                        @foreach($canReceiveFrom as $type)
                                                            <span class="badge bg-info me-1 mb-1">{{ $type }}</span>
                                                        @endforeach
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                @else
                                    <div class="alert alert-warning mb-3">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        <span>Please set your blood type to see compatibility information</span>
                                    </div>
                                @endif
                                
                                <div class="text-center">
                                    <a href="{{ route('bloodbank.donate') }}" class="btn btn-primary">
                                        <i class="fas fa-hand-holding-medical me-2"></i>Schedule a Donation
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Upcoming Donations -->
        <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($upcomingDonations) > 0)
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Blood Bank/Hospital</th>
                                    <th>Donation Date</th>
                                    <th>Blood Type</th>
                                    <th>Units</th>
                                    <th>For Request</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($upcomingDonations as $donation)
                                <tr>
                                    <td>{{ $donation->bloodBank ? $donation->bloodBank->name : 'Unknown Blood Bank' }}</td>
                                    <td>{{ \Carbon\Carbon::parse($donation->donation_date)->format('M d, Y') }}</td>
                                    <td>{{ $donation->blood_type }}</td>
                                    <td>{{ $donation->units }}</td>
                                    <td>
                                        @if($donation->request)
                                            <a href="{{ route('bloodbank.requests.show', $donation->request->id) }}">
                                                {{ Str::limit($donation->request->reason ?: 'Blood Request', 30) }}
                                            </a>
                                        @else
                                            <span class="text-muted">General</span>
                                        @endif
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-danger cancel-donation" data-id="{{ $donation->id }}">
                                            <i class="fas fa-times-circle"></i> Cancel
                                        </button>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="text-center py-4">
                        <p class="text-muted mb-0">No upcoming donations scheduled</p>
                        <a href="{{ route('bloodbank.donate') }}" class="btn btn-sm btn-primary mt-2">
                            <i class="fas fa-calendar-plus me-2"></i>Schedule a Donation
                        </a>
                    </div>
                @endif
            </div>
        </div>

        <!-- Donation History -->
        <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>
                <div>
                    <button id="downloadHistoryBtn" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-download me-2"></i>Download
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                @if(count($donationHistory) > 0)
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="donationHistoryTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Blood Bank/Hospital</th>
                                    <th>Blood Type</th>
                                    <th>Units</th>
                                    <th>For Request</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($donationHistory as $donation)
                                <tr>
                                    <td>{{ \Carbon\Carbon::parse($donation->donation_date)->format('M d, Y') }}</td>
                                    <td>{{ $donation->bloodBank ? $donation->bloodBank->name : 'Unknown Blood Bank' }}</td>
                                    <td>{{ $donation->blood_type }}</td>
                                    <td>{{ $donation->units }}</td>
                                    <td>
                                        @if($donation->request)
                                            <a href="{{ route('bloodbank.requests.show', $donation->request->id) }}">
                                                {{ Str::limit($donation->request->reason ?: 'Blood Request', 30) }}
                                            </a>
                                        @else
                                            <span class="text-muted">General</span>
                                        @endif
                                    </td>
                                    <td>
                                        <span class="badge bg-{{ $donation->status == 'completed' ? 'success' : ($donation->status == 'scheduled' ? 'info' : 'secondary') }}">
                                            {{ ucfirst($donation->status) }}
                                        </span>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <div class="p-3">
                        {{ $donationHistory->links('pagination::bootstrap-5') }}
                    </div>
                @else
                    <div class="text-center py-4">
                        <p class="text-muted mb-0">No donation history found</p>
                    </div>
                @endif
            </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')
@if(setting('google_map_enabled'))
<script src="https://maps.googleapis.com/maps/api/js?key={{ setting('google_map_key') }}&libraries=places"></script>
<script>
    $(document).ready(function() {
        let map;
        let marker;
        // Initialize map
        initMap();
        
        function initMap() {
            // Get user coordinates from server
            var userLatitude = {{ $user->latitude ?? 'null' }};
            var userLongitude = {{ $user->longitude ?? 'null' }};
            
            if (userLatitude === null || userLongitude === null) {
                // Show a more prominent request for location
                $('#locationMap').html(`
                    <div class="alert alert-info mb-0 text-center">
                        <i class="fas fa-map-marker-alt fa-2x mb-2 d-block"></i>
                        <h6 class="mb-2">Location Required</h6>
                        <p class="mb-3 small">Please set your location to help us match you with nearby blood requests and donation centers.</p>
                        <button type="button" id="autoDetectLocationBtn" class="btn btn-primary btn-sm">
                            <i class="fas fa-crosshairs me-2"></i>Detect My Location Now
                        </button>
                    </div>
                `);
                
                // Add event listener for the auto-detect button
                $('#autoDetectLocationBtn').on('click', function() {
                    detectUserLocation();
                });
                return;
            }
            
            var lat = parseFloat(userLatitude);
            var lng = parseFloat(userLongitude);
            
            var location = { lat: lat, lng: lng };
            
            // Initialize map
            map = new google.maps.Map(document.getElementById('locationMap'), {
                zoom: 13,
                center: location,
            });
            
            // Add marker
            marker = new google.maps.Marker({
                position: location,
                map: map,
                draggable: true
            });
            
            // Update coordinates when marker is moved
            google.maps.event.addListener(marker, 'dragend', function() {
                const position = marker.getPosition();
                $('#latitude').val(position.lat().toFixed(6));
                $('#longitude').val(position.lng().toFixed(6));
            });
        }
        
        // Detect location function
        function detectUserLocation() {
            if (navigator.geolocation) {
                // Show loading state
                $('#locationMap').html(`
                    <div class="alert alert-info mb-0 text-center">
                        <i class="fas fa-spinner fa-spin fa-2x mb-2 d-block"></i>
                        <h6 class="mb-2">Detecting Location...</h6>
                        <p class="mb-0 small">Please allow location access when prompted</p>
                    </div>
                `);
                
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        var lat = position.coords.latitude;
                        var lng = position.coords.longitude;
                        
                        $('#latitude').val(lat.toFixed(6));
                        $('#longitude').val(lng.toFixed(6));
                        
                        var newPosition = { lat: lat, lng: lng };
                        
                        // Clear the loading message and initialize map
                        $('#locationMap').empty();
                        
                        map = new google.maps.Map(document.getElementById('locationMap'), {
                            zoom: 13,
                            center: newPosition
                        });

                        marker = new google.maps.Marker({
                            position: newPosition,
                            map: map,
                            draggable: true,
                            title: 'Your Location'
                        });

                        google.maps.event.addListener(marker, 'dragend', function() {
                            var pos = marker.getPosition();
                            $('#latitude').val(pos.lat().toFixed(6));
                            $('#longitude').val(pos.lng().toFixed(6));
                        });
                        
                        showSuccess('Location detected successfully! You can drag the marker to adjust if needed.');
                    },
                    function(error) {
                        var errorMessage;
                        switch(error.code) {
                            case error.PERMISSION_DENIED:
                                errorMessage = "Location access was denied. Please enable location access and try again.";
                                break;
                            case error.POSITION_UNAVAILABLE:
                                errorMessage = "Location information is unavailable. Please try again later.";
                                break;
                            case error.TIMEOUT:
                                errorMessage = "Location request timed out. Please try again.";
                                break;
                            default:
                                errorMessage = "An unknown error occurred while detecting location.";
                                break;
                        }
                        
                        // Show error state
                        $('#locationMap').html(`
                            <div class="alert alert-warning mb-0 text-center">
                                <i class="fas fa-exclamation-triangle fa-2x mb-2 d-block"></i>
                                <h6 class="mb-2">Location Detection Failed</h6>
                                <p class="mb-3 small">${errorMessage}</p>
                                <button type="button" id="retryDetectLocationBtn" class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-redo me-2"></i>Try Again
                                </button>
                            </div>
                        `);
                        
                        // Add retry button event
                        $('#retryDetectLocationBtn').on('click', function() {
                            detectUserLocation();
                        });
                        
                        showError(errorMessage);
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 60000
                    }
                );
            } else {
                $('#locationMap').html(`
                    <div class="alert alert-danger mb-0 text-center">
                        <i class="fas fa-times-circle fa-2x mb-2 d-block"></i>
                        <h6 class="mb-2">Geolocation Not Supported</h6>
                        <p class="mb-0 small">Your browser doesn't support location detection</p>
                    </div>
                `);
                showError('Geolocation is not supported by this browser.');
            }
        }
        
        // Detect location button
        $('#detectLocationBtn').on('click', function() {
            detectUserLocation();
        });
    });
</script>
@endif

<script>
    $(document).ready(function() {
          // Donor profile form submission
        $("#saveDonorProfile").on('click', function(e) {
            e.preventDefault();
            console.log("saveDonorProfile");
            updateDonorProfile();
        });
      
        
        // 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);
                });
        });
        
        // Download donation history
        $('#downloadHistoryBtn').on('click', function() {
            const table = document.getElementById('donationHistoryTable');
            if (!table) {
                showError('No donation history to download');
                return;
            }
            
            let csv = [];
            const rows = table.querySelectorAll('tr');
            
            for (let i = 0; i < rows.length; i++) {
                let row = [], cols = rows[i].querySelectorAll('td, th');
                
                for (let j = 0; j < cols.length; j++) {
                    // Get the text content, removing any badges or unnecessary elements
                    let text = cols[j].innerText.trim();
                    row.push('"' + text.replace(/"/g, '""') + '"');
                }
                
                csv.push(row.join(','));
            }
            
            const csvString = csv.join('\n');
            const filename = 'donation_history_' + new Date().toISOString().split('T')[0] + '.csv';
            
            const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
            
            // Create a download link and trigger click
            const link = document.createElement('a');
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        });
        
        // Update donor profile
        function updateDonorProfile() {
            const bloodType = $('#bloodType').val();
            const isDonor = $('#isDonor').is(':checked');
            const showAsDonor = $('#showAsDonor').is(':checked');
            
            let payload = {
                blood_type: bloodType,
                is_donor: isDonor,
                show_as_donor: showAsDonor,
            };

            if ($('#latitude').length) {
                payload.latitude = $('#latitude').val();
                payload.longitude = $('#longitude').val();
            }

            if (!bloodType) {
                showError('Please select your blood type');
                return;
            }
            
            // Show loading state
            const submitBtn = $('#saveDonorProfile');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);
            
            // Submit profile update
            axios.put(`${base_url}/webapi/bloodbank/donors/profile`, payload)
            .then(response => {
                if (response.data.code === 200) {
                    showSuccess('Profile updated successfully');
                    setTimeout(() => {
                        //window.location.reload();
                    }, 1500);
                }
            })
            .catch(error => {
                console.error('Error updating profile:', error);
                showError(error.response?.data?.message || 'Error updating profile. Please try again.');
                setTimeout(() => {
                    //window.location.reload();
                }, 1500);
            })
            .finally(() => {
                submitBtn.html(originalText).prop('disabled', false);
            });
        }
        
        // Utility Functions
        function showSuccess(message) {
            myAlert.fire({
                icon: 'success',
                title: 'Success',
                text: message
            });
        }
        
        function showError(message) {
            myAlert.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
    });
</script>
@endsection