@extends('front_end.layouts.home')

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

@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.requests') }}" class="text-white me-3">
                                    <i class="fas fa-arrow-left fa-lg"></i>
                                </a>
                                <div>
                                    <h4 class="mb-0 text-white">Blood Request Details</h4>
                                    <p class="mb-0 text-white">View detailed information about this blood request</p>
                                </div>
                            </div>
                            <div>
                                @if($request->user_id == Auth::id() && $request->status != 'fulfilled' && $request->status != 'cancelled')
                                <button id="cancelRequestBtn" class="btn btn-light text-danger">
                                    <i class="fas fa-times-circle me-2"></i>Cancel Request
                                </button>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- Request Summary -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Request Summary</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="d-flex align-items-center mb-3">
                            <div class="icon-lg bg-danger bg-opacity-10 rounded-circle text-danger me-3">
                                <span class="fw-bold display-6">{{ $request->blood_type }}</span>
                            </div>
                            <div>
                                <h4 class="mb-1">{{ $request->reason ?: 'Blood Requirement' }}</h4>
                                <div class="d-flex align-items-center">
                                    @php
                                        $urgencyBadge = $request->urgency == 'emergency' ? 'danger' : ($request->urgency == 'urgent' ? 'warning' : 'primary');
                                        $statusBadge = $request->status == 'fulfilled' ? 'success' : ($request->status == 'in_progress' ? 'info' : ($request->status == 'cancelled' ? 'danger' : 'secondary'));
                                    @endphp
                                    <span class="badge bg-{{ $urgencyBadge }} me-2">{{ ucfirst($request->urgency) }}</span>
                                    <span class="badge bg-{{ $statusBadge }}">{{ str_replace('_', ' ', ucfirst($request->status)) }}</span>
                                    <span class="mx-2">•</span>
                                    <span class="text-muted small">
                                        <i class="fas fa-clock me-1"></i> Posted {{ \Carbon\Carbon::parse($request->created_at)->diffForHumans() }}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-sm-6">
                                <div class="card h-100 bg-light border-0">
                                    <div class="card-body p-3">
                                        <h6 class="card-title small text-muted">Hospital/Location</h6>
                                        <p class="mb-0">{{ $request->hospital_name }}</p>
                                        <p class="mb-0 small">{{ $request->hospital_address }}</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="card h-100 bg-light border-0">
                                    <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>
                                        @if($request->user->email)
                                        <p class="mb-0 small">
                                            <i class="fas fa-envelope me-2"></i>{{ $request->user->email }}
                                        </p>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="card h-100 bg-light border-0">
                                    <div class="card-body p-3">
                                        <h6 class="card-title small text-muted">Blood Requirement</h6>
                                        <div class="d-flex align-items-center">
                                            <div class="display-6 fw-bold me-2">{{ $request->units_needed }}</div>
                                            <div>
                                                <p class="mb-0">Units</p>
                                                <p class="mb-0 small text-muted">{{ $request->blood_type }} blood type</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-6">
                                <div class="card h-100 bg-light border-0">
                                    <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: {{ \Carbon\Carbon::parse($request->needed_by)->format('M d, Y') }}</p>
                                        <p class="mb-0 small text-{{ \Carbon\Carbon::parse($request->needed_by)->isPast() ? 'danger' : 'success' }}">
                                            {{ \Carbon\Carbon::parse($request->needed_by)->diffForHumans() }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        @if($request->reason)
                        <div class="mb-4">
                            <h6 class="mb-2">Request Reason</h6>
                            <p class="mb-0">{{ $request->reason }}</p>
                        </div>
                        @endif

                        @if($request->latitude && $request->longitude)
                        <div class="mb-4">
                            <h6 class="mb-2">Location</h6>
                            <div class="card bg-light border-0">
                                <div class="card-body p-2">
                                    <div id="map" style="height: 200px;"></div>
                                </div>
                            </div>
                        </div>
                        @endif
                    </div>

                    <div class="col-md-4">
                        <div class="card bg-white border shadow-sm h-100">
                            <div class="card-header bg-transparent">
                                <h6 class="mb-0">Donation Progress</h6>
                            </div>
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    @php
                                        $progress = $request->donations_count > 0 ? 
                                            min(100, ($request->donations_count / $request->units_needed) * 100) : 0;
                                        
                                        $progressColor = $progress < 30 ? 'danger' : 
                                            ($progress < 70 ? 'warning' : 'success');
                                    @endphp
                                    
                                    <div class="position-relative d-inline-block">
                                        <svg width="120" height="120" viewBox="0 0 120 120">
                                            <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
                                            <circle cx="60" cy="60" r="54" fill="none" stroke-width="12"
                                                stroke="#{{ $progressColor == 'danger' ? 'dc3545' : ($progressColor == 'warning' ? 'ffc107' : '28a745') }}"
                                                stroke-dasharray="339.292" stroke-dashoffset="{{ 339.292 * (1 - ($progress / 100)) }}"
                                                stroke-linecap="round" transform="rotate(-90 60 60)" />
                                        </svg>
                                        <div class="position-absolute top-50 start-50 translate-middle">
                                            <h3 class="mb-0">{{ $request->donations_count }}</h3>
                                            <p class="mb-0 small">of {{ $request->units_needed }}</p>
                                        </div>
                                    </div>
                                </div>
                                
                                <p class="text-{{ $progressColor }} mb-3">
                                    {{ $request->donations_count }} units donated out of {{ $request->units_needed }} needed
                                </p>
                                
                                @if($request->status != 'fulfilled' && $request->status != 'cancelled' && \Carbon\Carbon::parse($request->needed_by)->isFuture())
                                    @if($canDonate)
                                        <button id="respondBtn" class="btn btn-primary w-100">
                                            <i class="fas fa-heart me-2"></i>Respond to Request
                                        </button>
                                    @else
                                        <div class="alert alert-warning mb-0 small">
                                            <i class="fas fa-exclamation-triangle me-2"></i>
                                            {{ $compatibilityMessage ?: 'You are not eligible to donate to this request.' }}
                                        </div>
                                    @endif
                                @elseif($request->status == 'fulfilled')
                                    <div class="alert alert-success mb-0 small">
                                        <i class="fas fa-check-circle me-2"></i>
                                        This request has been fulfilled
                                    </div>
                                @elseif($request->status == 'cancelled')
                                    <div class="alert alert-danger mb-0 small">
                                        <i class="fas fa-times-circle me-2"></i>
                                        This request has been cancelled
                                    </div>
                                @else
                                    <div class="alert alert-danger mb-0 small">
                                        <i class="fas fa-calendar-times me-2"></i>
                                        The needed by date has passed
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Donations List -->
        @if(count($request->donations) > 0)
        <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">Donations</h5>
                <span class="badge bg-primary">{{ count($request->donations) }} donations</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Donor</th>
                                <th>Blood Type</th>
                                <th>Units</th>
                                <th>Donation Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($request->donations as $donation)
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar avatar-sm me-2">
                                            @if($donation->user->avatar)
                                                <img src="{{ asset($donation->user->avatar) }}" class="rounded-circle" alt="{{ $donation->user->name }}">
                                            @else
                                                <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                                    {{ strtoupper(substr($donation->user->name, 0, 1)) }}
                                                </div>
                                            @endif
                                        </div>
                                        <div>
                                            <p class="mb-0">{{ $donation->user->name }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td>{{ $donation->blood_type }}</td>
                                <td>{{ $donation->units }}</td>
                                <td>{{ \Carbon\Carbon::parse($donation->donation_date)->format('M d, Y') }}</td>
                                <td>
                                    @php
                                        $statusBadge = $donation->status == 'completed' ? 'success' : 
                                                    ($donation->status == 'scheduled' ? 'info' : 
                                                    ($donation->status == 'cancelled' ? 'danger' : 'secondary'));
                                    @endphp
                                    <span class="badge bg-{{ $statusBadge }}">
                                        {{ ucfirst($donation->status) }}
                                    </span>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        @endif

        <!-- Requester Information -->
        <div class="card border-0 shadow-sm rounded-3 mb-4">
            <div class="card-header bg-transparent">
                <h5 class="mb-0">Requester Information</h5>
            </div>
            <div class="card-body">
                <div class="d-flex">
                    <div class="avatar avatar-lg me-3">
                        @if($request->user->avatar)
                            <img src="{{ asset($request->user->avatar) }}" class="rounded-circle" alt="{{ $request->user->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($request->user->name, 0, 1)) }}
                            </div>
                        @endif
                    </div>
                    <div>
                        <h5 class="mb-1">{{ $request->user->name }}</h5>
                        <p class="mb-2 text-muted small">
                            <i class="fas fa-user me-2"></i>Member since {{ \Carbon\Carbon::parse($request->user->created_at)->format('M Y') }}
                        </p>
                        <div class="d-flex gap-2">
                            @if($request->user->id != Auth::id())
                                <a href="{{ route('profile.view', $request->user->id) }}" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-user me-2"></i>View Profile
                                </a>
                                @if($request->user->phone)
                                    <a href="tel:{{ $request->user->phone }}" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-phone me-2"></i>Contact
                                    </a>
                                @endif
                            @else
                                <span class="badge bg-light text-dark">This is your request</span>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 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>{{ $request->blood_type }}</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Units Needed:</p>
                                <strong>{{ $request->units_needed }}</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Hospital:</p>
                                <strong>{{ $request->hospital_name }}</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Address:</p>
                                <strong>{{ $request->hospital_address }}</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Contact:</p>
                                <strong>{{ $request->contact_phone }}</strong>
                            </div>
                            <div class="col-6">
                                <p class="small mb-1">Urgency:</p>
                                <strong>{{ ucfirst($request->urgency) }}</strong>
                            </div>
                            <div class="col-12">
                                <p class="small mb-1">Needed By:</p>
                                <strong>{{ \Carbon\Carbon::parse($request->needed_by)->format('M d, Y') }}</strong>
                            </div>
                        </div>
                    </div>
                </div>
                <form id="responseForm">
                    <input type="hidden" id="responseRequestId" value="{{ $request->id }}">
                    <div class="mb-3">
                        <label for="responseDonationDate" class="form-label">When can you donate?</label>
                        <input type="date" class="form-control" id="responseDonationDate" 
                               min="{{ date('Y-m-d') }}" 
                               max="{{ date('Y-m-d', strtotime('+90 days')) }}" 
                               required>
                        <div class="form-text">Please select a date between today and {{ date('M d, Y', strtotime('+90 days')) }}</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>

<!-- Cancel Request Confirmation Modal -->
@if($request->user_id == Auth::id() && $request->status != 'fulfilled' && $request->status != 'cancelled')
<div class="modal fade" id="cancelRequestModal" tabindex="-1" aria-labelledby="cancelRequestModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancelRequestModalLabel">Cancel Blood Request</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 blood request?</strong>
                </div>
                <p>This action cannot be undone. If you still need blood, you will need to create a new request.</p>
                
                @if(count($request->donations) > 0)
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>This request has {{ count($request->donations) }} donation(s) associated with it.</strong>
                    <p class="mb-0 small">Donors who have already scheduled donations will be notified of the cancellation.</p>
                </div>
                @endif
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Keep Request</button>
                <button type="button" id="confirmCancelRequest" class="btn btn-danger">Cancel Request</button>
            </div>
        </div>
    </div>
</div>
@endif

@endsection

@section('extra-js')
<script>
    $(document).ready(function() {
        const isAuthenticated = {{ Auth::check() ? 'true' : 'false' }};
        
        // Initialize map if coordinates available
        @if($request->latitude && $request->longitude)
        initMap();
        
        function initMap() {
            const map = L.map('map').setView([{{ $request->latitude }}, {{ $request->longitude }}], 14);
            
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
            
            L.marker([{{ $request->latitude }}, {{ $request->longitude }}])
                .addTo(map)
                .bindPopup("{{ $request->hospital_name }}")
                .openPopup();
        }
        @endif
        
        // Respond to request button
        $('#respondBtn').on('click', function() {
            if (!isAuthenticated) {
                showLoginPrompt();
                return;
            }
            $('#responseModal').modal('show');
        });
        
        // Handle response submission
        $('#submitResponse').on('click', function() {
            const donationDate = $('#responseDonationDate').val();
            const units = $('#responseUnits').val();
            
            if (!donationDate) {
                showError('Please select a donation date');
                return;
            }
            
            if (!units) {
                showError('Please select the number of units');
                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/{{ $request->id }}/respond`, {
                units: units,
                donation_date: donationDate
            })
            .then(response => {
                if (response.data.code === 201) {
                    showSuccess('Response submitted successfully');
                    $('#responseModal').modal('hide');
                    
                    // Reload page after a brief delay
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            })
            .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);
            });
        });
        
        // Cancel request button
        $('#cancelRequestBtn').on('click', function() {
            $('#cancelRequestModal').modal('show');
        });
        
        // Confirm cancel request
        $('#confirmCancelRequest').on('click', function() {
            // Show loading state
            const submitBtn = $('#confirmCancelRequest');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Cancelling...').prop('disabled', true);
            
            // Cancel request
            axios.post(`${base_url}/webapi/bloodbank/requests/{{ $request->id }}/cancel`)
            .then(response => {
                if (response.data.code === 200) {
                    showSuccess('Request cancelled successfully');
                    $('#cancelRequestModal').modal('hide');
                    
                    // Reload page after a brief delay
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            })
            .catch(error => {
                console.error('Error cancelling request:', error);
                showError(error.response?.data?.message || 'Error cancelling request. 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
            });
        }
        
        // HTML5 date input handles date picking natively
        // Set default date to tomorrow to encourage advance planning
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        const defaultDate = tomorrow.toISOString().split('T')[0];
        $('#responseDonationDate').val(defaultDate);
    });
</script>
@endsection