@extends('layouts.ownerLayout')

@section('title', 'Clientes')

@section('vendor-style')
@vite([
  'resources/assets/vendor/fonts/flag-icons.scss',
  'resources/assets/vendor/libs/datatables-bs5/datatables.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-responsive-bs5/responsive.bootstrap5.scss',
  'resources/assets/vendor/libs/datatables-buttons-bs5/buttons.bootstrap5.scss',
  'resources/assets/vendor/libs/@form-validation/form-validation.scss',
  'resources/assets/vendor/libs/select2/select2.scss',
  'resources/assets/vendor/libs/notyf/notyf.scss',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.scss'
])
@endsection

@section('vendor-script')
@vite([
  'resources/assets/vendor/libs/moment/moment.js',
  'resources/assets/vendor/libs/datatables-bs5/datatables-bootstrap5.js',
  'resources/assets/vendor/libs/select2/select2.js',
  'resources/assets/vendor/libs/@form-validation/popular.js',
  'resources/assets/vendor/libs/@form-validation/bootstrap5.js',
  'resources/assets/vendor/libs/@form-validation/auto-focus.js',
  'resources/assets/vendor/libs/cleave-zen/cleave-zen.js',
  'resources/assets/vendor/libs/notyf/notyf.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.js'
])
@endsection

@section('page-script')
@vite('resources/assets/js/owner-clients.js')
<script>
  window.__ownerClientsData = {
    openAddModal: @json($errors->any()),
    canManage: @json($canManageClients),
    toast: {
      success: @json(session('status')),
      errors: @json($errors->all())
    }
  };
</script>
@endsection

@section('content')
@if (!$canManageClients)
  <div class="alert alert-warning mb-6">
    Tu usuario no tiene organización asignada. Solicita al administrador asociarte a una organización para gestionar clientes.
  </div>
@endif

<div class="row g-6 mb-6">
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Total clientes</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['total']) }}</h4>
            </div>
            <small class="mb-0">Registrados</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-primary"><i class="icon-base ti tabler-users icon-26px"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Activos</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['active']) }}</h4>
            </div>
            <small class="mb-0">Con contacto habilitado</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-success"><i class="icon-base ti tabler-user-check icon-26px"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Con correo</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['with_email']) }}</h4>
            </div>
            <small class="mb-0">Para seguimiento</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-info"><i class="icon-base ti tabler-mail icon-26px"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-xl-3">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-start justify-content-between">
          <div class="content-left">
            <span class="text-heading">Países</span>
            <div class="d-flex align-items-center my-1">
              <h4 class="mb-0 me-2">{{ number_format($stats['countries']) }}</h4>
            </div>
            <small class="mb-0">Cobertura actual</small>
          </div>
          <div class="avatar">
            <span class="avatar-initial rounded bg-label-warning"><i class="icon-base ti tabler-world icon-26px"></i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-datatable table-responsive">
    <table class="datatables-customers table border-top">
      <thead>
        <tr>
          <th>Cliente</th>
          <th>Grupo</th>
          <th>País</th>
          <th>Servicios</th>
          <th class="text-nowrap">Total cobrado</th>
          <th>Estado</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach($customers as $customer)
          @php
            $orderData = $orderStats->get($customer->id);
            $ordersCount = (int) data_get($orderData, 'orders_count', 0);
            $totalSpent = (float) data_get($orderData, 'total_spent', 0);
          @endphp
          <tr>
            <td>
              <div class="d-flex flex-column">
                <span class="fw-medium text-heading">{{ $customer->name }}</span>
                <small>{{ $customer->email ?: ($customer->formatted_mobile ?: 'Sin contacto') }}</small>
                @if($customer->mobile)
                  <span class="d-none">{{ $customer->mobile }} {{ preg_replace('/\D+/', '', $customer->mobile) }}</span>
                @endif
              </div>
            </td>
            <td>{{ $customer->mariachiGroup?->name ?: 'Sin grupo' }}</td>
            <td>{{ $customer->country ?: 'Colombia' }}</td>
            <td>{{ $ordersCount }}</td>
            <td>${{ number_format($totalSpent, 0, ',', '.') }}</td>
            <td>
              <span class="badge {{ $customer->is_active ? 'bg-label-success' : 'bg-label-secondary' }}">
                {{ $customer->is_active ? 'Activo' : 'Inactivo' }}
              </span>
            </td>
            <td>
              <div class="d-flex align-items-center">
                <a
                  href="{{ route('owner.clients.show', $customer) }}"
                  class="btn btn-text-secondary rounded-pill waves-effect btn-icon"
                  title="Ver detalle">
                  <i class="icon-base ti tabler-eye icon-22px"></i>
                </a>
                @if($customer->is_active)
                  <form id="deactivate-customer-form-{{ $customer->id }}" action="{{ route('owner.clients.deactivate', $customer) }}" method="POST">
                    @csrf
                    @method('PATCH')
                    <button
                      type="button"
                      class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-deactivate-customer"
                      data-form-id="deactivate-customer-form-{{ $customer->id }}"
                      data-name="{{ $customer->name }}"
                      title="Desactivar">
                      <i class="icon-base ti tabler-user-x icon-22px"></i>
                    </button>
                  </form>
                @endif
              </div>
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>

  <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEcommerceCustomerAdd" aria-labelledby="offcanvasEcommerceCustomerAddLabel">
    <div class="offcanvas-header">
      <h5 id="offcanvasEcommerceCustomerAddLabel" class="offcanvas-title">Agregar cliente</h5>
      <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body border-top mx-0 flex-grow-0">
      <form class="ecommerce-customer-add pt-0" id="eCommerceCustomerAddForm" method="POST" action="{{ route('owner.clients.store') }}">
        @csrf
        <div class="ecommerce-customer-add-basic mb-4">
          <h6 class="mb-6">Información básica</h6>
          <div class="mb-6 form-control-validation">
            <label class="form-label" for="ecommerce-customer-add-group">Grupo musical*</label>
            @php
              $defaultGroupId = $selectedWorkspaceGroupId
                ?? data_get($mariachiGroupOptions->firstWhere('is_default', true), 'id')
                ?? data_get($mariachiGroupOptions->first(), 'id');
            @endphp
            <select class="form-select" id="ecommerce-customer-add-group" name="mariachi_group_id" required>
              @foreach($mariachiGroupOptions as $group)
                <option value="{{ $group->id }}" @selected((string) old('mariachi_group_id', $defaultGroupId) === (string) $group->id)>
                  {{ $group->name }}
                </option>
              @endforeach
            </select>
          </div>
          <div class="mb-6 form-control-validation">
            <label class="form-label" for="ecommerce-customer-add-name">Nombre*</label>
            <input type="text" class="form-control" id="ecommerce-customer-add-name" placeholder="John Doe" name="name" value="{{ old('name') }}" required />
          </div>
          <div class="mb-6 form-control-validation">
            <label class="form-label" for="ecommerce-customer-add-email">Email</label>
            <input type="email" id="ecommerce-customer-add-email" class="form-control" placeholder="john.doe@example.com" name="email" value="{{ old('email') }}" />
          </div>
          <div>
            <label class="form-label" for="ecommerce-customer-add-contact">Móvil</label>
            <input type="text" id="ecommerce-customer-add-contact" class="form-control" placeholder="+57 300 000 0000" name="mobile" value="{{ old('mobile') }}" />
          </div>
        </div>

        <div class="ecommerce-customer-add-shiping mb-6 pt-4">
          <h6 class="mb-6">Información de dirección</h6>
          <div class="mb-6">
            <label class="form-label" for="ecommerce-customer-add-address">Dirección línea 1</label>
            <input type="text" id="ecommerce-customer-add-address" class="form-control" placeholder="Calle 45 # 10-20" name="address_line_1" value="{{ old('address_line_1') }}" />
          </div>
          <div class="mb-6">
            <label class="form-label" for="ecommerce-customer-add-address-2">Dirección línea 2</label>
            <input type="text" id="ecommerce-customer-add-address-2" class="form-control" name="address_line_2" value="{{ old('address_line_2') }}" />
          </div>
          <div class="mb-6">
            <label class="form-label" for="ecommerce-customer-add-town">Ciudad / Municipio</label>
            <input type="text" id="ecommerce-customer-add-town" class="form-control" placeholder="Bogotá" name="town" value="{{ old('town') }}" />
          </div>
          <div class="col-12 mb-6">
            <label class="form-label" for="ecommerce-customer-add-state">Departamento / Estado</label>
            <input type="text" id="ecommerce-customer-add-state" class="form-control" placeholder="Cundinamarca" name="state_province" value="{{ old('state_province') }}" />
          </div>
          <div class="col-12 mb-6">
            <label class="form-label" for="ecommerce-customer-add-post-code">Código postal</label>
            <input type="text" id="ecommerce-customer-add-post-code" class="form-control" placeholder="110111" name="post_code" value="{{ old('post_code') }}" maxlength="20" />
          </div>
          <div>
            <label class="form-label" for="ecommerce-customer-add-country">País</label>
            <select id="ecommerce-customer-add-country" class="select2 form-select" name="country">
              <option value="">Selecciona</option>
              <option value="Colombia" @selected(old('country', 'Colombia') === 'Colombia')>Colombia</option>
              <option value="México" @selected(old('country') === 'México')>México</option>
              <option value="Estados Unidos" @selected(old('country') === 'Estados Unidos')>Estados Unidos</option>
              <option value="Perú" @selected(old('country') === 'Perú')>Perú</option>
              <option value="Chile" @selected(old('country') === 'Chile')>Chile</option>
            </select>
          </div>
        </div>

        <div class="d-sm-flex mb-6">
          <div class="me-auto mb-2 mb-md-0">
            <h6 class="mb-1">¿Usar como dirección de cobro?</h6>
            <small class="text-body-secondary">Podrás editarlo más adelante.</small>
          </div>
          <div class="form-check form-switch my-auto me-n2">
            <input type="hidden" name="is_billing_same" value="0">
            <input type="checkbox" class="form-check-input" name="is_billing_same" value="1" @checked((string) old('is_billing_same', '1') === '1') />
          </div>
        </div>

        <div class="mb-6 form-control-validation">
          <label class="form-label" for="customer_is_active">Estado</label>
          <select id="customer_is_active" class="form-select" name="is_active" required>
            <option value="1" @selected((string) old('is_active', '1') === '1')>Activo</option>
            <option value="0" @selected((string) old('is_active') === '0')>Inactivo</option>
          </select>
        </div>

        <div>
          <button type="submit" class="btn btn-primary me-sm-4 data-submit" @disabled(!$canManageClients)>Agregar</button>
          <button type="reset" class="btn btn-label-danger" data-bs-dismiss="offcanvas">Cancelar</button>
        </div>
      </form>
    </div>
  </div>
</div>
@endsection
