@extends('adminlte::page')

@section('title', 'Add New Member')

@section('content')
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Member Registration Form</h5>
                <div class="card-toolbar">
                    <a href="{{ route('memberships.index') }}" class="btn btn-secondary btn-sm">
                        <i class="cil-arrow-left"></i> Back to Members
                    </a>
                </div>
            </div>
                <form action="{{ route('memberships.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="card-body">
                        <h5 class="mb-3">Personal Information</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="first_name">First Name</label>
                                    <input type="text" name="first_name" id="first_name"
                                           class="form-control @error('first_name') is-invalid @enderror"
                                           value="{{ old('first_name') }}" required>
                                    @error('first_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="second_name">Second Name</label>
                                    <input type="text" name="second_name" id="second_name"
                                           class="form-control @error('second_name') is-invalid @enderror"
                                           value="{{ old('second_name') }}" required>
                                    @error('second_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="gender">Gender</label>
                                    <select name="gender" id="gender" class="form-control @error('gender') is-invalid @enderror" required>
                                        <option value="">Select Gender</option>
                                        <option value="male" {{ old('gender') == 'male' ? 'selected' : '' }}>Male</option>
                                        <option value="female" {{ old('gender') == 'female' ? 'selected' : '' }}>Female</option>
                                    </select>
                                    @error('gender')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="occupation">Occupation</label>
                                    <select name="occupation" id="occupation" class="form-control @error('occupation') is-invalid @enderror">
                                        <option value="">Select Occupation</option>
                                        @php
                                            $occupations = \App\Models\Occupation::active()->ordered()->get();
                                        @endphp
                                        @foreach($occupations as $occupationOption)
                                            <option value="{{ $occupationOption->name }}" {{ old('occupation') == $occupationOption->name ? 'selected' : '' }}>
                                                {{ $occupationOption->name }}
                                            </option>
                                        @endforeach
                                        <option value="other">Other (Specify)</option>
                                    </select>
                                    @error('occupation')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="id_number">ID Number</label>
                                    <input type="text" name="id_number" id="id_number"
                                           class="form-control @error('id_number') is-invalid @enderror"
                                           value="{{ old('id_number') }}" required>
                                    @error('id_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Custom Occupation Input (shown when "Other" is selected) -->
                        <div class="row" id="custom_occupation_row" style="display: none;">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="custom_occupation">Specify Occupation</label>
                                    <input type="text" name="custom_occupation" id="custom_occupation"
                                           class="form-control @error('custom_occupation') is-invalid @enderror"
                                           value="{{ old('custom_occupation') }}"
                                           placeholder="Enter your occupation">
                                    @error('custom_occupation')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="phone_number">Phone Number</label>
                                    <input type="tel" name="phone_number" id="phone_number"
                                           class="form-control @error('phone_number') is-invalid @enderror"
                                           value="{{ old('phone_number') }}" required>
                                    @error('phone_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">Email Address</label>
                                    <input type="email" name="email" id="email"
                                           class="form-control @error('email') is-invalid @enderror"
                                           value="{{ old('email') }}" required>
                                    @error('email')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="role">User Role</label>
                                    <select name="role" id="role" class="form-control @error('role') is-invalid @enderror" required>
                                        <option value="member" {{ old('role', 'member') == 'member' ? 'selected' : '' }}>Member</option>
                                        <option value="admin" {{ old('role') == 'admin' ? 'selected' : '' }}>Admin</option>
                                        <option value="manager" {{ old('role') == 'manager' ? 'selected' : '' }}>Manager</option>
                                    </select>
                                    @error('role')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="form-text text-muted">A random password will be auto-generated and sent to the member's email</small>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="branch_id">Branch</label>
                                    <select name="branch_id" id="branch_id" class="form-control @error('branch_id') is-invalid @enderror" required>
                                        <option value="">Select Branch</option>
                                        @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" {{ old('branch_id') == $branch->id ? 'selected' : '' }}>
                                            {{ $branch->name }} - {{ $branch->location }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @error('branch_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="membership_number">Membership Number</label>
                                    <input type="text" name="membership_number" id="membership_number"
                                           class="form-control @error('membership_number') is-invalid @enderror"
                                           value="{{ old('membership_number') }}" required>
                                    @error('membership_number')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="joining_date">Joining Date</label>
                                    <input type="date" name="joining_date" id="joining_date"
                                           class="form-control @error('joining_date') is-invalid @enderror"
                                           value="{{ old('joining_date', date('Y-m-d')) }}" required>
                                    @error('joining_date')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="status">Status</label>
                                    <select name="status" id="status" class="form-control @error('status') is-invalid @enderror" required>
                                        <option value="active" {{ old('status', 'active') == 'active' ? 'selected' : '' }}>Active</option>
                                        <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                                        <option value="suspended" {{ old('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                                    </select>
                                    @error('status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="share_capital">Initial Share Capital (KSh)</label>
                                    <input type="number" name="share_capital" id="share_capital" step="0.01" min="0"
                                           class="form-control @error('share_capital') is-invalid @enderror"
                                           value="{{ old('share_capital', '0.00') }}" required>
                                    @error('share_capital')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="savings_balance">Initial Savings Balance (KSh)</label>
                                    <input type="number" name="savings_balance" id="savings_balance" step="0.01" min="0"
                                           class="form-control @error('savings_balance') is-invalid @enderror"
                                           value="{{ old('savings_balance', '0.00') }}" required>
                                    @error('savings_balance')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="registration_fee">Registration Fee (KSh)</label>
                                    <input type="number" name="registration_fee" id="registration_fee" step="0.01" min="0"
                                           class="form-control @error('registration_fee') is-invalid @enderror"
                                           value="{{ old('registration_fee', '500.00') }}" required>
                                    @error('registration_fee')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="registration_fee_status">Registration Fee Status</label>
                                    <select name="registration_fee_status" id="registration_fee_status" class="form-control @error('registration_fee_status') is-invalid @enderror" required>
                                        <option value="pending" {{ old('registration_fee_status', 'pending') == 'pending' ? 'selected' : '' }}>Pending Payment</option>
                                        <option value="paid" {{ old('registration_fee_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                                        <option value="waived" {{ old('registration_fee_status') == 'waived' ? 'selected' : '' }}>Waived</option>
                                    </select>
                                    @error('registration_fee_status')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="passport_photo" class="form-label">Passport Photo</label>
                            <input type="file" name="passport_photo" id="passport_photo"
                                   class="form-control @error('passport_photo') is-invalid @enderror"
                                   accept="image/*">
                            <div class="form-text">Upload a clear passport-sized photo (JPEG, PNG, JPG - Max 2MB)</div>
                            @error('passport_photo')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="form-group">
                            <label for="notes">Notes (Optional)</label>
                            <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror"
                                      rows="3" placeholder="Any additional notes about this member...">{{ old('notes') }}</textarea>
                            @error('notes')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
            <div class="card-footer">
                <button type="submit" class="btn btn-primary">
                    <i class="cil-save"></i> Create Membership
                </button>
                <a href="{{ route('memberships.index') }}" class="btn btn-secondary ms-2">
                    <i class="cil-x"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto-generate membership number
    function generateMembershipNumber() {
        const firstName = document.getElementById('first_name').value;
        const secondName = document.getElementById('second_name').value;

        if (firstName && secondName) {
            const initials = (firstName.charAt(0) + secondName.charAt(0)).toUpperCase();
            const timestamp = Date.now().toString().slice(-4);
            const random = Math.floor(Math.random() * 100);
            return 'MS' + initials + timestamp + random.toString().padStart(2, '0');
        }

        // Fallback if names not entered yet
        const timestamp = Date.now();
        const random = Math.floor(Math.random() * 1000);
        return 'MS' + timestamp.toString().slice(-6) + random.toString().padStart(3, '0');
    }

    // Auto-fill membership number when names change
    const firstNameInput = document.getElementById('first_name');
    const secondNameInput = document.getElementById('second_name');
    const membershipInput = document.getElementById('membership_number');

    function updateMembershipNumber() {
        if (!membershipInput.value || membershipInput.value === membershipInput.defaultValue) {
            membershipInput.value = generateMembershipNumber();
        }
    }

    firstNameInput.addEventListener('input', updateMembershipNumber);
    secondNameInput.addEventListener('input', updateMembershipNumber);

    // Initial generation
    if (!membershipInput.value) {
        setTimeout(updateMembershipNumber, 100); // Small delay to ensure DOM is ready
    }

    // Handle occupation dropdown change
    const occupationSelect = document.getElementById('occupation');
    const customOccupationRow = document.getElementById('custom_occupation_row');
    const customOccupationInput = document.getElementById('custom_occupation');

    occupationSelect.addEventListener('change', function() {
        if (this.value === 'other') {
            customOccupationRow.style.display = 'block';
            customOccupationInput.required = true;
            customOccupationInput.focus();
        } else {
            customOccupationRow.style.display = 'none';
            customOccupationInput.required = false;
            customOccupationInput.value = '';
        }
    });

    // Handle form submission for custom occupation
    const form = document.querySelector('form');
    form.addEventListener('submit', function(e) {
        if (occupationSelect.value === 'other' && customOccupationInput.value.trim()) {
            // Set a hidden field to indicate this is a custom occupation
            let customOccupationHidden = document.getElementById('custom_occupation_value');
            if (!customOccupationHidden) {
                customOccupationHidden = document.createElement('input');
                customOccupationHidden.type = 'hidden';
                customOccupationHidden.name = 'custom_occupation_value';
                customOccupationHidden.id = 'custom_occupation_value';
                form.appendChild(customOccupationHidden);
            }
            customOccupationHidden.value = customOccupationInput.value.trim();
        }
    });
});
</script>
@stop

