@extends('layouts.app')

@section('title', 'Issue New Book')
@section('content')
@php
use App\Models\Issue;
use App\Models\BookCopy;
@endphp

<!-- CSS Resources -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<style>
    /* Base Styles */
    .bg-gradient-primary {
        background: linear-gradient(135deg, #4361ee, #3f37c9);
    }
    .card {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    }

    /* Select2 Container */
    .select2-container {
        width: 100% !important;
    }

    .select2-container .select2-selection--single {
        height: 42px !important;
        border: 1px solid #ced4da !important;
        border-radius: 8px !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 40px !important;
        padding-left: 15px !important;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 40px !important;
    }

    /* Dropdown styling */
    .select2-dropdown {
        border: 1px solid #ced4da !important;
        border-radius: 8px !important;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15) !important;
    }

    /* Search Box Styling */
    .select2-search--dropdown:before {
        font-family: "Font Awesome 6 Free";
        font-weight: 900;
        content: "\f002";
        position: absolute;
        left: 20px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 1;
    }

    .select2-search--dropdown .select2-search__field {
        padding-left: 35px !important;
        border-radius: 6px !important;
        border: 1px solid #ced4da !important;
    }

    /* Student history panel */
    .student-history {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-top: 20px;
        background-color: #f8f9fa;
        display: none;
    }

    .student-history h5 {
        border-bottom: 1px solid #dee2e6;
        padding-bottom: 10px;
        margin-bottom: 15px;
    }

    .history-item {
        padding: 10px 0;
        border-bottom: 1px dashed #dee2e6;
    }

    .history-item:last-child {
        border-bottom: none;
    }

    .badge-overdue {
        background-color: #dc3545;
    }

    .badge-returned {
        background-color: #28a745;
    }

    .badge-issued {
        background-color: #007bff;
    }

    /* Highlight search term */
    .highlight {
        background-color: #FFF9C4 !important;
        color: #000 !important;
        padding: 1px 2px;
        border-radius: 2px;
    }

    /* Button styling */
    .btn-primary {
        background-color: #4361ee;
        border-color: #4361ee;
        padding: 10px 24px;
        font-size: 1rem;
        border-radius: 8px;
    }

    .btn-primary:hover {
        background-color: #3a56d4;
        border-color: #3a56d4;
    }
</style>

<div class="container py-4">
    <div class="card border-0">
        <div class="card-header bg-gradient-primary text-white">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="fas fa-book-open me-2"></i> Issue New Book</h4>
                <a href="{{ route('issues.index') }}" class="btn btn-light btn-sm">
                    <i class="fas fa-list me-1"></i> View Issued Books
                </a>
            </div>
        </div>

        <div class="card-body">
            <form method="POST" action="{{ route('issues.store') }}" id="issueForm">
                @csrf

                @if($apiError)
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>API Error:</strong> {{ $apiError }}
                    <p class="mb-0 mt-1">Using fallback student data</p>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                @endif

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group mb-4">
                            <label for="student_id" class="form-label fw-bold">Student</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-user-graduate"></i></span>
                                <select class="form-control select2" id="student_id" name="student_id" required>
                                    <option value="">Select Student</option>
                                    @foreach ($students as $student)
                                        @if(!empty($student['sname']) && !empty($student['srollno']))
                                            @php
                                                $hasIssuedBooks = Issue::where('student_id', $student['srollno'])
                                                    ->where('status', 'issued')
                                                    ->exists();
                                            @endphp
                                            <option value="{{ $student['srollno'] }}"
                                                data-name="{{ $student['sname'] }}"
                                                data-rollno="{{ $student['srollno'] }}"
                                                @if($hasIssuedBooks) class="has-issues" @endif>
                                                {{ $student['sname'] }} ({{ $student['srollno'] }})
                                                @if($hasIssuedBooks) - Has issued books @endif
                                            </option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <small class="text-muted">Students with existing issues appear with warning icon</small>

                            <!-- Student History Panel -->
                            <div class="student-history" id="studentHistory">
                                <h5><i class="fas fa-history me-2"></i>Issued Book History</h5>
                                <div id="historyContent">
                                    <!-- Content will be loaded via AJAX -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group mb-4">
                            <label for="book_copy_id" class="form-label fw-bold">Book Copy</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-book"></i></span>
                                <select class="form-control select2" id="book_copy_id" name="book_copy_id" required>
                                    <option value="">Select Book Copy</option>
                                    @foreach($books as $book)
                                        @if($book->copies->count())
                                        <optgroup label="{{ $book->name }}">
                                            @foreach($book->copies as $copy)
                                                @php
                                                    $copyStatus = BookCopy::find($copy->id)->status;
                                                @endphp
                                                <option value="{{ $copy->id }}"
                                                    data-book="{{ $book->name }}"
                                                    data-copy="{{ $copy->id }}"
                                                    data-barcode="{{ $copy->barcode }}"
                                                    data-status="{{ $copyStatus }}">
                                                    Copy #{{ $copy->id }} ({{ $book->id }})
                                                    @if($copyStatus !== 'available') - {{ ucfirst($copyStatus) }} @endif
                                                </option>
                                            @endforeach
                                        </optgroup>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <small class="text-muted">Available copies are highlighted in green</small>
                        </div>
                    </div>
                </div>

                <div class="d-grid mt-2">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-check-circle me-2"></i> Issue Book
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- JavaScript at the bottom -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize Select2 with custom templates and search placeholder
    $('.select2').select2({
        templateResult: formatResult,
        templateSelection: formatSelection,
        escapeMarkup: function(markup) {
            return markup;
        },
        language: {
            searching: function() {
                return '';
            }
        }
    });

    // Add search icon and placeholder text to dropdowns
    $(document).on('select2:open', (e) => {
        let searchField = $('.select2-search__field');
        let selectId = e.target.id;

        // Set appropriate placeholder based on which select is opened
        if (selectId === 'student_id') {
            searchField.attr('placeholder', 'Search students...');
        } else if (selectId === 'book_copy_id') {
            searchField.attr('placeholder', 'Search books...');
        }

        // Focus and style the search field
        searchField.focus();
        searchField.css({
            'width': '100%',
            'padding-left': '35px'
        });
    });

    // When student is selected, load their history
    $('#student_id').on('change', function() {
        var studentId = $(this).val();
        var historyPanel = $('#studentHistory');
        var historyContent = $('#historyContent');

        if (studentId) {
            // Show loading state
            historyContent.html('<div class="text-center py-3"><i class="fas fa-spinner fa-spin me-2"></i>Loading history...</div>');
            historyPanel.show();

            // AJAX request to get student's book issue history
            $.ajax({
                url: '{{ route("issues.studentHistory") }}',
                type: 'GET',
                data: { student_id: studentId },
                success: function(response) {
                    if (response.length > 0) {
                        var html = '';
                        response.forEach(function(issue) {
                            var statusClass = '';
                            var statusText = '';

                            if (issue.return_date) {
                                statusClass = 'badge-returned';
                                statusText = 'Returned on ' + new Date(issue.return_date).toLocaleDateString();
                            } else if (new Date(issue.due_date) < new Date()) {
                                statusClass = 'badge-overdue';
                                statusText = 'Overdue since ' + new Date(issue.due_date).toLocaleDateString();
                            } else {
                                statusClass = 'badge-issued';
                                statusText = 'Issued - Due on ' + new Date(issue.due_date).toLocaleDateString();
                            }

                            html += `
                                <div class="history-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <strong>${issue.book_name}</strong>
                                        <span class="badge ${statusClass}">${statusText}</span>
                                    </div>
                                    <div class="d-flex justify-content-between text-muted small">
                                        <span>Copy #${issue.copy_id} (${issue.barcode})</span>
                                        <span>Issued: ${new Date(issue.issue_date).toLocaleDateString()}</span>
                                    </div>
                                </div>
                            `;
                        });

                        historyContent.html(html);
                    } else {
                        historyContent.html('<div class="text-center py-3 text-muted">No book issue history found for this student.</div>');
                    }
                },
                error: function() {
                    historyContent.html('<div class="alert alert-danger">Failed to load history. Please try again.</div>');
                }
            });
        } else {
            historyPanel.hide();
        }
    });

    function formatResult(data) {
        if (!data.id) return data.text;

        var $option = $(data.element);
        var text = data.text;
        var searchTerm = $('.select2-search__field').val().trim();

        if (searchTerm) {
            var regex = new RegExp('(' + escapeRegExp(searchTerm) + ')', 'gi');
            text = text.replace(regex, '<span class="highlight">$1</span>');
        }

        if ($option.hasClass('has-issues')) {
            text = '<i class="fas fa-exclamation-circle text-warning me-2"></i>' + text;
        }

        if ($option.data('status')) {
            text += ' <span class="badge bg-' + getStatusClass($option.data('status')) + '">' +
                   $option.data('status') + '</span>';
        }

        return $('<span>').html(text);
    }

    function formatSelection(data) {
        var $option = $(data.element);
        if ($option.data('name')) {
            return $option.data('name') + ' (' + $option.data('rollno') + ')';
        }
        if ($option.data('book')) {
            return $option.data('book') + ' - Copy #' + $option.data('copy');
        }
        return data.text;
    }

    function getStatusClass(status) {
        switch(status) {
            case 'available': return 'success';
            case 'issued': return 'warning';
            case 'lost': return 'danger';
            case 'damaged': return 'info';
            default: return 'secondary';
        }
    }

    function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
});
</script>
@endsection
