@extends('FrontUser.layouts.app')

@section('title', 'Schedule New Call')

@section('content')
<div class="call-create-page">
    <!-- Page Header -->
    <div class="page-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title">Schedule New Call</h2>
                <p class="page-subtitle">Book a call with your preferred package</p>
            </div>
            <div class="page-actions">
                <a href="{{ route('user.calls.index') }}" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back to Calls
                </a>
            </div>
        </div>
    </div>

    @if(!$hasBalance)
    <div class="alert alert-warning">
        <i class="fas fa-exclamation-triangle"></i>
        <strong>Insufficient Balance:</strong> You need at least ₹{{ $minBalance }} to schedule a call. 
        <a href="{{ route('user.wallet.index') }}" class="alert-link">Add funds to your wallet</a>.
    </div>
    @endif

    @if(isset($licenseStatus) && !$licenseStatus['isActive'])
    <div class="alert alert-info">
        <i class="fas fa-info-circle"></i>
        <strong>License Status:</strong> 
        @if($licenseStatus['startsAt'] && $licenseStatus['startsAt']->isFuture())
            Your license will be activated on {{ $licenseStatus['startsAt']->format('M d, Y') }}. 
            You can schedule calls after that date.
        @elseif($licenseStatus['expiresAt'] && $licenseStatus['expiresAt']->isPast())
            Your license has expired on {{ $licenseStatus['expiresAt']->format('M d, Y') }}. 
            Please contact support to renew your license.
        @else
            Your license is currently inactive. Please contact support for assistance.
        @endif
    </div>
    @endif

    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Call Details</h5>
                </div>
                <div class="card-body">
                    <form id="callForm">
                        @csrf
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Phone Number</label>
                                    <input type="tel" class="form-control" name="phone_number" placeholder="Enter phone number" required>
                                    <small class="form-text">Include country code (e.g., +91 for India)</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="form-label">Scheduled Time</label>
                                    <input type="datetime-local" class="form-control" name="scheduled_time" min="{{ date('Y-m-d\TH:i') }}">
                                    <small class="form-text">Leave empty for immediate call (5 minutes)</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Call Package</label>
                            <div class="package-selection">
                                @foreach($callPackages as $package)
                                <div class="package-option">
                                    <input type="radio" name="package" value="{{ $package['id'] }}" id="package_{{ $package['id'] }}" required>
                                    <label for="package_{{ $package['id'] }}">
                                        <div class="package-card">
                                            <div class="package-header">
                                                <h6>{{ $package['name'] }}</h6>
                                                <div class="package-price">₹{{ $package['price'] }}</div>
                                            </div>
                                            <div class="package-duration">{{ $package['duration'] }} minutes</div>
                                            <div class="package-features">
                                                <ul>
                                                    @foreach($package['features'] as $feature)
                                                    <li>{{ $feature }}</li>
                                                    @endforeach
                                                </ul>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                                @endforeach
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="terms" required>
                                <label class="form-check-label" for="terms">
                                    I agree to the <a href="#" class="text-primary">Terms of Service</a> and <a href="#" class="text-primary">Privacy Policy</a>
                                </label>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-lg" {{ !$hasBalance ? 'disabled' : '' }}>
                            <i class="fas fa-phone"></i> Schedule Call
                        </button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Call Summary</h5>
                </div>
                <div class="card-body">
                    <div class="summary-item">
                        <div class="summary-label">Selected Package:</div>
                        <div class="summary-value" id="selectedPackage">None</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">Duration:</div>
                        <div class="summary-value" id="selectedDuration">0 minutes</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">Cost:</div>
                        <div class="summary-value" id="selectedCost">₹0.00</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-label">Your Balance:</div>
                        <div class="summary-value">₹{{ number_format(Auth::user()->wallet_balance ?? 0, 2) }}</div>
                    </div>
                    <hr>
                    <div class="summary-item total">
                        <div class="summary-label">Total Cost:</div>
                        <div class="summary-value" id="totalCost">₹0.00</div>
                    </div>
                </div>
            </div>
            
            @if(isset($licenseStatus))
            <div class="card mt-3">
                <div class="card-header">
                    <h5 class="card-title">License Information</h5>
                </div>
                <div class="card-body">
                    <div class="license-info">
                        <div class="license-item">
                            <div class="license-label">Status:</div>
                            <div class="license-value">
                                <span class="badge bg-{{ $licenseStatus['isActive'] ? 'success' : 'warning' }}">
                                    {{ $licenseStatus['isActive'] ? 'Active' : 'Inactive' }}
                                </span>
                            </div>
                        </div>
                        @if($licenseStatus['startsAt'])
                        <div class="license-item">
                            <div class="license-label">Start Date:</div>
                            <div class="license-value">{{ $licenseStatus['startsAt']->format('M d, Y') }}</div>
                        </div>
                        @endif
                        @if($licenseStatus['expiresAt'])
                        <div class="license-item">
                            <div class="license-label">Expiry Date:</div>
                            <div class="license-value">{{ $licenseStatus['expiresAt']->format('M d, Y') }}</div>
                        </div>
                        @endif
                        @if($licenseStatus['key'])
                        <div class="license-item">
                            <div class="license-label">License Key:</div>
                            <div class="license-value">
                                <code class="text-muted">{{ substr($licenseStatus['key'], 0, 8) }}...</code>
                            </div>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
            @endif

            <div class="card mt-3">
                <div class="card-header">
                    <h5 class="card-title">Call Tips</h5>
                </div>
                <div class="card-body">
                    <div class="tip-item">
                        <i class="fas fa-lightbulb text-warning"></i>
                        <div>
                            <strong>Best Time:</strong> Schedule calls during business hours for better connectivity.
                        </div>
                    </div>
                    <div class="tip-item">
                        <i class="fas fa-shield-alt text-success"></i>
                        <div>
                            <strong>Secure:</strong> All calls are encrypted and recorded for quality assurance.
                        </div>
                    </div>
                    <div class="tip-item">
                        <i class="fas fa-headset text-info"></i>
                        <div>
                            <strong>Support:</strong> 24/7 customer support available for any issues.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('styles')
<style>
.license-info {
    font-size: 0.9rem;
}

.license-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 0;
    border-bottom: 1px solid #f1f3f4;
}

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

.license-label {
    font-weight: 500;
    color: #6c757d;
}

.license-value {
    font-weight: 600;
    color: #2c3e50;
}

.license-value code {
    font-size: 0.8rem;
    background: #f8f9fa;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
}
</style>
@endsection

@section('scripts')
<script>
const packages = @json($callPackages);

// Update summary when package is selected
document.querySelectorAll('input[name="package"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const package = packages.find(p => p.id === this.value);
        if (package) {
            document.getElementById('selectedPackage').textContent = package.name;
            document.getElementById('selectedDuration').textContent = package.duration + ' minutes';
            document.getElementById('selectedCost').textContent = '₹' + package.price;
            document.getElementById('totalCost').textContent = '₹' + package.price;
        }
    });
});

// Form submission
document.getElementById('callForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Scheduling...';
    submitBtn.disabled = true;
    
    fetch('{{ route("user.calls.store") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            setTimeout(() => {
                window.location.href = '{{ route("user.calls.index") }}';
            }, 2000);
        } else {
            showNotification('error', data.message);
        }
    })
    .catch(error => {
        showNotification('error', 'An error occurred. Please try again.');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Show notification
function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'error' ? 'danger' : 'info'} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 5000);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('Call creation page loaded successfully!');
});
</script>
@endsection
