@extends('layouts.app')
@section('content')
<div class="container">
<form method="POST" action="{{ route('admin_fit.users.update', $user) }}" enctype="multipart/form-data">
@csrf
@method('PUT')
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center  bg-dark text-white">
                    <span>Editar Usuario</span>
                    <div class="d-flex gap-2">
                        <button
                            type="button"
                            class="btn btn-sm btn-primary"
                            id="btn-user-sales-modal"
                            data-user-id="{{ $user->id }}"
                            data-sales-url="{{ route('admin_fit.users.sales', $user) }}"
                        >
                            <i class="bi bi-bar-chart-line me-1"></i>
                            Ver ventas
                        </button>
                        <button
                            type="button"
                            class="btn btn-sm btn-success"
                            id="btn-user-membership-sale"
                            data-user-name="{{ $user->name }}"
                            data-preview-url="{{ route('admin_fit.users.membership_sale_preview', $user) }}"
                            data-create-url="{{ route('admin_fit.users.membership_sale_create', $user) }}"
                        >
                            <i class="bi bi-file-earmark-plus me-1"></i>
                            Nuevo documento
                        </button>
                        <a href="{{ route('admin_fit.pay.create', ['user_id' => $user->id]) }}" class="btn btn-sm btn-warning"><i class="bi bi-cash-coin me-1"></i>Crear pago</a>
                        <a href="{{ route('admin_fit.users.index') }}" class="btn btn-sm btn-secondary">
                        <i class="bi bi-chevron-left"></i>
                        Volver</a>
                    </div>
                </div>
                <div class="card-body bg-white">
                    @if(session('success'))
                        <div class="alert alert-success">{{ session('success') }}</div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger mb-3">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif
                        <h6 class="mb-3">Datos del Usuario</h6>
                        <div class="row g-3">
                            <div class="col-md-12">
                                <label class="form-label">Rol</label>
                                <select name="role_name" id="role_name" class="form-select @error('role_name') is-invalid @enderror" required>
                                    <option value="">Seleccionar</option>
                                    @foreach($roles as $role)
                                        <option value="{{ $role->name }}" {{ old('role_name', $currentRole) === $role->name ? 'selected' : '' }}>
                                            {{ $role->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('role_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Nombre</label>
                                <input type="text" name="name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name', $user->name) }}" required>
                                @error('name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control @error('email') is-invalid @enderror" value="{{ old('email', $user->email) }}" required>
                                @error('email')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>


                            <div class="col-md-6">
                                <label class="form-label">Nueva Contraseña</label>
                                <input type="password" name="password" class="form-control @error('password') is-invalid @enderror" placeholder="Opcional">
                                @error('password')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Confirmar Contraseña</label>
                                <input type="password" name="password_confirmation" class="form-control @error('password') is-invalid @enderror" placeholder="Opcional">
                            </div>

                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input @error('is_active') is-invalid @enderror" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', $user->is_active) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="is_active">Usuario activo</label>
                                    @error('is_active')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                        </div>

                        <hr class="my-4">

                        <h6 class="mb-3">Datos de Persona</h6>
                        <p class="text-muted small mb-3">
                            @if($user->people_id)
                                Este usuario ya tiene relación con Persona. Actualiza los campos según sea necesario.
                            @else
                                Este usuario aún no tiene relación con Persona. Completa los campos para crearla.
                            @endif
                        </p>

                        <div class="row g-3">

                            <div class="col-md-6">
                                <label class="form-label">Apellidos</label>
                                <input type="text" name="people[last_name]" class="form-control @error('people.last_name') is-invalid @enderror" value="{{ old('people.last_name', optional($user->people)->last_name) }}">
                                @error('people.last_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Fecha de Nacimiento</label>
                                <input type="date" name="people[birth_date]" class="form-control @error('people.birth_date') is-invalid @enderror" value="{{ old('people.birth_date', optional($user->people)->birth_date) }}">
                                @error('people.birth_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Género</label>
                                <select name="people[gender]" class="form-select @error('people.gender') is-invalid @enderror">
                                    <option value="">Seleccionar</option>
                                    <option value="male" {{ old('people.gender', optional($user->people)->gender) === 'male' ? 'selected' : '' }}>Masculino</option>
                                    <option value="female" {{ old('people.gender', optional($user->people)->gender) === 'female' ? 'selected' : '' }}>Femenino</option>
                                    <option value="other" {{ old('people.gender', optional($user->people)->gender) === 'other' ? 'selected' : '' }}>Otro</option>
                                </select>
                                @error('people.gender')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-4">
                                <label class="form-label">Teléfono</label>
                                <input type="text" name="people[phone]" class="form-control @error('people.phone') is-invalid @enderror" value="{{ old('people.phone', optional($user->people)->phone) }}">
                                @error('people.phone')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>


                            <div class="col-md-12">
                                <label class="form-label">Dirección</label>
                                <input type="text" name="people[address]" class="form-control @error('people.address') is-invalid @enderror" value="{{ old('people.address', optional($user->people)->address) }}">
                                @error('people.address')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Tipo de Documento</label>
                                <select name="people[document_type]" class="form-select @error('people.document_type') is-invalid @enderror">
                                    <option value="">Seleccionar</option>
                                    <option value="cedula" {{ old('people.document_type', optional($user->people)->document_type) === 'cedula' ? 'selected' : '' }}>Cédula</option>
                                    <option value="rif" {{ old('people.document_type', optional($user->people)->document_type) === 'rif' ? 'selected' : '' }}>RIF</option>
                                </select>
                                @error('people.document_type')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Número de Documento</label>
                                <input type="text" name="people[document_number]" class="form-control @error('people.document_number') is-invalid @enderror" value="{{ old('people.document_number', optional($user->people)->document_number) }}">
                                @error('people.document_number')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                        </div>

                        <hr class="my-4">

                        <h6 class="mb-3">Membresía</h6>
                        @php
                            $consumedMembershipDays = $user->daysOfMembership();
                            $totalMembershipDays = $user->totalDaysOfMembership();
                            $membershipProgressPercent = $totalMembershipDays > 0
                                ? min(100, round(($consumedMembershipDays / $totalMembershipDays) * 100, 2))
                                : 0;
                            $indicatorDots = max(0, $totalMembershipDays);
                            $filledDots = min($consumedMembershipDays, $indicatorDots);
                        @endphp

                        <div class="card border-0 shadow-sm mb-3 bg-light">
                            <div class="card-body py-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="fw-semibold">Consumo de membresía</div>
                                    <div class="small text-muted">{{ $consumedMembershipDays }} / {{ $totalMembershipDays }} días ({{ $membershipProgressPercent }}%)</div>
                                </div>
                                @if ($indicatorDots > 0)
                                    <div class="d-flex align-items-center gap-1 mt-2 flex-wrap" aria-label="Indicador de días consumidos">
                                        @for ($dot = 1; $dot <= $indicatorDots; $dot++)
                                            <span
                                                class="rounded-circle {{ $dot <= $filledDots ? 'bg-dark' : 'bg-white border' }}"
                                                style="width: 10px; height: 10px; display: inline-block;"
                                            ></span>
                                        @endfor
                                    </div>
                                @else
                                    <div class="small text-muted mt-2">Sin días de membresía para mostrar.</div>
                                @endif
                            </div>
                        </div>
                        <p class="text-muted small mb-3">Puede asignar una membresía al usuario. Si no selecciona ninguna, el usuario no tendrá membresía activa.</p>
                        <div class="col-12">
                            <div class="form-check">
                                <input
                                    class="form-check-input @error('is_couple') is-invalid @enderror"
                                    type="checkbox"
                                    name="is_couple"
                                    id="is_couple"
                                    value="1"
                                    {{ old('is_couple', !empty($user->couple_id)) ? 'checked' : '' }}
                                >
                                <label class="form-check-label" for="is_couple">Viene en pareja</label>
                                @error('is_couple')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>

                        @if (empty($user->couple_id) && !empty($coupledByUser))
                            <div class="col-12">
                                <div class="alert alert-info py-2 mb-0">
                                    Este Viene en <strong>pareja</strong> {{ trim($coupledByUser->name . ' ' . ($coupledByUser->people->last_name ?? '')) }}.
                                </div>
                            </div>
                        @endif

                        <div class="col-md-12 {{ old('is_couple', !empty($user->couple_id)) ? '' : 'd-none' }}" id="coupleSelectWrapper">
                            <label class="form-label">Usuario pareja</label>
                            <select name="couple_id" id="couple_id" class="form-select @error('couple_id') is-invalid @enderror">
                                <option value="">Seleccionar usuario</option>
                                @foreach($coupleCandidates as $candidate)
                                    <option value="{{ $candidate->id }}" {{ (string) old('couple_id', $currentCoupleId) === (string) $candidate->id ? 'selected' : '' }}>
                                        {{ trim($candidate->name . ' ' . ($candidate->people->last_name ?? '')) }} - {{ $candidate->email }}
                                    </option>
                                @endforeach
                            </select>
                            @error('couple_id')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="row mb-3 {{ old('role_name', $currentRole) === 'Cliente' && old('is_couple', !empty($user->couple_id)) && old('couple_id', $currentCoupleId) ? 'd-none' : '' }}" id="membershipSection">
                            <div class="col-md-6">
                                <label class="form-label">Membresía</label>
                                <select name="membership_id" id="membership_id" class="form-select">
                                    <option value="">Sin membresía</option>
                                    @foreach($memberships as $membership)
                                        <option value="{{ $membership->id }}" {{ (old('membership_id', optional($user->membership_users->first())->membership_id ?? '') == $membership->id) ? 'selected' : '' }}>
                                            {{ $membership->name }} - {{ $membership->price }}$ ({{ $membership->duration_days }} días)
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Plan de pago</label>
                                <select name="payment_plan_id" id="payment_plan_id" class="form-select @error('payment_plan_id') is-invalid @enderror">
                                    <option value="">Sin plan de pago</option>
                                    @foreach($paymentPlans as $paymentPlan)
                                        <option value="{{ $paymentPlan->id }}" {{ (old('payment_plan_id', optional($user->membership_users->first())->payment_plan_id ?? '') == $paymentPlan->id) ? 'selected' : '' }}>
                                            {{ $paymentPlan->plan_name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('payment_plan_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Fecha de inicio de membresía</label>
                                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ old('start_date', optional($user->membership_users->first())->getStart_date() ?? '') }}">
                            </div>
                        </div>
                        <hr class="my-4">

                        <div id="entryTimeSection" class="{{ old('role_name', $currentRole) === 'Cliente' && old('is_couple', !empty($user->couple_id)) && old('couple_id', $currentCoupleId) ? 'd-none' : '' }}">
                        <h6 class="mb-3">Horario de Entrada/Salida</h6>
                        <p class="text-muted small mb-3">Puede asignar un horario de entrada y salida al usuario. Si no selecciona ninguno, el usuario no tendrá horario activo.</p>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Horario de Entrada</label>
                                <select name="entry_time_id" id="entry_time_id" class="form-select">
                                    <option value="">Sin horario</option>
                                    @foreach($entryTimes as $entryTime)
                                        <option value="{{ $entryTime->id }}" {{ (old('entry_time_id', optional($user->entry_time_users->first())->entry_time_id ?? '') == $entryTime->id) ? 'selected' : '' }}>
                                            {{ $entryTime->entry_time }} - {{ $entryTime->exit_time }} ({{ $entryTime->period }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="submit" class="btn btn-success">Guardar</button>
                        </div>
                    
                </div>
            </div>
        </div>
        <div class="col-md-4">
                <div class="card mb-3 shadow-sm">
                    <div class="card-header bg-info text-white">Imagen</div>
                    <div class="card-body small">
                        <div class="row mb-4 align-items-center">
                            <div class="col-md-12 text-center">
                                <img id="user-image-preview" src="{{ !empty(optional($user->people)->url_face) ? route('admin_fit.users.image', ['filename' => optional($user->people)->url_face]) : asset('images/no-user-imagen.jpg') }}" alt="Imagen de usuario" class="img-thumbnail mb-2" style="width: 180px; height: 180px; object-fit: contain; object-position: center; background-color: #f8f9fa;">
                            </div>
                            <div class="col-md-12 text-center">
                                <label class="form-label w-100">Subir imagen</label>
                                <input type="file" name="user_image" class="form-control @error('user_image') is-invalid @enderror" accept="image/*" onchange="
                                    const [file] = this.files;
                                    if (file) {
                                        document.getElementById('user-image-preview').src = URL.createObjectURL(file);
                                    }
                                ">
                                @error('user_image')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
            <div class="card mb-3 shadow-sm">
                <div class="card-header bg-info text-white">Asistencia</div>
                <div class="card-body small">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Total</span>
                        <span class="badge bg-dark">{{ (int) ($assistanceSummary['total'] ?? 0) }}</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Semana actual</span>
                        <span class="badge bg-primary">{{ (int) ($assistanceSummary['week'] ?? 0) }}</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">Mes en curso</span>
                        <span class="badge bg-success">{{ (int) ($assistanceSummary['month'] ?? 0) }}</span>
                    </div>
                </div>
            </div>
            <div class="card mb-3 shadow-sm">
                <div class="card-header bg-info text-white">Ayuda por Campo</div>
                <div class="card-body small">
                    <p class="mb-2"><strong>Nombre:</strong> Nombre completo para identificar la cuenta.</p>
                    <p class="mb-2"><strong>Email:</strong> Debe ser único para iniciar sesión.</p>
                    <p class="mb-2"><strong>Rol:</strong> Al guardar, se actualiza el rol y hereda sus permisos.</p>
                    <p class="mb-2"><strong>Nueva Contraseña:</strong> Déjalo vacío para conservar la contraseña actual.</p>
                    <p class="mb-2"><strong>Usuario activo:</strong> Habilita o deshabilita el acceso.</p>
                    <p class="mb-2"><strong>Viene en pareja:</strong> Al seleccionarlo y elegir un usuario pareja, se heredan la membresía y el horario de entrada/salida de ese usuario.</p>
                    <hr>
                    <p class="mb-2"><strong>Nombres/Apellidos:</strong> Datos de identidad personal de la relación Persona.</p>
                    <p class="mb-2"><strong>Fecha de Nacimiento:</strong> Usa formato YYYY-MM-DD.</p>
                    <p class="mb-2"><strong>Género:</strong> Selecciona Masculino, Femenino u Otro.</p>
                    <p class="mb-2"><strong>Teléfono:</strong> Número de contacto de la persona.</p>
                    <p class="mb-2"><strong>Dirección:</strong> Dirección principal de la persona.</p>
                    <p class="mb-2"><strong>Tipo/Número de Documento:</strong> Datos de identificación.</p>
                    <hr>
                    <p class="mb-2"><strong>Membresía:</strong> Selecciona una membresía para asociar al usuario. Si no seleccionas ninguna, el usuario no tendrá membresía activa.</p>
                    <p class="mb-2"><strong>Nota de pareja:</strong> Si marcas la opción de pareja y eliges un usuario, esta sección no aplica porque la membresía y el horario se heredan automáticamente.</p>
                    <p class="mb-2"><strong>Fecha de inicio de membresía:</strong> Puedes definir desde cuándo estará activa la membresía asignada.</p>
                    <hr>
                    <p class="mb-2"><strong>Horario de Entrada/Salida:</strong> Puedes asignar un horario de entrada y salida al usuario. Si no seleccionas ninguno, el usuario no tendrá horario activo.</p>
                </div>
            </div>
        </div>
    </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const isCoupleCheckbox = document.getElementById('is_couple');
    const coupleSelectWrapper = document.getElementById('coupleSelectWrapper');
    const coupleSelect = document.getElementById('couple_id');
    const roleSelect = document.getElementById('role_name');
    const membershipSection = document.getElementById('membershipSection');
    const entryTimeSection = document.getElementById('entryTimeSection');
    const membershipSelect = document.getElementById('membership_id');
    const paymentPlanSelect = document.getElementById('payment_plan_id');
    const startDateInput = document.getElementById('start_date');
    const entryTimeSelect = document.getElementById('entry_time_id');

    if (!isCoupleCheckbox || !coupleSelectWrapper || !coupleSelect) {
        return;
    }

    function syncCoupleVisibility() {
        const checked = isCoupleCheckbox.checked;
        coupleSelectWrapper.classList.toggle('d-none', !checked);
        coupleSelect.required = checked;

        if (!checked) {
            coupleSelect.value = '';
        }

        const hasCoupleSelected = checked && coupleSelect.value !== '';
        const isClienteRole = roleSelect && roleSelect.value === 'Cliente';
        const showMembershipAndEntry = isClienteRole && !hasCoupleSelected;

        if (membershipSection) {
            membershipSection.classList.toggle('d-none', !showMembershipAndEntry);
        }

        if (entryTimeSection) {
            entryTimeSection.classList.toggle('d-none', !showMembershipAndEntry);
        }

        if (membershipSelect) {
            membershipSelect.disabled = !showMembershipAndEntry;
        }

        if (paymentPlanSelect) {
            paymentPlanSelect.disabled = !showMembershipAndEntry;
        }

        if (startDateInput) {
            startDateInput.disabled = !showMembershipAndEntry;
        }

        if (entryTimeSelect) {
            entryTimeSelect.disabled = !showMembershipAndEntry;
        }
    }

    isCoupleCheckbox.addEventListener('change', syncCoupleVisibility);
    coupleSelect.addEventListener('change', syncCoupleVisibility);
    if (roleSelect) {
        roleSelect.addEventListener('change', syncCoupleVisibility);
    }
    syncCoupleVisibility();
});
</script>

<div class="modal fade" id="userSalesModal" tabindex="-1" aria-labelledby="userSalesModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userSalesModalLabel">Ultimas 30 ventas del usuario</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-end mb-3">
                    <div class="px-3 py-2 border rounded bg-light text-end shadow-sm">
                        <div class="small text-muted">Total deuda (filtro actual)</div>
                        <div id="user-sales-debt-total" class="fs-5 fw-bold text-primary">0.00</div>
                        <div class="small text-muted mt-1">Total Ref (filtro actual)</div>
                        <div id="user-sales-aux-debt-total" class="fs-5 fw-bold text-success">0.00</div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table id="userSalesTable" class="table table-sm table-striped align-middle mb-0 w-100">
                        <thead>
                            <tr>
                                <th>Venta</th>
                                <th>Fecha</th>
                                <th class="text-end">Total Venta</th>
                                <th class="text-end">Deuda Venta</th>
                                <th>Tipo</th>
                                <th>Descripcion</th>
                                <th class="text-end">Cantidad</th>
                                <th class="text-end">Precio Unitario</th>
                                <th class="text-end">Subtotal</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection