@extends('layouts.admin')
@section('title', isset($user) ? 'Edit User' : 'Tambah User')
@section('content')
<div class="row justify-content-center"><div class="col-lg-7">
<div class="card">
  <div class="card-header">{{ isset($user) ? 'Edit: '.$user->name : 'Tambah User Baru' }}</div>
  <div class="card-body">
    <form action="{{ isset($user) ? route('admin.users.update',$user) : route('admin.users.store') }}" method="POST">
    @csrf @if(isset($user)) @method('PUT') @endif
    <div class="row g-3">
      <div class="col-md-6"><label class="form-label fw-semibold">Nama *</label><input type="text" name="name" class="form-control" value="{{ old('name',$user->name??'') }}" required></div>
      <div class="col-md-6"><label class="form-label fw-semibold">Email *</label><input type="email" name="email" class="form-control" value="{{ old('email',$user->email??'') }}" required></div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">Role *</label>
        <select name="role" class="form-select" required>
          @foreach(['admin'=>'Admin','cs'=>'CS','technician'=>'Teknisi'] as $v=>$l)<option value="{{ $v }}" {{ old('role',$user->role??'')===$v?'selected':'' }}>{{ $l }}</option>@endforeach
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">Divisi *</label>
        <select name="division" class="form-select" required>
          @foreach(['JPN','FixLab','Havva'] as $d)<option value="{{ $d }}" {{ old('division',$user->division??'JPN')===$d?'selected':'' }}>{{ $d }}</option>@endforeach
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label fw-semibold">Status</label>
        <select name="is_active" class="form-select">
          <option value="1" {{ old('is_active',$user->is_active??1)?'selected':'' }}>Aktif</option>
          <option value="0" {{ !old('is_active',$user->is_active??1)?'selected':'' }}>Nonaktif</option>
        </select>
      </div>
      <div class="col-md-6">
        <label class="form-label fw-semibold">No. WhatsApp</label>
        <div class="input-group">
          <input id="whatsapp_number" type="text" name="whatsapp_number" class="form-control" value="{{ old('whatsapp_number',$user->whatsapp_number??'') }}" placeholder="628xxx">
          <button type="button" id="whatsapp-test-button" class="btn btn-outline-secondary">Uji</button>
        </div>
        <div id="whatsapp-test-result" class="form-text text-muted">Gunakan nomor WA dengan kode negara, mis. 628xxx.</div>
      </div>
      <div class="col-md-6">
        <label class="form-label fw-semibold">Nomor Telegram <span class="text-muted small">(ID atau @username)</span></label>
        <div class="input-group">
          <input id="telegram_chat_id" type="text" name="telegram_chat_id" class="form-control" value="{{ old('telegram_chat_id',$user->telegram_chat_id??'') }}" placeholder="123456789 atau @username">
          <button type="button" id="telegram-test-button" class="btn btn-outline-secondary">Uji</button>
        </div>
        <div id="telegram-test-result" class="form-text text-muted">Gunakan ID Telegram numerik atau username @. Pastikan bot Telegram sudah dibuka oleh penerima.</div>
      </div>
      <div class="col-12">
        <label class="form-label fw-semibold">Akses Modul</label>
        <div class="row gy-2">
          @foreach(\App\Models\User::permissionMap() as $perm => $label)
          <div class="col-md-4">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="permissions[]" value="{{ $perm }}" id="perm-{{ str_replace(['.','*'], ['-','wild'], $perm) }}" {{ in_array($perm, old('permissions', $user->permissions ?? [])) ? 'checked' : '' }}>
              <label class="form-check-label" for="perm-{{ str_replace(['.','*'], ['-','wild'], $perm) }}">{{ $label }}</label>
            </div>
          </div>
          @endforeach
        </div>
        <div class="form-text">Kosongkan jika ingin gunakan default role.</div>
      </div>
      <div class="col-md-6"><label class="form-label fw-semibold">Password {{ isset($user)?'(kosongkan jika tidak diubah)':'' }} *</label><input type="password" name="password" class="form-control" {{ isset($user)?'':'required' }}></div>
      <div class="col-md-6"><label class="form-label fw-semibold">Konfirmasi Password</label><input type="password" name="password_confirmation" class="form-control"></div>
      @if(isset($user) && $user->two_factor_enabled)
      <div class="col-12"><div class="alert alert-info d-flex justify-content-between align-items-center small"><span><i class="fas fa-shield-halved me-2"></i>2FA aktif untuk user ini</span><form action="{{ route('admin.users.2fa.reset',$user) }}" method="POST">@csrf<button class="btn btn-sm btn-warning">Reset 2FA</button></form></div></div>
      @endif
      <div class="col-12 d-flex gap-2 justify-content-end"><a href="{{ route('admin.users.index') }}" class="btn btn-secondary">Batal</a><button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Simpan</button></div>
    </div>
    </form>
  </div>
</div>
</div></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
  const token = document.querySelector('input[name="_token"]').value;

  const tests = [
    {
      buttonId: 'telegram-test-button',
      inputId: 'telegram_chat_id',
      resultId: 'telegram-test-result',
      url: '{{ route('admin.users.testTelegram') }}',
      payload: (value) => ({ telegram_chat_id: value }),
      emptyMessage: 'Masukkan ID atau @username Telegram terlebih dahulu.',
    },
    {
      buttonId: 'whatsapp-test-button',
      inputId: 'whatsapp_number',
      resultId: 'whatsapp-test-result',
      url: '{{ route('admin.users.testWhatsapp') }}',
      payload: (value) => ({ whatsapp_number: value }),
      emptyMessage: 'Masukkan nomor WhatsApp terlebih dahulu.',
    },
  ];

  tests.forEach(({ buttonId, inputId, resultId, url, payload, emptyMessage }) => {
    const button = document.getElementById(buttonId);
    const input = document.getElementById(inputId);
    const result = document.getElementById(resultId);
    if (!button || !input || !result) return;

    button.addEventListener('click', async function () {
      const value = input.value.trim();
      if (!value) {
        result.textContent = emptyMessage;
        result.className = 'form-text text-danger';
        return;
      }

      button.disabled = true;
      button.textContent = 'Menguji...';

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': token,
            'Accept': 'application/json',
          },
          body: JSON.stringify(payload(value)),
        });
        const data = await response.json();
        result.textContent = data.message || (response.ok ? 'Pesan uji berhasil dikirim.' : 'Gagal mengirim pesan uji.');
        result.className = 'form-text ' + (response.ok ? 'text-success' : 'text-danger');
      } catch (error) {
        result.textContent = 'Terjadi kesalahan jaringan. Coba lagi.';
        result.className = 'form-text text-danger';
      } finally {
        button.disabled = false;
        button.textContent = 'Uji';
      }
    });
  });
});
</script>
@endsection
