@extends('layouts.admin')
@section('title','Tax Settings')

@section('content')

<style>
/* ── Toggle switch ── */
.ts-toggle{position:relative;display:inline-flex;align-items:center;cursor:pointer;gap:.625rem}
.ts-toggle input{position:absolute;opacity:0;width:0;height:0}
.ts-track{width:2.5rem;height:1.375rem;border-radius:9999px;background:var(--border);border:1px solid var(--border);position:relative;transition:background .2s;flex-shrink:0}
.ts-toggle input:checked ~ .ts-track{background:var(--foreground);border-color:var(--foreground)}
.ts-thumb{position:absolute;top:2px;left:2px;width:15px;height:15px;border-radius:50%;background:var(--background);box-shadow:0 1px 3px rgba(0,0,0,.2);transition:transform .2s cubic-bezier(.34,1.56,.64,1)}
.ts-toggle input:checked ~ .ts-track .ts-thumb{transform:translateX(1.125rem)}
.ts-lbl{font-size:.875rem;color:var(--foreground);font-weight:500;user-select:none}

/* ── Disabled state dropdown ── */
.select:disabled,.input:disabled{background:var(--muted);color:var(--muted-foreground);cursor:not-allowed;opacity:.7}
</style>

{{-- ══ Page header ══ --}}
<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:1.5rem;margin-bottom:1.5rem">
  <div>
    <h1 style="font-size:1.25rem;font-weight:800;color:var(--foreground);letter-spacing:-.025em;margin:0 0 .25rem">Tax Configuration</h1>
    <p style="font-size:.8125rem;color:var(--muted-foreground);margin:0">Enterprise-grade taxation engine with regional priority resolution.</p>
  </div>

  <div style="display:flex;align-items:center;gap:1.75rem;flex-shrink:0">
    @foreach([[$stats['total'],'Total Rules'],[$stats['countries'],'Countries'],[$stats['regions'],'Regions']] as [$val,$lbl])
    <div style="text-align:center">
      <div style="font-size:1.5rem;font-weight:800;color:var(--foreground);line-height:1">{{ $val }}</div>
      <div style="font-size:.68rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.07em;margin-top:2px">{{ $lbl }}</div>
    </div>
    @endforeach
    <div style="text-align:center">
      <div style="font-size:.68rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.07em;margin-bottom:.375rem">Tax Support</div>
      <form method="POST" action="{{ route('admin.tax.settings') }}" id="tax-enabled-form">
        @csrf
        @foreach(array_filter($settings, fn($k) => $k !== 'tax_enabled', ARRAY_FILTER_USE_KEY) as $k => $v)
          <input type="hidden" name="{{ $k }}" value="{{ $v }}">
        @endforeach
        <label class="ts-toggle" style="gap:0" onchange="document.getElementById('tax-enabled-form').submit()">
          <input type="checkbox" name="tax_enabled" value="1" @checked($settings['tax_enabled']==='1')>
          <span class="ts-track"><span class="ts-thumb"></span></span>
        </label>
      </form>
    </div>
  </div>
</div>


<form method="POST" action="{{ route('admin.tax.settings') }}" id="main-form">
@csrf

{{-- ══ GLOBAL SETTINGS ══ --}}
<div class="card" style="margin-bottom:1.25rem">
  <div class="card-header">
    <div style="display:flex;align-items:center;gap:.625rem">
      <svg width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065zM15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
      </svg>
      <div class="card-title">Global Settings</div>
    </div>
    <button type="submit" class="btn btn-primary btn-sm">
      <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
      Save Settings
    </button>
  </div>

  <div style="padding:1.375rem">

    {{-- Row 1 --}}
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:1rem;margin-bottom:1.25rem">
      <div>
        <label>Tax Calculation Type</label>
        <select name="tax_calculation_type" class="select">
          <option value="exclusive" @selected($settings['tax_calculation_type']==='exclusive')>Exclusive (Add on top)</option>
          <option value="inclusive" @selected($settings['tax_calculation_type']==='inclusive')>Inclusive (Included in price)</option>
        </select>
      </div>
      <div>
        <label>Tax ID Label</label>
        <input type="text" name="tax_id_label" class="input" value="{{ $settings['tax_id_label'] }}" placeholder="Tax ID/VAT/GST">
      </div>
      <div>
        <label>Discount Logic</label>
        <select name="tax_discount_logic" class="select">
          <option value="tax_after_discount"  @selected($settings['tax_discount_logic']==='tax_after_discount')>Tax after discount</option>
          <option value="tax_before_discount" @selected($settings['tax_discount_logic']==='tax_before_discount')>Tax before discount</option>
          <option value="no_tax_on_discount"  @selected($settings['tax_discount_logic']==='no_tax_on_discount')>No tax on discounted</option>
        </select>
      </div>
      <div>
        <label>Home Country</label>
        <select name="tax_home_country" id="gs-country" class="select" onchange="syncHomeCountry(this.value)">
          <option value="">— Select Country —</option>
          @foreach($countries as $c)
          <option value="{{ $c }}" @selected($settings['tax_home_country']===$c)>{{ $c }}</option>
          @endforeach
        </select>
      </div>
    </div>

    {{-- Advanced --}}
    <div style="border-top:1px solid var(--border);padding-top:1.25rem;margin-bottom:1.25rem">
      <div style="font-size:.8125rem;font-weight:700;color:var(--foreground);margin-bottom:1rem">Advanced Configuration</div>

      <div style="display:grid;grid-template-columns:1fr auto auto;gap:1.5rem;align-items:start;margin-bottom:1.25rem">
        <div>
          <label>Tax Exempt Countries
            <span style="font-size:.72rem;font-weight:400;color:var(--muted-foreground)">(comma-separated)</span>
          </label>
          <input type="text" name="tax_exempt_countries" class="input"
            value="{{ $settings['tax_exempt_countries'] }}" placeholder="US, AU, CA, DE">
        </div>
        <div style="padding-top:1.625rem">
          <label class="ts-toggle">
            <input type="hidden" name="tax_exempt_if_tax_id" value="0">
            <input type="checkbox" name="tax_exempt_if_tax_id" value="1" @checked($settings['tax_exempt_if_tax_id']==='1')>
            <span class="ts-track"><span class="ts-thumb"></span></span>
            <span class="ts-lbl">Exempt if Tax ID provided</span>
          </label>
        </div>
        <div style="padding-top:1.625rem">
          <label class="ts-toggle">
            <input type="hidden" name="tax_vat_gst_mode" value="0">
            <input type="checkbox" name="tax_vat_gst_mode" value="1" @checked($settings['tax_vat_gst_mode']==='1')>
            <span class="ts-track"><span class="ts-thumb"></span></span>
            <span class="ts-lbl">VAT/GST Mode</span>
          </label>
        </div>
      </div>

      <div style="display:flex;align-items:center;gap:2rem;flex-wrap:wrap">
        @foreach([
          ['tax_domains',   'Tax Domains'],
          ['tax_billable',  'Tax Billable'],
          ['tax_late_fees', 'Tax Late Fees'],
        ] as [$key, $label])
        <label class="ts-toggle">
          <input type="hidden" name="{{ $key }}" value="0">
          <input type="checkbox" name="{{ $key }}" value="1" @checked($settings[$key]==='1')>
          <span class="ts-track"><span class="ts-thumb"></span></span>
          <span class="ts-lbl">{{ $label }}</span>
        </label>
        @endforeach
        <input type="hidden" name="tax_enabled" value="{{ $settings['tax_enabled'] }}">
      </div>
    </div>
  </div>
</div>

</form>

{{-- ══ TAX SIMULATOR ══ --}}
<div class="card" style="margin-bottom:1.25rem">
  <div class="card-header">
    <div>
      <div class="card-title">Tax Simulator</div>
      <div class="card-sub">Instantly test your rules without creating invoices.</div>
    </div>
  </div>
  <div style="padding:1.125rem 1.375rem">
    <form method="POST" action="{{ route('admin.tax.simulate') }}"
      style="display:flex;align-items:flex-end;gap:.75rem;flex-wrap:wrap">
      @csrf

      <div>
        <label style="font-size:.75rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.375rem">Country</label>
        <select name="sim_country" id="sim-country" class="select" style="width:200px"
          onchange="updateStates('sim-country','sim-state')">
          <option value="">— Select Country —</option>
          @foreach($countries as $c)
          <option value="{{ $c }}" @selected(old('sim_country',session('_old_input.sim_country'))===$c)>{{ $c }}</option>
          @endforeach
        </select>
      </div>

      <div>
        <label style="font-size:.75rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.375rem">State / Region</label>
        <select name="sim_state" id="sim-state" class="select" style="width:180px">
          <option value="">All States</option>
        </select>
      </div>

      <div>
        <label style="font-size:.75rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.375rem">Amount</label>
        <div style="position:relative">
          <span style="position:absolute;left:.75rem;top:50%;transform:translateY(-50%);font-size:.875rem;font-weight:600;color:var(--muted-foreground)">{{ $currencySymbol }}</span>
          <input type="number" name="sim_amount" class="input" style="padding-left:2rem;width:130px"
            step="0.01" min="0" value="{{ session('sim_amount', 100) }}" placeholder="100">
        </div>
      </div>

      <button type="submit" class="btn btn-primary btn-sm" style="height:2.375rem">
        <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        Run Test
      </button>
    </form>

    @if(session('sim_result'))
    @php $r = session('sim_result'); @endphp
    <div style="margin-top:1rem;padding:1rem;background:var(--muted);border:1px solid var(--border);border-radius:var(--radius);display:flex;align-items:flex-start;gap:2rem;flex-wrap:wrap">
      @foreach([
        ['Net Amount',  $currencySymbol.number_format(session('sim_amount'),2)],
        ['Tax Rate',    number_format($r['total_rate'],3).'%'],
        ['Tax Amount',  $currencySymbol.number_format($r['tax_amount'],2)],
        ['Gross Total', $currencySymbol.number_format($r['gross'],2)],
      ] as [$lbl,$val])
      <div>
        <div style="font-size:.72rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.25rem">{{ $lbl }}</div>
        <div style="font-size:1.125rem;font-weight:700;color:var(--foreground)">{{ $val }}</div>
      </div>
      @endforeach
      @if($r['rules']->count())
      <div>
        <div style="font-size:.72rem;font-weight:600;color:var(--muted-foreground);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.375rem">Applied Rules</div>
        <div style="display:flex;gap:.375rem;flex-wrap:wrap">
          @foreach($r['rules'] as $rule)
          <span class="badge b-blue">{{ $rule->name }} {{ number_format($rule->rate,1) }}%</span>
          @endforeach
        </div>
      </div>
      @else
      <p style="font-size:.875rem;color:var(--muted-foreground)">No matching rules found for the selected country/state.</p>
      @endif
    </div>
    @endif
  </div>
</div>

{{-- ══ TAX RULES TABLE ══ --}}
<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title">Tax Rules</div>
      <div class="card-sub">{{ $rules->count() }} rules · Priority resolved by Level then Country → State specificity</div>
    </div>
    <button type="button" class="btn btn-primary btn-sm" onclick="showModal('add-rule-modal')">
      <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
      </svg>
      Add New Rule
    </button>
  </div>

  <table style="width:100%;border-collapse:collapse">
    <thead>
      <tr style="border-bottom:1px solid var(--border)">
        <th class="th">Name</th>
        <th class="th">Country</th>
        <th class="th">State / Region</th>
        <th class="th">Level</th>
        <th class="th">Rate</th>
        <th class="th">Status</th>
        <th class="th">Actions</th>
      </tr>
    </thead>
    <tbody>
      @forelse($rules as $rule)
      <tr class="trow">
        <td class="td" style="font-weight:700;color:var(--foreground)">{{ $rule->name }}</td>
        <td class="td">{{ $rule->country }}</td>
        <td class="td">{{ $rule->state ?? 'All States' }}</td>
        <td class="td"><span class="badge b-gray">{{ $rule->level }}</span></td>
        <td class="td">
          <form method="POST" action="{{ route('admin.tax.rules.update', $rule) }}"
            style="display:flex;align-items:center;gap:.375rem">
            @csrf
            <input type="number" name="rate" class="input"
              style="width:110px;font-family:monospace;font-weight:700;font-size:.875rem;color:#2563eb;padding:.3rem .625rem"
              step="0.001" min="0" max="100" value="{{ number_format($rule->rate,3) }}">
            <span style="font-size:.875rem;color:var(--muted-foreground)">%</span>
            <button type="submit" class="btn btn-xs"
              style="background:#f0fdf4;color:#16a34a;border:1px solid #bbf7d0;padding:.3rem .5rem" title="Save"
              onmouseover="this.style.background='#16a34a';this.style.color='#fff'"
              onmouseout="this.style.background='#f0fdf4';this.style.color='#16a34a'">
              <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/></svg>
            </button>
          </form>
        </td>
        <td class="td">
          <span class="badge {{ $rule->is_active ? 'b-green' : 'b-gray' }}">{{ $rule->is_active ? 'Active' : 'Inactive' }}</span>
        </td>
        <td class="td">
          <div style="display:flex;align-items:center;gap:.375rem">
            <form method="POST" action="{{ route('admin.tax.rules.duplicate', $rule) }}">
              @csrf
              <button type="submit" class="btn btn-secondary btn-xs" title="Duplicate">
                <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
              </button>
            </form>
            <form method="POST" action="{{ route('admin.tax.rules.destroy', $rule) }}">
              @csrf @method('DELETE')
              <button type="submit" class="btn btn-danger btn-xs" onclick="return confirm('Delete {{ $rule->name }}?')" title="Delete">
                <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
              </button>
            </form>
          </div>
        </td>
      </tr>
      @empty
      <tr><td colspan="7" style="padding:3rem;text-align:center;color:var(--muted-foreground);font-size:.875rem">
        No tax rules yet. Click <strong>Add New Rule</strong> to get started.
      </td></tr>
      @endforelse
    </tbody>
  </table>

  <div style="padding:.875rem 1.375rem;border-top:1px solid var(--border);
    display:flex;align-items:center;justify-content:space-between;background:var(--muted)">
    <div style="display:flex;align-items:center;gap:.5rem;font-size:.8125rem;color:var(--muted-foreground)">
      <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
      Changes are not saved automatically — use Save Settings or the inline ✓ buttons.
    </div>
    <button type="submit" form="main-form" class="btn btn-primary btn-sm">
      <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
      Update Tax Settings
    </button>
  </div>
</div>


{{-- ══ ADD RULE MODAL ══ --}}
<div id="add-rule-modal" style="display:none;position:fixed;inset:0;z-index:500;
  align-items:center;justify-content:center;background:rgba(0,0,0,.5);backdrop-filter:blur(2px)">
  <div class="card" style="width:100%;max-width:540px;padding:0;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.15)">

    <div class="card-header">
      <div class="card-title">Add Tax Rule</div>
      <button type="button" class="btn btn-ghost btn-xs" onclick="hideModal('add-rule-modal')"
        style="padding:.25rem .5rem;font-size:1.125rem;line-height:1">×</button>
    </div>

    <form method="POST" action="{{ route('admin.tax.rules.store') }}" style="padding:1.375rem">
      @csrf
      <div style="display:flex;flex-direction:column;gap:1rem">

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem">
          <div>
            <label>Rule Name <span style="color:var(--destructive)">*</span></label>
            <input type="text" name="name" class="input" placeholder="e.g. GST, VAT, Sales Tax" required>
          </div>
          <div>
            <label>Rate (%) <span style="color:var(--destructive)">*</span></label>
            <input type="number" name="rate" class="input"
              style="font-family:monospace;font-weight:700"
              step="0.001" min="0" max="100" placeholder="18.000" required>
          </div>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:.75rem">
          <div>
            <label>Country <span style="color:var(--destructive)">*</span></label>
            <select name="country" id="rule-country" class="select" required
              onchange="updateStates('rule-country','rule-state')">
              <option value="">— Select Country —</option>
              @foreach($countries as $c)
              <option value="{{ $c }}" @selected(setting('tax_home_country')===$c)>{{ $c }}</option>
              @endforeach
            </select>
          </div>
          <div>
            <label>
              State / Region
              <span style="font-size:.72rem;font-weight:400;color:var(--muted-foreground)">(blank = all states)</span>
            </label>
            <select name="state" id="rule-state" class="select">
              <option value="">— All States —</option>
            </select>
          </div>
        </div>

        <div>
          <label>Priority Level</label>
          <select name="level" class="select">
            <option value="Level 1">Level 1 — Primary (highest priority)</option>
            <option value="Level 2">Level 2 — Secondary</option>
            <option value="Level 3">Level 3 — Tertiary</option>
          </select>
          <p style="font-size:.72rem;color:var(--muted-foreground);margin:.25rem 0 0">
            Multiple rules at the same level are summed. Lower number = higher priority.
          </p>
        </div>

      </div>

      <div style="display:flex;justify-content:flex-end;gap:.5rem;margin-top:1.375rem;padding-top:1rem;border-top:1px solid var(--border)">
        <button type="button" class="btn btn-secondary btn-sm" onclick="hideModal('add-rule-modal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-sm">
          Add Rule
          <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </form>
  </div>
</div>

{{-- Countries + states data for JS ──────────────────────────────────── --}}
<script>
const COUNTRIES_DATA = @json($countriesData);

/**
 * Populate a state <select> based on the selected country.
 * @param {string} countrySelectId
 * @param {string} stateSelectId
 * @param {string} [selectedState]   — pre-select this value after populating
 */
function updateStates(countrySelectId, stateSelectId, selectedState) {
  const country     = document.getElementById(countrySelectId).value;
  const stateSelect = document.getElementById(stateSelectId);
  const states      = COUNTRIES_DATA[country] || [];

  // Clear existing options
  stateSelect.innerHTML = '';

  const allOpt = document.createElement('option');
  allOpt.value       = '';
  allOpt.textContent = states.length ? '— All States —' : '— No regions —';
  stateSelect.appendChild(allOpt);

  states.forEach(function(s) {
    const opt = document.createElement('option');
    opt.value       = s;
    opt.textContent = s;
    if (s === selectedState) opt.selected = true;
    stateSelect.appendChild(opt);
  });

  // Disable the dropdown if there are no states
  stateSelect.disabled = states.length === 0;
}

function showModal(id) { document.getElementById(id).style.display = 'flex'; }
function hideModal(id) { document.getElementById(id).style.display = 'none'; }
document.querySelectorAll('[id$="-modal"]').forEach(function(m) {
  m.addEventListener('click', function(e) { if (e.target === this) hideModal(this.id); });
});

// Pre-populate state dropdowns on page load
(function() {
  // Simulator — restore previous selection if available
  const prevCountry = @json(old('sim_country', session('_old_input.sim_country', '')));
  const prevState   = @json(old('sim_state',   session('_old_input.sim_state',   '')));
  if (prevCountry) {
    const simCountry = document.getElementById('sim-country');
    if (simCountry) {
      simCountry.value = prevCountry;
      updateStates('sim-country', 'sim-state', prevState);
    }
  }

  // Add Rule modal — pre-select home country
  const homeCountry = @json(setting('tax_home_country', ''));
  const ruleCountry = document.getElementById('rule-country');
  if (ruleCountry && homeCountry) {
    ruleCountry.value = homeCountry;
    updateStates('rule-country', 'rule-state');
  }
})();
</script>

@endsection
