@extends('layouts.ownerLayout')

@section('title', 'Otros Costos')

@section('vendor-style')
@vite([
  '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/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/datatables-bs5/datatables-bootstrap5.js',
  'resources/assets/vendor/libs/select2/select2.js',
  'resources/assets/vendor/libs/notyf/notyf.js',
  'resources/assets/vendor/libs/sweetalert2/sweetalert2.js'
])
@endsection

@section('page-script')
@vite('resources/assets/js/owner-other-costs.js')
@vite('resources/assets/js/owner-price-rules.js')
<script>
  window.__otherCostPageData = {
    canManage: @json($canManageOtherCosts),
    openCreateModal: @json(old('form_type') === 'create'),
    openEditModal: @json(old('form_type') === 'edit'),
    editItemId: @json(old('item_id')),
    toast: {
      success: @json(session('status')),
      errors: @json($errors->all())
    }
  };
</script>
@endsection

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

@if($currentGroup)
  <div class="card mb-6">
    <div class="card-body d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
      <div>
        <h5 class="mb-1">Otros costos de {{ $currentGroup->name }}</h5>
        <p class="mb-0 text-body-secondary">Este bloque ya quedó vinculado directamente al grupo mariachi.</p>
      </div>
      <div class="d-flex flex-column flex-sm-row gap-2">
        <form method="GET" action="{{ route('owner.settings.other-costs') }}">
          <select class="form-select" name="mariachi_group_id" onchange="this.form.submit()">
            @foreach($mariachiGroups as $group)
              <option value="{{ $group->id }}" @selected((int) $currentGroup->id === (int) $group->id)>{{ $group->name }}</option>
            @endforeach
          </select>
        </form>
        <a href="{{ route('owner.settings.mariachi-groups.show', $currentGroup) }}" class="btn btn-label-primary">Ver grupo</a>
      </div>
    </div>
  </div>
@endif

<div class="card mb-6">
  <div class="card-widget-separator-wrapper">
    <div class="card-body card-widget-separator">
      <div class="row gy-4 gy-sm-1">
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-1 border-end pb-4 pb-sm-0">
            <div>
              <p class="mb-1">Total costos</p>
              <h4 class="mb-1">{{ number_format($stats['total']) }}</h4>
              <p class="mb-0 text-body-secondary">Catálogo completo</p>
            </div>
            <span class="avatar me-sm-6">
              <span class="avatar-initial rounded bg-label-primary"><i class="icon-base ti tabler-currency-dollar icon-28px"></i></span>
            </span>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start card-widget-2 border-end pb-4 pb-sm-0">
            <div>
              <p class="mb-1">Activos</p>
              <h4 class="mb-1">{{ number_format($stats['active']) }}</h4>
              <p class="mb-0 text-body-secondary">Aplicables</p>
            </div>
            <span class="avatar p-2 me-lg-6">
              <span class="avatar-initial rounded bg-label-success"><i class="icon-base ti tabler-checks icon-28px"></i></span>
            </span>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start border-end pb-4 pb-sm-0 card-widget-3">
            <div>
              <p class="mb-1">Inactivos</p>
              <h4 class="mb-1">{{ number_format($stats['inactive']) }}</h4>
              <p class="mb-0 text-body-secondary">No aplicables</p>
            </div>
            <span class="avatar p-2 me-sm-6">
              <span class="avatar-initial rounded bg-label-warning"><i class="icon-base ti tabler-ban icon-28px"></i></span>
            </span>
          </div>
        </div>
        <div class="col-sm-6 col-lg-3">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <p class="mb-1">Precio promedio</p>
              <h4 class="mb-1">${{ number_format($stats['avg_price'], 0, ',', '.') }}</h4>
              <p class="mb-0 text-body-secondary">Referencia</p>
            </div>
            <span class="avatar p-2">
              <span class="avatar-initial rounded bg-label-info"><i class="icon-base ti tabler-chart-histogram icon-28px"></i></span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header border-bottom">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-4">
      <h5 class="card-title mb-0">Filtros</h5>
      <button type="button" class="btn btn-primary" id="btnOpenCreateOtherCost" @disabled(!$canManageOtherCosts)>
        <i class="icon-base ti tabler-plus icon-xs me-1"></i>
        Agregar ítem
      </button>
    </div>
    <div class="d-flex justify-content-between align-items-center row pt-4 gap-6 gap-md-0 g-md-6">
      <div class="col-md-6 other_cost_status_filter"></div>
      <div class="col-md-6 other_cost_order_filter"></div>
    </div>
  </div>
  <div class="card-datatable">
    <table class="datatables-owner-other-costs table border-top">
      <thead>
        <tr>
          <th>ID</th>
          <th>Nombre</th>
          <th>Costo interno</th>
          <th>Precio cliente</th>
          <th>Estado</th>
          <th>Orden</th>
          <th>Acciones</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($items as $item)
          <tr>
            <td>{{ $item->id }}</td>
            <td class="fw-medium text-heading">{{ $item->name }}</td>
            <td>${{ number_format((float) $item->internal_cost, 0, ',', '.') }}</td>
            <td>${{ number_format((float) $item->base_price, 0, ',', '.') }}</td>
            <td>
              <span class="badge {{ $item->is_active ? 'bg-label-info' : 'bg-label-secondary' }}">
                {{ $item->is_active ? 'Activo' : 'Inactivo' }}
              </span>
            </td>
            <td>{{ $item->sort_order }}</td>
            <td>
              <div class="d-flex align-items-center">
                <button
                  type="button"
                  class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-edit-other-cost"
                  title="Editar"
                  data-id="{{ $item->id }}"
                  data-name="{{ $item->name }}"
                  data-internal-cost="{{ number_format((float) $item->internal_cost, 2, '.', '') }}"
                  data-base-price="{{ number_format((float) $item->base_price, 2, '.', '') }}"
                  data-is-active="{{ $item->is_active ? 1 : 0 }}"
                  data-sort-order="{{ $item->sort_order }}"
                  data-update-url="{{ route('owner.settings.other-costs.update', $item) }}"
                >
                  <i class="icon-base ti tabler-edit icon-22px"></i>
                </button>
                <button
                  type="button"
                  class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-manage-price-rules"
                  title="Reglas de precio"
                  data-target-type="other_cost"
                  data-target-id="{{ $item->id }}"
                  data-target-name="{{ $item->name }}"
                >
                  <i class="icon-base ti tabler-calendar-dollar icon-22px"></i>
                </button>

                <form id="delete-other-cost-form-{{ $item->id }}" action="{{ route('owner.settings.other-costs.destroy', $item) }}" method="POST">
                  @csrf
                  @method('DELETE')
                  <button
                    type="button"
                    class="btn btn-text-secondary rounded-pill waves-effect btn-icon btn-delete-other-cost"
                    data-form-id="delete-other-cost-form-{{ $item->id }}"
                    data-name="{{ $item->name }}"
                    title="Eliminar"
                  >
                    <i class="icon-base ti tabler-trash icon-22px"></i>
                  </button>
                </form>
              </div>
            </td>
          </tr>
        @endforeach
      </tbody>
    </table>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasCreateOtherCost" aria-labelledby="offcanvasCreateOtherCostLabel">
  <div class="offcanvas-header border-bottom">
    <h5 id="offcanvasCreateOtherCostLabel" class="offcanvas-title">Nuevo costo</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body mx-0 flex-grow-0 p-6 h-100">
    <form id="createOtherCostForm" method="POST" action="{{ route('owner.settings.other-costs.store') }}" class="h-100 d-flex flex-column">
      @csrf
      <input type="hidden" name="form_type" value="create">
      <input type="hidden" name="mariachi_group_id" value="{{ $currentGroup?->id }}">
      <div class="mb-4">
        <label class="form-label" for="create_name">Nombre</label>
        <input type="text" class="form-control" id="create_name" name="name" value="{{ old('form_type') === 'create' ? old('name') : '' }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="create_internal_cost">Costo interno (COP)</label>
        <input type="number" min="0" step="1000" class="form-control" id="create_internal_cost" name="internal_cost" value="{{ old('form_type') === 'create' ? old('internal_cost', 0) : 0 }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="create_base_price">Precio cliente (COP)</label>
        <input type="number" min="0" step="1000" class="form-control" id="create_base_price" name="base_price" value="{{ old('form_type') === 'create' ? old('base_price', 0) : 0 }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="create_sort_order">Orden</label>
        <input type="number" min="0" class="form-control" id="create_sort_order" name="sort_order" value="{{ old('form_type') === 'create' ? old('sort_order', 100) : 100 }}">
      </div>
      <div class="mb-4">
        <label class="form-label" for="create_is_active">Estado</label>
        <select class="form-select" id="create_is_active" name="is_active">
          <option value="1" @selected(old('form_type') === 'create' ? old('is_active', '1') === '1' : true)>Activo</option>
          <option value="0" @selected(old('form_type') === 'create' && old('is_active') === '0')>Inactivo</option>
        </select>
      </div>
      <div class="mt-auto pt-4 d-flex gap-3">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="offcanvas">Cancelar</button>
        <button type="submit" class="btn btn-primary" @disabled(!$canManageOtherCosts)>Guardar</button>
      </div>
    </form>
  </div>
</div>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasEditOtherCost" aria-labelledby="offcanvasEditOtherCostLabel">
  <div class="offcanvas-header border-bottom">
    <h5 id="offcanvasEditOtherCostLabel" class="offcanvas-title">Editar costo</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body mx-0 flex-grow-0 p-6 h-100">
    <form id="editOtherCostForm" method="POST" action="#" class="h-100 d-flex flex-column">
      @csrf
      @method('PUT')
      <input type="hidden" name="form_type" value="edit">
      <input type="hidden" name="item_id" id="edit_item_id" value="{{ old('item_id') }}">
      <input type="hidden" name="mariachi_group_id" value="{{ $currentGroup?->id }}">
      <div class="mb-4">
        <label class="form-label" for="edit_name">Nombre</label>
        <input type="text" class="form-control" id="edit_name" name="name" value="{{ old('form_type') === 'edit' ? old('name') : '' }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="edit_internal_cost">Costo interno (COP)</label>
        <input type="number" min="0" step="1000" class="form-control" id="edit_internal_cost" name="internal_cost" value="{{ old('form_type') === 'edit' ? old('internal_cost', 0) : 0 }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="edit_base_price">Precio cliente (COP)</label>
        <input type="number" min="0" step="1000" class="form-control" id="edit_base_price" name="base_price" value="{{ old('form_type') === 'edit' ? old('base_price', 0) : 0 }}" required>
      </div>
      <div class="mb-4">
        <label class="form-label" for="edit_sort_order">Orden</label>
        <input type="number" min="0" class="form-control" id="edit_sort_order" name="sort_order" value="{{ old('form_type') === 'edit' ? old('sort_order', 100) : 100 }}">
      </div>
      <div class="mb-4">
        <label class="form-label" for="edit_is_active">Estado</label>
        <select class="form-select" id="edit_is_active" name="is_active">
          <option value="1" @selected(old('form_type') === 'edit' ? old('is_active', '1') === '1' : true)>Activo</option>
          <option value="0" @selected(old('form_type') === 'edit' && old('is_active') === '0')>Inactivo</option>
        </select>
      </div>
      <div class="mt-auto pt-4 d-flex gap-3">
        <button type="button" class="btn btn-label-secondary" data-bs-dismiss="offcanvas">Cancelar</button>
        <button type="submit" class="btn btn-primary" @disabled(!$canManageOtherCosts)>Actualizar</button>
      </div>
    </form>
  </div>
</div>
@include('content.owner.settings.partials.price-rules-modal')
@endsection
