@extends('layouts.app')

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

@section('content')
@php
    $selectedBranchId = old('branch_id', $customer->branch_id ?? $defaultBranchId ?? null);
@endphp
<form method="POST" action="{{ $editing ? route('tenant.customers.update', $customer) : route('tenant.customers.store') }}" enctype="multipart/form-data" class="customer-form-card member-form-card">
    @csrf
    @if($editing) @method('PATCH') @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">{{ $editing ? 'Member profile' : 'New member profile' }}</div>
                <h2 class="h4 mb-1">{{ $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">
                    {{ $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="{{ 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> {{ $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>{{ $editing ? $customer->account_number : 'Auto generated' }}</strong>
        </div>
        <div>
            <i class="bi bi-shield-check"></i>
            <span>KYC status</span>
            <strong>{{ ucfirst(old('kyc_status', $customer->kyc_status ?? 'pending')) }}</strong>
        </div>
        <div>
            <i class="bi bi-person-badge"></i>
            <span>Account officer</span>
            <strong>{{ $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>{{ $editing ? ($customer->user_id ? 'Enabled' : 'Not enabled') : 'Optional' }}</strong>
        </div>
    </div>

    @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">{{ $errors->first() }}</div>
        </div>
    @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="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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>
                        @foreach(['male','female'] as $gender)
                            <option @selected(old('gender', $customer->gender ?? '') === $gender) value="{{ $gender }}">{{ ucfirst($gender) }}</option>
                        @endforeach
                    </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="{{ 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="{{ 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="{{ 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">
                @if($showBranchField ?? false)
                    <div class="col-md-6">
                        <label class="form-label">Branch</label>
                        <select name="branch_id" class="form-select" required>
                            @foreach($branches as $branch)
                                <option value="{{ $branch->id }}" @selected((string) $selectedBranchId === (string) $branch->id)>{{ $branch->name }}</option>
                            @endforeach
                        </select>
                    </div>
                @else
                    <input type="hidden" name="branch_id" value="{{ $selectedBranchId }}">
                @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>
                        @foreach($customerGroups as $group)
                            <option value="{{ $group->id }}" @selected((string) old('customer_group_id', $customer->customer_group_id ?? '') === (string) $group->id)>{{ $group->name }}</option>
                        @endforeach
                    </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="{{ 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>
                    @if($canAssignAccountOfficers ?? false)
                        <select name="account_officer_id" class="form-select">
                            <option value="">Unassigned</option>
                            @foreach($accountOfficers as $officer)
                                <option value="{{ $officer->id }}" @selected((string) old('account_officer_id', $customer->account_officer_id ?? '') === (string) $officer->id)>{{ $officer->name }} - {{ $officer->roleLabel() }}</option>
                            @endforeach
                        </select>
                        <div class="form-text">Assigned members are visible only to this officer and tenant admin.</div>
                    @else
                        <div class="form-control bg-light">{{ $editing ? ($customer->accountOfficer?->name ?? 'Unassigned') : auth()->user()->name }}</div>
                        <div class="form-text">{{ $editing ? 'Only tenant admin can change this assignment.' : 'New members you create are assigned to you automatically.' }}</div>
                    @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 @selected(old('status', $customer->status ?? 'active') === 'active') value="active">Active</option>
                        <option @selected(old('status', $customer->status ?? '') === 'inactive') value="inactive">Inactive</option>
                        <option @selected(old('status', $customer->status ?? '') === 'suspended') 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 @selected(old('kyc_status', $customer->kyc_status ?? 'pending') === 'pending') value="pending">Pending</option>
                        <option @selected(old('kyc_status', $customer->kyc_status ?? '') === 'verified') value="verified">Verified</option>
                        <option @selected(old('kyc_status', $customer->kyc_status ?? '') === 'rejected') 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">{{ old('address', $customer->address ?? '') }}</textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label">City</label>
                    <input name="city" value="{{ old('city', $customer->city ?? '') }}" class="form-control">
                </div>
                <div class="col-md-6">
                    <label class="form-label">State</label>
                    <input name="state" value="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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="{{ 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>
            @unless($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" @checked(old('create_portal'))>
                                <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>
            @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>
            @endunless
        </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="{{ route('tenant.customers.index') }}" class="btn btn-outline-secondary">Cancel</a>
            <button class="btn btn-primary"><i class="bi bi-save me-1"></i> {{ $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>
@endsection
