@extends('layouts.app')

@section('title', 'Send Notifications | Institution Axis')

@section('sidebar-menu')
    @include('schooladmin.partials.sidebar')
@endsection

@section('breadcrumb')
    <span><a href="{{ route('schooladmin.dashboard') }}">Home</a></span> / <span><a href="{{ route('schooladmin.communication.index') }}">Communication</a></span> / <span class="active-page">Send Notifications</span>
@endsection

@section('content')
<div class="row g-4">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0 rounded-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-paper-plane me-2 text-primary"></i>Compose Message</h5>
            </div>
            <div class="card-body">
                <form action="{{ route('schooladmin.communication.send') }}" method="POST">
                    @csrf
                    <div class="mb-3">
                        <label class="form-label font-weight-bold">Select Delivery Type</label>
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="form-check card-select p-3 border rounded">
                                    <input class="form-check-input" type="radio" name="type" id="typeSms" value="SMS" checked>
                                    <label class="form-check-label w-100" for="typeSms">
                                        <i class="fas fa-sms text-info mb-2 fs-4"></i><br>
                                        <strong>SMS</strong>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-check card-select p-3 border rounded">
                                    <input class="form-check-input" type="radio" name="type" id="typeEmail" value="Email">
                                    <label class="form-check-label w-100" for="typeEmail">
                                        <i class="fas fa-envelope text-success mb-2 fs-4"></i><br>
                                        <strong>Email</strong>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-check card-select p-3 border rounded">
                                    <input class="form-check-input" type="radio" name="type" id="typeBoth" value="Both">
                                    <label class="form-check-label w-100" for="typeBoth">
                                        <i class="fas fa-layer-group text-primary mb-2 fs-4"></i><br>
                                        <strong>Both</strong>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="emailSubjectField" class="mb-3 d-none">
                        <label for="subject" class="form-label">Email Subject</label>
                        <input type="text" name="subject" id="subject" class="form-control" placeholder="Enter email subject">
                    </div>

                    <div class="mb-3">
                        <label for="message" class="form-label">Message Content</label>
                        <textarea name="message" id="message" rows="5" class="form-control" placeholder="Type your message here..." required></textarea>
                        <div class="form-text mt-2" id="smsCount">0 characters (0 segments)</div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label font-weight-bold">Selected Recipients (<span id="selectedCount">0</span>)</label>
                        <p class="text-muted small">Select recipients from the list on the right.</p>
                        <div id="selectedRecipientsList" class="d-flex flex-wrap gap-2"></div>
                        <input type="hidden" name="recipients[]" id="recipientsHidden">
                    </div>

                    <hr>
                    <div class="d-flex justify-content-between">
                        <button type="reset" class="btn btn-light">Clear Form</button>
                        <button type="submit" class="btn btn-primary px-4 shadow-sm">Send Notification</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-0 rounded-4 h-100">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-users me-2 text-secondary"></i>Recipients</h5>
                <div class="input-group input-group-sm w-50">
                    <input type="text" id="recipientSearch" class="form-control" placeholder="Search...">
                </div>
            </div>
            <div class="card-body p-0">
                <ul class="nav nav-tabs nav-fill" id="recipientTabs">
                    <li class="nav-item">
                        <a class="nav-link active py-2" data-bs-toggle="tab" href="#tabTeachers">Teachers</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link py-2" data-bs-toggle="tab" href="#tabParents">Parents</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link py-2" data-bs-toggle="tab" href="#tabStudents">Students</a>
                    </li>
                </ul>

                <div class="tab-content">
                    <div class="tab-pane fade show active p-3" id="tabTeachers">
                        <div class="form-check mb-2 border-bottom pb-2">
                            <input class="form-check-input select-all" type="checkbox" data-target="teacher" id="selectAllTeachers">
                            <label class="form-check-label fw-bold" for="selectAllTeachers">Select All Teachers</label>
                        </div>
                        <div class="list-container overflow-auto" style="max-height: 400px;">
                            @foreach($teachers as $teacher)
                            <div class="form-check py-1 recipient-item" data-name="{{ $teacher->name }}">
                                <input class="form-check-input recipient-check" type="checkbox" value="user_{{ $teacher->id }}" data-name="{{ $teacher->name }}" data-role="Teacher">
                                <label class="form-check-label small">{{ $teacher->name }}</label>
                            </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="tab-pane fade p-3" id="tabParents">
                        <div class="form-check mb-2 border-bottom pb-2">
                            <input class="form-check-input select-all" type="checkbox" data-target="parent" id="selectAllParents">
                            <label class="form-check-label fw-bold" for="selectAllParents">Select All Parents</label>
                        </div>
                        <div class="list-container overflow-auto" style="max-height: 400px;">
                            @foreach($parents as $parent)
                            <div class="form-check py-1 recipient-item" data-name="{{ $parent->name }}">
                                <input class="form-check-input recipient-check" type="checkbox" value="user_{{ $parent->id }}" data-name="{{ $parent->name }}" data-role="Parent">
                                <label class="form-check-label small">{{ $parent->name }}</label>
                            </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="tab-pane fade p-3" id="tabStudents">
                        <div class="form-check mb-2 border-bottom pb-2">
                            <input class="form-check-input select-all" type="checkbox" data-target="student" id="selectAllStudents">
                            <label class="form-check-label fw-bold" for="selectAllStudents">Select All Students</label>
                        </div>
                        <div class="list-container overflow-auto" style="max-height: 400px;">
                            @foreach($students as $student)
                            <div class="form-check py-1 recipient-item" data-name="{{ $student->fullName() }}">
                                <input class="form-check-input recipient-check" type="checkbox" value="student_{{ $student->id }}" data-name="{{ $student->fullName() }}" data-role="Student">
                                <label class="form-check-label small">{{ $student->fullName() }}</label>
                            </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('custom-styles')
<style>
    .card-select { cursor: pointer; transition: all 0.2s; }
    .card-select:hover { border-color: #e54027 !important; background-color: #fef0ef; }
    .nav-tabs .nav-link { border-radius: 0; color: #6c757d; font-size: 0.85rem; font-weight: 600; border: none; border-bottom: 2px solid transparent; }
    .nav-tabs .nav-link.active { color: #e54027; border-bottom: 2px solid #e54027; background: transparent; }
    .recipient-check { cursor: pointer; }
    .list-container::-webkit-scrollbar { width: 4px; }
    .list-container::-webkit-scrollbar-thumb { background-color: #dee2e6; border-radius: 10px; }
</style>
@endsection

@section('custom-scripts')
<script>
    const typeRadios = document.querySelectorAll('input[name="type"]');
    const emailSubjectField = document.getElementById('emailSubjectField');
    const messageInput = document.getElementById('message');
    const smsCountLabel = document.getElementById('smsCount');
    const recipientChecks = document.querySelectorAll('.recipient-check');
    const selectedList = document.getElementById('selectedRecipientsList');
    const selectedCount = document.getElementById('selectedCount');
    const searchInput = document.getElementById('recipientSearch');

    // Toggle Subject field
    typeRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            if (radio.value === 'Email' || radio.value === 'Both') {
                emailSubjectField.classList.remove('d-none');
            } else {
                emailSubjectField.classList.add('d-none');
            }
        });
    });

    // SMS Counter
    messageInput.addEventListener('input', () => {
        const len = messageInput.value.length;
        const segments = Math.ceil(len / 160) || 1;
        smsCountLabel.innerText = `${len} characters (${segments} segments)`;
    });

    // Recipient Selection Logic
    function updateSelectedRecipients() {
        selectedList.innerHTML = '';
        const selected = [];
        recipientChecks.forEach(check => {
            if (check.checked) {
                selected.push(check.value);
                const badge = document.createElement('span');
                badge.className = 'badge bg-light text-dark border p-2 d-flex align-items-center';
                badge.innerHTML = `${check.dataset.name} <small class="ms-1 text-muted">(${check.dataset.role})</small> <i class="fas fa-times ms-2 text-danger cursor-pointer remove-badge" data-value="${check.value}"></i>`;
                selectedList.appendChild(badge);
            }
        });
        selectedCount.innerText = selected.length;
        
        // Remove badges logic
        document.querySelectorAll('.remove-badge').forEach(r => {
            r.addEventListener('click', function() {
                const val = this.getAttribute('data-value');
                document.querySelector(`.recipient-check[value="${val}"]`).checked = false;
                updateSelectedRecipients();
            });
        });
    }

    recipientChecks.forEach(check => {
        check.addEventListener('change', updateSelectedRecipients);
    });

    // Select All logic
    document.querySelectorAll('.select-all').forEach(allCheck => {
        allCheck.addEventListener('change', function() {
            const role = this.getAttribute('data-target');
            const targetContainer = document.getElementById(`tab${role.charAt(0).toUpperCase() + role.slice(1)}s`);
            targetContainer.querySelectorAll('.recipient-check').forEach(c => {
                c.checked = this.checked;
            });
            updateSelectedRecipients();
        });
    });

    // Search Logic
    searchInput.addEventListener('input', function() {
        const query = this.value.toLowerCase();
        document.querySelectorAll('.recipient-item').forEach(item => {
            const name = item.getAttribute('data-name').toLowerCase();
            if (name.includes(query)) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
</script>
@endsection
