@extends('layout.admin')

@section('content')
@php
  $normalizeText = static function (?string $value): string {
    $text = trim((string) $value);
    if ($text === '') {
      return '';
    }

    $hasMojibakeHints = str_contains($text, 'Ã')
      || str_contains($text, 'Â')
      || str_contains($text, 'à')
      || str_contains($text, 'â');

    if ($hasMojibakeHints && function_exists('mb_convert_encoding')) {
      $fixed = @mb_convert_encoding($text, 'UTF-8', 'Windows-1252');
      if (is_string($fixed) && trim($fixed) !== '') {
        $text = $fixed;
      }
    }

    return str_replace(['Â·', 'Â', 'Ã', '�'], ['·', '', '', ''], $text);
  };
@endphp
<div class="card shadow-sm">
  <div class="card-header bg-primary text-white">
    <h4>Instagram Sell Settings</h4>
  </div>

  <div class="card-body">
    @if(session('success'))
      <div class="alert alert-success">{{ session('success') }}</div>
    @endif

    <form method="POST" action="{{ url('/admin/in-settings') }}">
      @csrf

      {{-- Account Password --}}
      <div class="mb-3">
        <label class="form-label">Instagram একাউন্টে লগইনের পাসওয়ার্ড</label>
        <input type="text" name="account_password"
               value="{{ $normalizeText($setting->account_password ?? '') }}"
               class="form-control" required>
      </div>

      {{-- Price --}}
      <div class="mb-3">
        <label class="form-label">প্রতি একাউন্ট প্রাইস (৳)</label>
        <input type="number" step="0.01" name="per_account_price"
               value="{{ $setting->per_account_price ?? 0 }}"
               class="form-control" required>
      </div>

      {{-- Limit --}}
      <div class="mb-3">
        <label class="form-label">প্রতিদিন ইউজার কয়টি জমা দিতে পারবে?</label>
        <input type="number" name="daily_limit_per_user"
               value="{{ $setting->daily_limit_per_user ?? 0 }}"
               class="form-control" required>
      </div>

      <div class="mb-3">
        <label class="form-label">OFF Notice Telegram Link</label>
        <input type="text" name="telegram_link"
               value="{{ $normalizeText(old('telegram_link', $setting->telegram_link ?? '')) }}"
               class="form-control"
               placeholder="https://t.me/your_channel">
      </div>

      {{-- Toggle --}}
      <div class="form-check mb-3">
        <input type="checkbox" name="submission_enabled"
               class="form-check-input"
               {{ ($setting->submission_enabled ?? false) ? 'checked' : '' }}>
        <label class="form-check-label">Instagram সাবমিশন চালু</label>
      </div>

      {{-- Upline Commissions --}}
      <div class="mb-3">
        <label class="form-label fw-semibold">
          আপলাইন কমিশন (লেভেল অনুযায়ী)
        </label>

        <div id="commissionWrap" class="row g-2">
          @php
            $commissions = $setting->upline_commissions ?? [0.50];
          @endphp

          @foreach($commissions as $i => $val)
            <div class="col-md-4 commission-row">
              <div class="input-group">
                <span class="input-group-text">Level {{ $i+1 }}</span>
                <input type="number" step="0.01" min="0"
                       name="upline_commissions[]"
                       value="{{ $val }}"
                       class="form-control">
                <button type="button" class="btn btn-outline-danger btn-remove">×</button>
              </div>
            </div>
          @endforeach
        </div>

        <button type="button" id="addCommission"
                class="btn btn-outline-primary btn-sm mt-2">
          + Add Level
        </button>

        <div class="text-muted mt-1" style="font-size:12px;">
          0 দিলে ঐ লেভেলে কমিশন যাবে না
        </div>
      </div>

      <button type="submit" class="btn btn-success w-100">
        Update Settings
      </button>
    </form>
  </div>
</div>

<script>
(function(){
  const wrap = document.getElementById('commissionWrap');
  const addBtn = document.getElementById('addCommission');

  function renumber(){
    wrap.querySelectorAll('.commission-row').forEach((row, i)=>{
      row.querySelector('.input-group-text').innerText = 'Level ' + (i+1);
    });
  }

  wrap.addEventListener('click', e=>{
    if(e.target.classList.contains('btn-remove')){
      e.target.closest('.commission-row').remove();
      renumber();
    }
  });

  addBtn.addEventListener('click', ()=>{
    const div = document.createElement('div');
    div.className = 'col-md-4 commission-row';
    div.innerHTML = `
      <div class="input-group">
        <span class="input-group-text">Level X</span>
        <input type="number" step="0.01" min="0"
               name="upline_commissions[]" value="0"
               class="form-control">
        <button type="button" class="btn btn-outline-danger btn-remove">×</button>
      </div>`;
    wrap.appendChild(div);
    renumber();
  });

  renumber();
})();
</script>
@endsection
