@extends('layouts.admin')

@section('title', 'Student Details')
@section('page-title', 'Student Details')

@section('content')
    <div class="card">
        <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <h3>{{ $student->name }}</h3>
            <div style="display: flex; gap: 10px;">
                <button onclick="location.reload()" class="btn btn-secondary" title="Refresh">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
                <a href="{{ route('admin.students.edit', $student->id) }}" class="btn btn-secondary">Edit</a>
                <a href="{{ route('admin.students.index') }}" class="btn btn-secondary">Back</a>
            </div>
        </div>
        
        <div style="padding: 30px;">
            <!-- Profile Picture Section -->
            <div style="text-align: center; margin-bottom: 30px; padding-bottom: 30px; border-bottom: 1px solid #404040;">
                @if($student->profile_picture)
                    @php
                        try {
                            $decrypted = \Illuminate\Support\Facades\Crypt::decryptString($student->profile_picture);
                        } catch (\Exception $e) {
                            $decrypted = null;
                        }
                    @endphp
                    @if($decrypted)
                        <img src="{{ $decrypted }}" alt="Profile Picture" 
                             style="width: 150px; height: 150px; border-radius: 50%; object-fit: cover; border: 3px solid #4a9eff; box-shadow: 0 4px 12px rgba(74, 158, 255, 0.3);">
                    @else
                        <div style="width: 150px; height: 150px; border-radius: 50%; background: #2d2d2d; display: flex; align-items: center; justify-content: center; border: 3px solid #4a9eff; margin: 0 auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);">
                            <i class="fas fa-user" style="font-size: 60px; color: #888;"></i>
                        </div>
                    @endif
                @else
                    <div style="width: 150px; height: 150px; border-radius: 50%; background: #2d2d2d; display: flex; align-items: center; justify-content: center; border: 3px solid #4a9eff; margin: 0 auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);">
                        <i class="fas fa-user" style="font-size: 60px; color: #888;"></i>
                    </div>
                @endif
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px;">
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">Full Name</strong>
                    <p style="font-size: 16px;">{{ $student->name }}</p>
                </div>
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">Email</strong>
                    <p style="font-size: 16px;">{{ $student->email }}</p>
                </div>
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">School ID</strong>
                    <p style="font-size: 16px;">{{ $student->school_id ?? 'N/A' }}</p>
                </div>
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">Phone</strong>
                    <p style="font-size: 16px;">{{ $student->phone ?? 'N/A' }}</p>
                </div>
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">Address</strong>
                    <p style="font-size: 16px;">{{ $student->address ?? 'N/A' }}</p>
                </div>
                <div>
                    <strong style="color: #888; display: block; margin-bottom: 5px;">Registered</strong>
                    <p style="font-size: 16px;">{{ $student->created_at->format('M d, Y') }}</p>
                </div>
            </div>
            
            <!-- Delivery Information Section -->
            <div style="border-top: 1px solid #404040; padding-top: 20px; margin-top: 30px;">
                <h4 style="margin-bottom: 20px; color: #4a9eff;">
                    <i class="fas fa-truck"></i> Delivery Information
                </h4>
                
                <div style="margin-bottom: 20px; padding: 15px; background: #1a1a1a; border-radius: 5px;">
                    <strong style="color: #888; display: block; margin-bottom: 10px;">Delivery Address</strong>
                    <p style="font-size: 14px; color: #e0e0e0; margin: 0;">
                        @if($student->delivery_address)
                            {{ $student->delivery_address }}
                        @else
                            <span style="color: #888;">Not provided</span>
                        @endif
                    </p>
                </div>
                
                <div style="margin-bottom: 20px; padding: 15px; background: #1a1a1a; border-radius: 5px;">
                    <strong style="color: #888; display: block; margin-bottom: 10px;">T-Shirt Size</strong>
                    <p style="font-size: 14px; color: #e0e0e0; margin: 0;">
                        @if($student->t_shirt_size)
                            <span style="color: #4a9eff; font-weight: bold;">{{ $student->t_shirt_size }}</span>
                        @else
                            <span style="color: #888;">Not selected</span>
                        @endif
                    </p>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                    @php
                        $items = [
                            't_shirt' => ['label' => 'T-Shirt', 'icon' => 'tshirt', 'size' => $student->t_shirt_size],
                            'cap' => ['label' => 'Cap', 'icon' => 'hat-cowboy'],
                            'id_card' => ['label' => 'ID Card', 'icon' => 'id-card'],
                            'handout_book' => ['label' => 'Handout Book', 'icon' => 'book'],
                        ];
                    @endphp
                    
                    @foreach($items as $key => $item)
                        @php
                            $status = $student->{$key . '_status'} ?? 'pending';
                            $updatedAt = $student->{$key . '_updated_at'};
                            $notes = $student->{$key . '_notes'};
                            $statusColors = [
                                'pending' => '#888',
                                'on_the_way' => '#ffa500',
                                'delivered' => '#6bff6b',
                                'canceled' => '#ff6b6b',
                                'returned' => '#ff6b6b',
                            ];
                            $statusLabels = [
                                'pending' => 'Pending',
                                'on_the_way' => 'On The Way',
                                'delivered' => 'Delivered',
                                'canceled' => 'Canceled',
                                'returned' => 'Returned',
                            ];
                        @endphp
                        <div style="padding: 20px; background: #1a1a1a; border-radius: 5px; border-left: 3px solid {{ $statusColors[$status] ?? '#888' }};">
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px;">
                                <div>
                                    <h5 style="margin: 0 0 5px 0; color: #e0e0e0;">
                                        <i class="fas fa-{{ $item['icon'] }}"></i> {{ $item['label'] }}
                                    </h5>
                                    @if(isset($item['size']) && $item['size'])
                                        <small style="color: #888;">Size: <strong style="color: #4a9eff;">{{ $item['size'] }}</strong></small>
                                    @elseif($key == 't_shirt')
                                        <small style="color: #888;">Size: <span style="color: #888;">Not selected</span></small>
                                    @endif
                                </div>
                                <span style="padding: 5px 12px; background: {{ $statusColors[$status] ?? '#888' }}; color: #1a1a1a; border-radius: 15px; font-size: 11px; font-weight: bold;">
                                    {{ $statusLabels[$status] ?? ucfirst($status) }}
                                </span>
                            </div>
                            
                            @if($updatedAt)
                                <small style="color: #888; display: block; margin-bottom: 10px;">
                                    Updated: {{ $updatedAt->format('M d, Y h:i A') }}
                                </small>
                            @endif
                            
                            @if($notes)
                                <p style="color: #e0e0e0; font-size: 12px; margin: 10px 0 0 0; padding: 10px; background: #2d2d2d; border-radius: 3px;">
                                    <strong>Notes:</strong> {{ $notes }}
                                </p>
                            @endif
                            
                            <button type="button" 
                                    onclick="openDeliveryModal('{{ $key }}', '{{ $status }}', '{{ addslashes($notes ?? '') }}')" 
                                    class="btn btn-secondary" 
                                    style="margin-top: 10px; width: 100%; padding: 8px; font-size: 12px;">
                                <i class="fas fa-edit"></i> Update Status
                            </button>
                        </div>
                    @endforeach
                </div>
            </div>
            
            @if($student->enrollments->count() > 0)
                <div style="border-top: 1px solid #404040; padding-top: 20px; margin-top: 30px;">
                    <h4 style="margin-bottom: 15px;">Enrolled Courses</h4>
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Course</th>
                                <th>Code</th>
                                <th>Enrollment Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($student->enrollments as $enrollment)
                                <tr>
                                    <td><strong>{{ $enrollment->course->name }}</strong></td>
                                    <td>{{ $enrollment->course->code }}</td>
                                    <td>{{ $enrollment->enrollment_date->format('M d, Y') }}</td>
                                    <td>
                                        @if($enrollment->status == 'active')
                                            <span style="color: #6bff6b;">Active</span>
                                        @elseif($enrollment->status == 'completed')
                                            <span style="color: #888;">Completed</span>
                                        @elseif($enrollment->status == 'withdrawn')
                                            <span style="color: #ff6b6b;">Withdrawn</span>
                                        @else
                                            <span style="color: #888;">Inactive</span>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @endif
        </div>
        
        <div style="padding: 0 30px 30px 30px; border-top: 1px solid #404040; margin-top: 20px; padding-top: 20px;">
            <button type="button" onclick="openConfirmationModal('Delete Student', 'Are you sure you want to delete {{ addslashes($student->name) }}? This action cannot be undone and all associated data will be permanently removed.', '{{ route('admin.students.destroy', $student->id) }}', 'DELETE')" class="btn btn-secondary" style="background: #dc3545; border: none;">
                <i class="fas fa-trash"></i> Delete Student
            </button>
        </div>
    </div>
    
    <!-- Delivery Status Update Modal -->
    <div id="deliveryModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 10000; overflow-y: auto;">
        <div style="position: relative; max-width: 500px; margin: 50px auto; background: #1a1a1a; border-radius: 10px; padding: 30px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="color: #e0e0e0; margin: 0;"><i class="fas fa-truck"></i> Update Delivery Status</h2>
                <button type="button" onclick="closeDeliveryModal()" style="background: none; border: none; color: #888; font-size: 24px; cursor: pointer;">&times;</button>
            </div>
            
            <form id="deliveryForm" onsubmit="updateDeliveryStatus(event)">
                <input type="hidden" id="deliveryItem" name="item">
                
                <div class="form-group" style="margin-bottom: 20px;">
                    <label for="deliveryStatus" style="color: #e0e0e0; display: block; margin-bottom: 8px;">Status *</label>
                    <select id="deliveryStatus" name="status" required style="width: 100%; padding: 12px; background: #2d2d2d; border: 1px solid #404040; border-radius: 5px; color: #e0e0e0;">
                        <option value="pending">Pending</option>
                        <option value="on_the_way">On The Way</option>
                        <option value="delivered">Delivered</option>
                        <option value="canceled">Canceled</option>
                        <option value="returned">Returned</option>
                    </select>
                </div>
                
                <div class="form-group" style="margin-bottom: 20px;">
                    <label for="deliveryNotes" style="color: #e0e0e0; display: block; margin-bottom: 8px;">Notes (Optional)</label>
                    <textarea id="deliveryNotes" name="notes" rows="4" style="width: 100%; padding: 12px; background: #2d2d2d; border: 1px solid #404040; border-radius: 5px; color: #e0e0e0; resize: vertical;" placeholder="Add any notes about this delivery..."></textarea>
                </div>
                
                <div style="display: flex; gap: 10px;">
                    <button type="submit" class="btn btn-primary" style="flex: 1;">
                        <i class="fas fa-save"></i> Update Status
                    </button>
                    <button type="button" onclick="closeDeliveryModal()" class="btn btn-secondary" style="flex: 1;">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    @push('scripts')
    <script>
        function openDeliveryModal(item, currentStatus, currentNotes) {
            document.getElementById('deliveryItem').value = item;
            document.getElementById('deliveryStatus').value = currentStatus;
            document.getElementById('deliveryNotes').value = currentNotes;
            document.getElementById('deliveryModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }
        
        function closeDeliveryModal() {
            document.getElementById('deliveryModal').style.display = 'none';
            document.body.style.overflow = 'auto';
        }
        
        function updateDeliveryStatus(event) {
            event.preventDefault();
            
            const item = document.getElementById('deliveryItem').value;
            const status = document.getElementById('deliveryStatus').value;
            const notes = document.getElementById('deliveryNotes').value;
            
            const btn = event.target.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            btn.disabled = true;
            
            const formData = new FormData();
            formData.append('item', item);
            formData.append('status', status);
            formData.append('notes', notes);
            formData.append('_token', '{{ csrf_token() }}');
            
            fetch('{{ route("admin.students.delivery-status", $student->id) }}', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else {
                    return response.text().then(text => {
                        try {
                            return JSON.parse(text);
                        } catch {
                            return { success: false, message: 'Unexpected response' };
                        }
                    });
                }
            })
            .then(data => {
                if (data && data.success === false) {
                    alert(data.message || 'Failed to update status. Please try again.');
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                } else {
                    // Success - page will reload from redirect
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }
        
        // Close modal when clicking outside
        document.getElementById('deliveryModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeliveryModal();
            }
        });
    </script>
    @endpush
@endsection
