<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compose SMS - Send Message</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        .compose-container {
            max-width: 1100px;
            margin: 0 auto;
            padding: 1.5rem;
        }
        
        .compose-card {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .contact-preview {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            background: #f8f9fa;
        }
        
        .message-preview {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 1rem;
            border-radius: 8px;
            margin-top: 1rem;
        }
        
        .char-counter {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .char-counter.warning {
            color: #fd7e14;
        }
        
        .char-counter.danger {
            color: #dc3545;
        }
        
        .sms-parts {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 0.75rem;
            margin-top: 0.5rem;
        }
        
        .btn-primary {
            background-color: #6c04f5;
            border-color: #6c04f5;
        }
        
        .btn-primary:hover {
            background-color: #5a03d1;
            border-color: #5a03d1;
        }
        
        .contact-item {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
        }
        
        .placeholder-info {
            background: #e8f5e8;
            border: 1px solid #c3e6c3;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body class="bg-light">
    <div class="container compose-container">
        <!-- Header -->
        <div class="text-center mb-4">
            <h1 class="h2 mb-3">
                <i class="fas fa-edit text-primary"></i>
                Compose SMS Message
            </h1>
            <p class="text-muted">Create and send personalized SMS to {{ count($contacts) }} selected contacts</p>
        </div>

        <!-- Navigation -->
        <div class="mb-3 d-flex gap-2">
            <a href="{{ route('sms.index') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back to Contacts
            </a>
            <a href="{{ route('admin.message-templates.index') }}" class="btn btn-outline-primary">
                <i class="fas fa-file-text"></i> Manage Templates
            </a>
        </div>

        <!-- Messages -->
        @if ($errors->any())
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i>
                <ul class="mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        <div class="row">
            <!-- Message Composer -->
            <div class="col-lg-8">
                <div class="compose-card">
                    <h4 class="mb-4">
                        <i class="fas fa-pen text-primary"></i>
                        Compose Your Message
                    </h4>

                    <!-- Placeholder Information -->
                    <div class="placeholder-info">
                        <h6><i class="fas fa-info-circle"></i> Available Placeholders:</h6>
                        <div class="row">
                            <div class="col-md-4">
                                <code>{first-name}</code> - First name only
                            </div>
                            <div class="col-md-4">
                                <code>{name}</code> - Full name
                            </div>
                            <div class="col-md-4">
                                <code>{school}</code> - School name
                            </div>
                        </div>
                    </div>

                    <form method="POST" action="{{ route('sms.send') }}" id="sms-form">
                        @csrf
                        
                        <!-- Hidden inputs for selected contacts -->
                        @foreach($contacts as $contact)
                            <input type="hidden" name="selected_contacts[]" value="{{ $contact->id }}">
                        @endforeach

                        <!-- Campaign Name -->
                        <div class="mb-3">
                            <label for="campaign_name" class="form-label">Campaign Name (Optional)</label>
                            <input type="text" class="form-control" id="campaign_name" name="campaign_name" 
                                   value="{{ old('campaign_name', 'TeenzFest 2025 - ' . date('M d, Y')) }}"
                                   placeholder="e.g., TeenzFest 2025 - Early Bird">
                            <small class="text-muted">This helps you organize and track your SMS campaigns</small>
                        </div>

                        <!-- Message Template Dropdown -->
                        <div class="mb-3">
                            <label for="template_select" class="form-label">Message Template (Optional)</label>
                            <select class="form-control" id="template_select" onchange="loadTemplate()">
                                <option value="">-- Select a template --</option>
                                @if(isset($messageTemplates))
                                    @foreach($messageTemplates as $template)
                                        <option value="{{ $template->id }}" data-content="{{ htmlspecialchars($template->content) }}">
                                            {{ $template->name }}
                                            @if($template->description)
                                                - {{ $template->description }}
                                            @endif
                                        </option>
                                    @endforeach
                                @endif
                            </select>
                            <small class="text-muted">Choose a pre-defined template to populate the message content</small>
                        </div>

                        <!-- Message Content -->
                        <div class="mb-3">
                            <label for="message" class="form-label">Message Content</label>
                            <textarea class="form-control" id="message" name="message" rows="6" 
                                      placeholder="Enter your SMS message here..." required>{{ old('message') }}</textarea>
                            
                            <!-- Character Counter -->
                            <div class="d-flex justify-content-between align-items-center mt-2">
                                <div class="char-counter" id="char-counter">
                                    <span id="char-count">0</span> characters
                                </div>
                                <div class="sms-parts" id="sms-parts" style="display: none;">
                                    <i class="fas fa-cut"></i>
                                    Will be sent as <strong id="parts-count">1</strong> SMS part(s)
                                    <br><small> <span id="estimated-cost">{{ count($contacts) }}</span></small>
                                </div>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="button" class="btn btn-outline-primary me-md-2" onclick="previewMessage()">
                                <i class="fas fa-eye"></i> Preview Message
                            </button>
                            <button type="submit" class="btn btn-success btn-lg" id="send-btn">
                                <i class="fas fa-paper-plane"></i> Send SMS to {{ count($contacts) }} Contacts
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Message Preview -->
                <div class="compose-card" id="preview-section" style="display: none;">
                    <h5>
                        <i class="fas fa-eye text-info"></i>
                        Message Preview
                    </h5>
                    <div class="message-preview" id="preview-content">
                        <!-- Preview will be populated by JavaScript -->
                    </div>
                </div>
            </div>

            <!-- Selected Contacts -->
            <div class="col-lg-4">
                <div class="compose-card">
                    <h5 class="mb-3">
                        <i class="fas fa-users text-primary"></i>
                        Selected Contacts ({{ count($contacts) }})
                    </h5>
                    
                    <div class="contact-preview">
                        @foreach($contacts as $contact)
                            <div class="contact-item">
                                <div class="fw-bold">{{ $contact->name }}</div>
                                <div class="text-muted small">
                                    <i class="fas fa-phone"></i> {{ $contact->phone_no }}
                                </div>
                                @if($contact->school_name)
                                    <div class="text-muted small">
                                        <i class="fas fa-school"></i> {{ $contact->school_name }}
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    </div>
                    
                    <!-- Summary -->
                    <div class="mt-3 pt-3 border-top">
                        <div class="row text-center">
                            <div class="col-6">
                                <strong>{{ count($contacts) }}</strong>
                                <br><small class="text-muted">Recipients</small>
                            </div>
                            <div class="col-6">
                                <strong id="total-estimated-cost">~KSH {{ count($contacts) }}</strong>
                                <br><small class="text-muted">Est. Cost</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const messageTextarea = document.getElementById('message');
            const charCounter = document.getElementById('char-counter');
            const charCountSpan = document.getElementById('char-count');
            const smsParts = document.getElementById('sms-parts');
            const partsCountSpan = document.getElementById('parts-count');
            const estimatedCostSpan = document.getElementById('estimated-cost');
            const totalEstimatedCostSpan = document.getElementById('total-estimated-cost');
            const sendBtn = document.getElementById('send-btn');
            const smsForm = document.getElementById('sms-form');
            
            const recipientCount = {{ count($contacts) }};
            const costPerSms = 1.00; // KSH per SMS

            function updateCharacterCount() {
                const message = messageTextarea.value;
                const charCount = message.length;
                const maxChars = 160;
                const parts = Math.ceil(charCount / maxChars) || 1;
                const totalCost = parts * recipientCount * costPerSms;

                charCountSpan.textContent = charCount;
                partsCountSpan.textContent = parts;
                estimatedCostSpan.textContent = totalCost.toFixed(2);
                totalEstimatedCostSpan.textContent = '~KSH ' + totalCost.toFixed(2);

                // Update character counter styling
                charCounter.className = 'char-counter';
                if (charCount > maxChars * 2) {
                    charCounter.classList.add('danger');
                } else if (charCount > maxChars) {
                    charCounter.classList.add('warning');
                }

                // Show/hide SMS parts info
                if (charCount > 0) {
                    smsParts.style.display = 'block';
                } else {
                    smsParts.style.display = 'none';
                }
            }

            // Update character count on input
            messageTextarea.addEventListener('input', updateCharacterCount);

            // Form submission with loading state
            smsForm.addEventListener('submit', function(e) {
                if (!confirm(`Are you sure you want to send this SMS to ${recipientCount} contacts?`)) {
                    e.preventDefault();
                    return;
                }

                sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending SMS...';
                sendBtn.disabled = true;
            });

            // Initialize
            updateCharacterCount();
        });

        function loadTemplate() {
            const templateSelect = document.getElementById('template_select');
            const messageTextarea = document.getElementById('message');
            const selectedOption = templateSelect.options[templateSelect.selectedIndex];
            
            if (selectedOption.value && selectedOption.dataset.content) {
                messageTextarea.value = selectedOption.dataset.content;
                updateCharacterCount(); // Update character count after loading template
            }
        }

        function previewMessage() {
            const message = document.getElementById('message').value;
            const previewSection = document.getElementById('preview-section');
            const previewContent = document.getElementById('preview-content');
            
            if (!message.trim()) {
                alert('Please enter a message to preview.');
                return;
            }

            // Sample contact for preview
            const sampleContact = @json($contacts->first());
            const firstName = sampleContact.name.split(' ')[0];
            
            // Replace placeholders
            let previewMessage = message
                .replace(/\{first-name\}/g, firstName)
                .replace(/\{name\}/g, sampleContact.name)
                .replace(/\{school\}/g, sampleContact.school_name || 'Unknown School');

            previewContent.innerHTML = `
                <strong>Preview for:</strong> ${sampleContact.name} (${sampleContact.phone_no})<br>
                <strong>School:</strong> ${sampleContact.school_name || 'Unknown'}<br><br>
                <div style="background: white; padding: 1rem; border-radius: 8px; border: 1px solid #ddd;">
                    ${previewMessage.replace(/\n/g, '<br>')}
                </div>
                <br>
                <small class="text-muted">
                    <i class="fas fa-info-circle"></i>
                    This preview shows how the message will appear to the first selected contact.
                    Other contacts will see their personalized version.
                </small>
            `;
            
            previewSection.style.display = 'block';
            previewSection.scrollIntoView({ behavior: 'smooth' });
        }
    </script>
</body>
</html>