@extends('layouts.admin')

@section('title', 'Create New User')

@section('content')
<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h3 class="card-title mb-0">Add New User</h3>
                    <a href="{{ route('admin.users.index') }}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Users
                    </a>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.users.store') }}" method="POST">
                        @csrf
                        
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h5 class="border-bottom pb-2">Auto-Generated Information</h5>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="user_id" class="form-label">User ID</label>
                                    <input type="text" class="form-control auto-generated" id="user_id" 
                                           value="USR-{{ str_pad($nextUserId, 4, '0', STR_PAD_LEFT) }}" readonly>
                                    <input type="hidden" name="user_id" value="USR-{{ str_pad($nextUserId, 4, '0', STR_PAD_LEFT) }}">
                                    <small class="form-text text-muted">Auto-generated user ID</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="license_key" class="form-label">License Key</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control auto-generated" id="license_key" 
                                               name="license_key" value="{{ old('license_key', \Illuminate\Support\Str::uuid()) }}" readonly>
                                        <button type="button" class="btn btn-outline-secondary" id="regenerateLicense">
                                            <i class="fas fa-sync-alt"></i>
                                        </button>
                                    </div>
                                    <small class="form-text text-muted">Auto-generated license key</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="license_start_date" class="form-label required-field">License Start Date</label>
                                    <input type="date" class="form-control @error('license_start_date') is-invalid @enderror" 
                                           id="license_start_date" name="license_start_date" 
                                           value="{{ old('license_start_date', date('Y-m-d')) }}" required>
                                    @error('license_start_date')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="form-text text-muted">When the license becomes active</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="expires_at" class="form-label required-field">License Expiry Date</label>
                                    <input type="date" class="form-control @error('expires_at') is-invalid @enderror" 
                                           id="expires_at" name="expires_at" value="{{ old('expires_at') }}" required>
                                    @error('expires_at')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="form-text text-muted">When the license expires</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h5 class="border-bottom pb-2">User Information</h5>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="name" class="form-label required-field">Admin Name</label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror" 
                                           id="name" name="name" value="{{ old('name') }}" required>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="email" class="form-label required-field">Email Address</label>
                                    <input type="email" class="form-control @error('email') is-invalid @enderror" 
                                           id="email" name="email" value="{{ old('email') }}" required>
                                    @error('email')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="password" class="form-label required-field">Password</label>
                                    <input type="password" class="form-control @error('password') is-invalid @enderror" 
                                           id="password" name="password" required>
                                    @error('password')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="password_confirmation" class="form-label required-field">Confirm Password</label>
                                    <input type="password" class="form-control" id="password_confirmation" 
                                           name="password_confirmation" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h5 class="border-bottom pb-2">Company Information</h5>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="company_name" class="form-label required-field">Company Name</label>
                                    <input type="text" class="form-control @error('company_name') is-invalid @enderror" 
                                           id="company_name" name="company_name" value="{{ old('company_name') }}" required>
                                    @error('company_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="business_type" class="form-label required-field">Business Type</label>
                                    <select class="form-select @error('business_type') is-invalid @enderror" id="business_type" name="business_type" required>
                                        <option value="">Select Business Type</option>
                                        <option value="retail" {{ old('business_type') == 'retail' ? 'selected' : '' }}>Retail</option>
                                        <option value="wholesale" {{ old('business_type') == 'wholesale' ? 'selected' : '' }}>Wholesale</option>
                                        <option value="manufacturing" {{ old('business_type') == 'manufacturing' ? 'selected' : '' }}>Manufacturing</option>
                                        <option value="service" {{ old('business_type') == 'service' ? 'selected' : '' }}>Service</option>
                                        <option value="other" {{ old('business_type') == 'other' ? 'selected' : '' }}>Other</option>
                                    </select>
                                    @error('business_type')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="contact_number" class="form-label required-field">Contact Number</label>
                                    <input type="tel" class="form-control @error('contact_number') is-invalid @enderror" 
                                           id="contact_number" name="contact_number" value="{{ old('contact_number') }}" required>
                                    @error('contact_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="alternate_number" class="form-label">Alternate Number</label>
                                    <input type="tel" class="form-control @error('alternate_number') is-invalid @enderror" 
                                           id="alternate_number" name="alternate_number" value="{{ old('alternate_number') }}">
                                    @error('alternate_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="website" class="form-label">Website</label>
                                    <input type="url" class="form-control @error('website') is-invalid @enderror" 
                                           id="website" name="website" value="{{ old('website') }}" placeholder="https://example.com">
                                    @error('website')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="gstin" class="form-label">GSTIN</label>
                                    <input type="text" class="form-control @error('gstin') is-invalid @enderror" 
                                           id="gstin" name="gstin" value="{{ old('gstin') }}" placeholder="e.g., 22AAAAA0000A1Z5">
                                    @error('gstin')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="address" class="form-label required-field">Address</label>
                            <textarea class="form-control @error('address') is-invalid @enderror" id="address" 
                                      name="address" rows="3" required>{{ old('address') }}</textarea>
                            @error('address')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h5 class="border-bottom pb-2">License Information</h5>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="status" class="form-label required-field">Account Status</label>
                                    <select class="form-select @error('status') is-invalid @enderror" id="status" name="status" required>
                                        <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>Inactive (Will activate on start date)</option>
                                        <option value="active" {{ old('status') == 'active' ? 'selected' : '' }}>Active (Immediate activation)</option>
                                        <option value="suspended" {{ old('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                                    </select>
                                    @error('status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="form-text text-muted">Account activation status</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label class="form-label">License Duration</label>
                                    <div class="form-control-plaintext">
                                        <span id="licenseDuration">Calculating...</span>
                                    </div>
                                    <small class="form-text text-muted">Auto-calculated duration</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="reset" class="btn btn-secondary me-md-2">Reset</button>
                            <button type="submit" class="btn btn-primary">Create User</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Phone number validation
        const phoneInputs = document.querySelectorAll('input[type="tel"]');
        phoneInputs.forEach(input => {
            input.addEventListener('input', function(e) {
                e.target.value = e.target.value.replace(/[^0-9+]/g, '');
            });
        });
        
        // Generate a new license key if needed
        document.getElementById('regenerateLicense').addEventListener('click', function() {
            document.getElementById('license_key').value = generateLicenseKey();
        });
        
        function generateLicenseKey() {
            return 'LIC-' + Math.random().toString(36).substr(2, 9).toUpperCase() + '-' + 
                   Math.random().toString(36).substr(2, 6).toUpperCase();
        }
        
        // Set default expiry date to 1 year from now
        if (!document.getElementById('expires_at').value) {
            const oneYearFromNow = new Date();
            oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
            document.getElementById('expires_at').value = oneYearFromNow.toISOString().split('T')[0];
        }
        
        // Calculate license duration
        function calculateLicenseDuration() {
            const startDate = document.getElementById('license_start_date').value;
            const endDate = document.getElementById('expires_at').value;
            
            if (startDate && endDate) {
                const start = new Date(startDate);
                const end = new Date(endDate);
                const diffTime = Math.abs(end - start);
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                
                if (diffDays < 0) {
                    document.getElementById('licenseDuration').textContent = 'Invalid (End date before start date)';
                    document.getElementById('licenseDuration').className = 'text-danger';
                } else {
                    const years = Math.floor(diffDays / 365);
                    const months = Math.floor((diffDays % 365) / 30);
                    const days = diffDays % 30;
                    
                    let duration = '';
                    if (years > 0) duration += years + ' year' + (years > 1 ? 's' : '') + ' ';
                    if (months > 0) duration += months + ' month' + (months > 1 ? 's' : '') + ' ';
                    if (days > 0) duration += days + ' day' + (days > 1 ? 's' : '');
                    
                    document.getElementById('licenseDuration').textContent = duration || '0 days';
                    document.getElementById('licenseDuration').className = 'text-success';
                }
            } else {
                document.getElementById('licenseDuration').textContent = 'Please select both dates';
                document.getElementById('licenseDuration').className = 'text-muted';
            }
        }
        
        // Add event listeners for date changes
        document.getElementById('license_start_date').addEventListener('change', calculateLicenseDuration);
        document.getElementById('expires_at').addEventListener('change', calculateLicenseDuration);
        
        // Calculate initial duration
        calculateLicenseDuration();
    });
</script>
@endsection