<?php
    $customer = $customer ?? null;
    $editing = $editing ?? isset($customer);
?>
<?php $__env->startSection('title', $editing ? 'Edit Member' : 'New Member'); ?>
<?php $__env->startSection('page-title', $editing ? 'Edit Member' : 'Register Member'); ?>
<?php $__env->startSection('page-subtitle', 'Capture member bio-data, assignment, KYC, address, and guarantor information'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $selectedBranchId = old('branch_id', $customer->branch_id ?? $defaultBranchId ?? null);
?>
<form method="POST" action="<?php echo e($editing ? route('tenant.customers.update', $customer) : route('tenant.customers.store')); ?>" enctype="multipart/form-data" class="customer-form-card member-form-card">
    <?php echo csrf_field(); ?>
    <?php if($editing): ?> <?php echo method_field('PATCH'); ?> <?php endif; ?>

    <div class="customer-form-hero member-form-hero">
        <div class="member-form-title">
            <div class="member-form-icon"><i class="bi bi-person-vcard"></i></div>
            <div>
                <div class="text-muted small"><?php echo e($editing ? 'Member profile' : 'New member profile'); ?></div>
                <h2 class="h4 mb-1"><?php echo e($editing ? $customer->fullName() : 'Register a new member'); ?></h2>
                <p class="mb-0 text-muted">Capture identity, assignment, KYC, guarantor, and portal access details in a clean step-by-step form.</p>
                <div class="small fw-semibold text-primary mt-2">
                    <?php echo e($editing ? '10-digit account number: '.$customer->account_number : 'A 10-digit account number will be generated automatically after saving.'); ?>

                </div>
            </div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="<?php echo e(route('tenant.customers.index')); ?>" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Members</a>
            <button class="btn btn-primary"><i class="bi bi-save me-1"></i> <?php echo e($editing ? 'Save member' : 'Register member'); ?></button>
        </div>
    </div>

    <div class="member-form-summary">
        <div>
            <i class="bi bi-credit-card-2-front"></i>
            <span>Account number</span>
            <strong><?php echo e($editing ? $customer->account_number : 'Auto generated'); ?></strong>
        </div>
        <div>
            <i class="bi bi-shield-check"></i>
            <span>KYC status</span>
            <strong><?php echo e(ucfirst(old('kyc_status', $customer->kyc_status ?? 'pending'))); ?></strong>
        </div>
        <div>
            <i class="bi bi-person-badge"></i>
            <span>Account officer</span>
            <strong><?php echo e($editing ? ($customer->accountOfficer?->name ?? 'Unassigned') : (($canAssignAccountOfficers ?? false) ? 'Optional' : auth()->user()->name)); ?></strong>
        </div>
        <div>
            <i class="bi bi-phone"></i>
            <span>Member portal</span>
            <strong><?php echo e($editing ? ($customer->user_id ? 'Enabled' : 'Not enabled') : 'Optional'); ?></strong>
        </div>
    </div>

    <?php if($errors->any()): ?>
        <div class="alert alert-warning border-0 mb-3">
            <div class="fw-semibold mb-1">Please review the highlighted fields.</div>
            <div class="small"><?php echo e($errors->first()); ?></div>
        </div>
    <?php endif; ?>

    <ul class="nav nav-pills customer-form-tabs" id="customerFormTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="personal-tab" data-bs-toggle="tab" data-bs-target="#personal-pane" type="button" role="tab"><i class="bi bi-person me-1"></i> Personal</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="assignment-tab" data-bs-toggle="tab" data-bs-target="#assignment-pane" type="button" role="tab"><i class="bi bi-diagram-3 me-1"></i> Assignment</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="kyc-tab" data-bs-toggle="tab" data-bs-target="#kyc-pane" type="button" role="tab"><i class="bi bi-shield-check me-1"></i> Address & KYC</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="guarantor-tab" data-bs-toggle="tab" data-bs-target="#guarantor-pane" type="button" role="tab"><i class="bi bi-person-vcard me-1"></i> Guarantor</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="portal-tab" data-bs-toggle="tab" data-bs-target="#portal-pane" type="button" role="tab"><i class="bi bi-phone me-1"></i> Portal</button>
        </li>
    </ul>

    <div class="tab-content customer-form-body">
        <div class="tab-pane fade show active" id="personal-pane" role="tabpanel" aria-labelledby="personal-tab">
            <div class="customer-form-section-title">
                <div>
                    <h3>Personal Information</h3>
                    <p>Basic identity and contact information for the member.</p>
                </div>
            </div>
            <div class="row g-3">
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">First name <span class="text-danger">*</span></label>
                    <input name="first_name" value="<?php echo e(old('first_name', $customer->first_name ?? '')); ?>" class="form-control form-control-lg" required>
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Middle name</label>
                    <input name="middle_name" value="<?php echo e(old('middle_name', $customer->middle_name ?? '')); ?>" class="form-control form-control-lg">
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Last name <span class="text-danger">*</span></label>
                    <input name="last_name" value="<?php echo e(old('last_name', $customer->last_name ?? '')); ?>" class="form-control form-control-lg" required>
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Phone <span class="text-danger">*</span></label>
                    <input name="phone" value="<?php echo e(old('phone', $customer->phone ?? '')); ?>" class="form-control form-control-lg" required>
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Email</label>
                    <input name="email" type="email" value="<?php echo e(old('email', $customer->email ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Gender</label>
                    <select name="gender" class="form-select">
                        <option value="">Select gender</option>
                        <?php $__currentLoopData = ['male','female']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $gender): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option <?php if(old('gender', $customer->gender ?? '') === $gender): echo 'selected'; endif; ?> value="<?php echo e($gender); ?>"><?php echo e(ucfirst($gender)); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Date of birth</label>
                    <input name="date_of_birth" type="date" value="<?php echo e(old('date_of_birth', isset($customer) && $customer->date_of_birth ? $customer->date_of_birth->format('Y-m-d') : '')); ?>" class="form-control" data-date-of-birth>
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Age</label>
                    <input value="<?php echo e(isset($customer) ? $customer->age() : ''); ?>" class="form-control bg-light" data-age-field readonly placeholder="Auto calculated">
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Occupation</label>
                    <input name="occupation" value="<?php echo e(old('occupation', $customer->occupation ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6 col-xl-4">
                    <label class="form-label">Photo</label>
                    <input name="photo" type="file" accept="image/*" class="form-control">
                    <div class="form-text">JPG or PNG, maximum 2MB.</div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="assignment-pane" role="tabpanel" aria-labelledby="assignment-tab">
            <div class="customer-form-section-title">
                <div>
                    <h3>Assignment & Status</h3>
                    <p>Control branch, account officer visibility, member status, and KYC status.</p>
                </div>
            </div>
            <div class="row g-3">
                <?php if($showBranchField ?? false): ?>
                    <div class="col-md-6">
                        <label class="form-label">Branch</label>
                        <select name="branch_id" class="form-select" required>
                            <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($branch->id); ?>" <?php if((string) $selectedBranchId === (string) $branch->id): echo 'selected'; endif; ?>><?php echo e($branch->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                <?php else: ?>
                    <input type="hidden" name="branch_id" value="<?php echo e($selectedBranchId); ?>">
                <?php endif; ?>
                <div class="col-md-6">
                    <label class="form-label">Member group</label>
                    <select name="customer_group_id" class="form-select">
                        <option value="">Ungrouped</option>
                        <?php $__currentLoopData = $customerGroups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($group->id); ?>" <?php if((string) old('customer_group_id', $customer->customer_group_id ?? '') === (string) $group->id): echo 'selected'; endif; ?>><?php echo e($group->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <div class="form-text">Use groups for associations, cooperatives, markets, schools, or employer groups.</div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Create new group</label>
                    <input name="new_customer_group_name" value="<?php echo e(old('new_customer_group_name')); ?>" class="form-control" placeholder="e.g. Ariaria Market Traders">
                    <div class="form-text">Typing a new group name will override the selected group.</div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Account officer</label>
                    <?php if($canAssignAccountOfficers ?? false): ?>
                        <select name="account_officer_id" class="form-select">
                            <option value="">Unassigned</option>
                            <?php $__currentLoopData = $accountOfficers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $officer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($officer->id); ?>" <?php if((string) old('account_officer_id', $customer->account_officer_id ?? '') === (string) $officer->id): echo 'selected'; endif; ?>><?php echo e($officer->name); ?> - <?php echo e($officer->roleLabel()); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <div class="form-text">Assigned members are visible only to this officer and tenant admin.</div>
                    <?php else: ?>
                        <div class="form-control bg-light"><?php echo e($editing ? ($customer->accountOfficer?->name ?? 'Unassigned') : auth()->user()->name); ?></div>
                        <div class="form-text"><?php echo e($editing ? 'Only tenant admin can change this assignment.' : 'New members you create are assigned to you automatically.'); ?></div>
                    <?php endif; ?>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Member status <span class="text-danger">*</span></label>
                    <select name="status" class="form-select" required>
                        <option <?php if(old('status', $customer->status ?? 'active') === 'active'): echo 'selected'; endif; ?> value="active">Active</option>
                        <option <?php if(old('status', $customer->status ?? '') === 'inactive'): echo 'selected'; endif; ?> value="inactive">Inactive</option>
                        <option <?php if(old('status', $customer->status ?? '') === 'suspended'): echo 'selected'; endif; ?> value="suspended">Suspended</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">KYC status <span class="text-danger">*</span></label>
                    <select name="kyc_status" class="form-select" required>
                        <option <?php if(old('kyc_status', $customer->kyc_status ?? 'pending') === 'pending'): echo 'selected'; endif; ?> value="pending">Pending</option>
                        <option <?php if(old('kyc_status', $customer->kyc_status ?? '') === 'verified'): echo 'selected'; endif; ?> value="verified">Verified</option>
                        <option <?php if(old('kyc_status', $customer->kyc_status ?? '') === 'rejected'): echo 'selected'; endif; ?> value="rejected">Rejected</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="kyc-pane" role="tabpanel" aria-labelledby="kyc-tab">
            <div class="customer-form-section-title">
                <div>
                    <h3>Address & KYC</h3>
                    <p>Residential details and government identification records.</p>
                </div>
            </div>
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label">Address</label>
                    <textarea name="address" rows="3" class="form-control"><?php echo e(old('address', $customer->address ?? '')); ?></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">City</label>
                    <input name="city" value="<?php echo e(old('city', $customer->city ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">State</label>
                    <input name="state" value="<?php echo e(old('state', $customer->state ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">ID type</label>
                    <input name="id_type" value="<?php echo e(old('id_type', $customer->id_type ?? '')); ?>" class="form-control" placeholder="NIN, BVN, Voter card">
                </div>
                <div class="col-md-4">
                    <label class="form-label">ID number</label>
                    <input name="id_number" value="<?php echo e(old('id_number', $customer->id_number ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-4">
                    <label class="form-label">BVN</label>
                    <div class="input-group">
                        <input name="bvn" value="<?php echo e(old('bvn', $customer->bvn ?? '')); ?>" class="form-control" inputmode="numeric" maxlength="11" placeholder="11 digits" data-identity-number="BVN">
                        <button class="btn btn-outline-primary" type="button" data-verify-identity="bvn">Verify</button>
                    </div>
                    <div class="form-text">Used for automatic KYC checks and virtual account providers that require BVN.</div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">NIN</label>
                    <div class="input-group">
                        <input name="nin" value="<?php echo e(old('nin', $customer->nin ?? '')); ?>" class="form-control" inputmode="numeric" maxlength="11" placeholder="11 digits" data-identity-number="NIN">
                        <button class="btn btn-outline-primary" type="button" data-verify-identity="nin">Verify</button>
                    </div>
                    <div class="form-text">Used for automatic KYC checks and providers that accept NIN.</div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <div class="small text-muted" data-identity-feedback>Enter 11 digits, then click Verify for an immediate format check. Full KYC runs when the member is saved.</div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">ID upload</label>
                    <input name="id_upload" type="file" class="form-control">
                    <div class="form-text">JPG, PNG, or PDF, maximum 4MB.</div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="guarantor-pane" role="tabpanel" aria-labelledby="guarantor-tab">
            <div class="customer-form-section-title">
                <div>
                    <h3>Guarantor Details</h3>
                    <p>Optional guarantor contact information for loan checks.</p>
                </div>
            </div>
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Guarantor name</label>
                    <input name="guarantor_name" value="<?php echo e(old('guarantor_name', $customer->guarantor_name ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Guarantor phone</label>
                    <input name="guarantor_phone" value="<?php echo e(old('guarantor_phone', $customer->guarantor_phone ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Relationship</label>
                    <input name="guarantor_relationship" value="<?php echo e(old('guarantor_relationship', $customer->guarantor_relationship ?? '')); ?>" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Guarantor address</label>
                    <input name="guarantor_address" value="<?php echo e(old('guarantor_address', $customer->guarantor_address ?? '')); ?>" class="form-control">
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="portal-pane" role="tabpanel" aria-labelledby="portal-tab">
            <div class="customer-form-section-title">
                <div>
                    <h3>Member Portal</h3>
                    <p>Optional member login setup for self-service savings and loan requests.</p>
                </div>
            </div>
            <?php if (! ($editing)): ?>
                <div class="row g-3">
                    <div class="col-lg-6">
                        <label class="form-label">Portal password</label>
                        <input name="portal_password" type="password" class="form-control" placeholder="Minimum 8 characters">
                        <div class="form-text">Email is required when creating a member login.</div>
                    </div>
                    <div class="col-lg-6">
                        <div class="customer-form-option">
                            <label class="form-check m-0">
                                <input class="form-check-input" name="create_portal" value="1" type="checkbox" <?php if(old('create_portal')): echo 'checked'; endif; ?>>
                                <span class="form-check-label fw-semibold">Create member login</span>
                            </label>
                            <div class="text-muted small mt-2">The member will be able to access their dashboard with the email and password provided.</div>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="customer-form-option">
                    <div class="fw-semibold">Portal login is managed from the linked member account.</div>
                    <div class="text-muted small mt-1">This edit form keeps the member profile details separate from login security changes.</div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="customer-submit-bar">
        <div class="text-muted small">
            Required fields are marked with <span class="text-danger">*</span>.
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="<?php echo e(route('tenant.customers.index')); ?>" class="btn btn-outline-secondary">Cancel</a>
            <button class="btn btn-primary"><i class="bi bi-save me-1"></i> <?php echo e($editing ? 'Save member' : 'Register member'); ?></button>
        </div>
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const dob = document.querySelector('[data-date-of-birth]');
    const age = document.querySelector('[data-age-field]');

    const updateAge = () => {
        if (!dob || !age || !dob.value) {
            if (age) age.value = '';
            return;
        }

        const birthDate = new Date(dob.value + 'T00:00:00');
        const today = new Date();
        let years = today.getFullYear() - birthDate.getFullYear();
        const monthDelta = today.getMonth() - birthDate.getMonth();

        if (monthDelta < 0 || (monthDelta === 0 && today.getDate() < birthDate.getDate())) {
            years--;
        }

        age.value = Number.isFinite(years) && years >= 0 ? years : '';
    };

    dob?.addEventListener('change', updateAge);
    updateAge();

    document.querySelectorAll('[data-verify-identity]').forEach((button) => {
        button.addEventListener('click', () => {
            const field = document.querySelector(`[name="${button.dataset.verifyIdentity}"]`);
            const feedback = document.querySelector('[data-identity-feedback]');
            const label = field?.dataset.identityNumber || 'Identity number';
            const value = String(field?.value || '').trim();

            if (/^\d{11}$/.test(value)) {
                feedback.textContent = `${label} format verified. Saving the member will run automatic KYC.`;
                feedback.classList.remove('text-danger', 'text-muted');
                feedback.classList.add('text-success');
                return;
            }

            feedback.textContent = `${label} must be exactly 11 digits.`;
            feedback.classList.remove('text-success', 'text-muted');
            feedback.classList.add('text-danger');
            field?.focus();
        });
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Polite hp\Documents\Codex\2026-05-08\build-a-complete-production-ready-saas\microfinance-saas\resources\views/tenant/customers/create.blade.php ENDPATH**/ ?>