@extends('layouts.app')

@section('title','Settings')

@section('content')
<div class="card">
  <div class="card-header">Settings</div>
  <div class="card-body">
    @if (session('ok'))
      <div style="margin-bottom:12px; padding:10px 12px; border-radius:10px; background:rgba(13,71,161,0.08); color:#0D47A1;">
        {{ session('ok') }}
      </div>
    @endif

    <form method="POST" action="{{ route('settings.update') }}" enctype="multipart/form-data">
      @csrf
      <div style="display:grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap:12px;">
        <div>
          <label>Logo</label>
          <div style="display:flex; align-items:center; gap:12px;">
            <img id="logoPreview" src="/brand/logo?t={{ time() }}" alt="Logo" style="height:48px; width:auto; border:1px solid #e0e0e0; border-radius:8px; background:#fff; padding:6px;" onerror="this.style.display='none'">
            <input type="file" name="logo_file" accept="image/*" />
          </div>
          <div class="muted">Upload PNG/JPG/WEBP/SVG. Served at /brand/logo</div>
        </div>
        <div>
          <label>School Name</label>
          <input type="text" name="school_name" value="{{ old('school_name', $settings['school_name']) }}" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
        </div>
        <div>
          <label>App Name</label>
          <input type="text" name="app_name" value="{{ old('app_name', $settings['app_name']) }}" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
        </div>
        <div>
          <label>Timezone</label>
          <div style="display:grid; grid-template-columns: 1fr 1fr; gap:8px; align-items:center;">
            <input id="tzInput" type="text" name="timezone" value="{{ old('timezone', $settings['timezone']) }}" placeholder="e.g. Africa/Lagos" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
            <select id="tzSelect" style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
              @php $tzCur = old('timezone', $settings['timezone']); @endphp
              @foreach (['Africa/Lagos','UTC','Africa/Accra','Africa/Nairobi','Europe/London','Europe/Berlin','America/New_York','America/Chicago','Asia/Dubai','Asia/Kolkata'] as $tz)
                <option value="{{ $tz }}" {{ $tzCur===$tz ? 'selected' : '' }}>{{ $tz }}</option>
              @endforeach
            </select>
          </div>
          <div class="muted">Use an IANA timezone (left). Quick select (right).</div>
        </div>
        <div>
          <label>Date Format</label>
          @php $dateFmt = old('date_format', $settings['date_format']); @endphp
          <select name="date_format" id="dateFormat" style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
            @foreach (['Y-m-d','d/m/Y','m/d/Y','d M Y','M d, Y'] as $fmt)
              <option value="{{ $fmt }}" {{ $dateFmt===$fmt ? 'selected' : '' }}>{{ $fmt }}</option>
            @endforeach
          </select>
          <div class="muted">PHP date format. Preview: <span id="datePreview"></span></div>
        </div>
        <div>
          <label>Time Format</label>
          @php $timeFmt = old('time_format', $settings['time_format']); @endphp
          <select name="time_format" id="timeFormat" style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
            @foreach (['H:i','H:i:s','g:i A','g:i:s A'] as $fmt)
              <option value="{{ $fmt }}" {{ $timeFmt===$fmt ? 'selected' : '' }}>{{ $fmt }}</option>
            @endforeach
          </select>
          <div class="muted">PHP time format. Preview: <span id="timePreview"></span></div>
        </div>
        <div>
          <label>School Start Time</label>
          <input type="time" name="school_start_time" value="{{ old('school_start_time', $settings['school_start_time']) }}" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
          <div class="muted">Used to mark students as Late after the grace period.</div>
        </div>
        <div>
          <label>School End Time</label>
          <input type="time" name="school_end_time" value="{{ old('school_end_time', $settings['school_end_time']) }}" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
        </div>
        <div>
          <label>Grace Minutes</label>
          <input type="number" min="0" max="120" name="grace_minutes" value="{{ old('grace_minutes', $settings['grace_minutes']) }}" placeholder="e.g. 15" required style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
          <div class="muted">Minutes after start time before marking as Late.</div>
        </div>
      </div>
      <div style="margin-top:16px; display:flex; gap:10px;">
        <button class="btn" type="submit">Save Settings</button>
        <a class="btn secondary" href="/" style="background:#90A4AE;">Cancel</a>
      </div>
    </form>
  </div>
</div>

@if (config('app.env') !== 'production')
<div class="card" style="margin-top:16px;">
  <div class="card-header">Test WhatsApp (Dev only)</div>
  <div class="card-body">
    <form method="POST" action="{{ route('settings.test_whatsapp') }}" style="display:grid; grid-template-columns: 1fr 2fr auto; gap:10px; align-items:end;">
      @csrf
      <div>
        <label>To Number</label>
        <input type="text" name="to_number" placeholder="e.g. +2348012345678" style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
      </div>
      <div>
        <label>Message</label>
        <input type="text" name="message" placeholder="Hello from CPS Attendance" style="width:100%; padding:10px 12px; border-radius:10px; border:1px solid #cfd8dc;">
      </div>
      <div>
        <button class="btn" type="submit">Send Test</button>
      </div>
    </form>
    <div class="muted" style="margin-top:6px;">If Twilio credentials are not set, the message will be queued and marked not sent.</div>
  </div>
</div>
@endif
<script>
  // Live previews for date/time format and logo upload
  document.addEventListener('DOMContentLoaded', function(){
    function fmtDate(date, fmt){
      // Minimal client-side preview, not full PHP tokens support
      const pad=(n)=>String(n).padStart(2,'0');
      const months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      const Y=date.getFullYear();
      const m=date.getMonth()+1; const d=date.getDate();
      const H=pad(date.getHours());
      const i=pad(date.getMinutes());
      const s=pad(date.getSeconds());
      const g=((date.getHours()%12)||12);
      const A=date.getHours()<12?'AM':'PM';
      return fmt
        .replace('Y',Y)
        .replace('m',pad(m))
        .replace('d',pad(d))
        .replace('M',months[m-1])
        .replace('H',H)
        .replace('i',i)
        .replace('s',s)
        .replace('g',g)
        .replace('A',A);
    }
    function updatePreviews(){
      const now=new Date();
      const df=document.getElementById('dateFormat').value;
      const tf=document.getElementById('timeFormat').value;
      document.getElementById('datePreview').textContent=fmtDate(now, df);
      document.getElementById('timePreview').textContent=fmtDate(now, tf);
    }
    const dfSel=document.getElementById('dateFormat');
    const tfSel=document.getElementById('timeFormat');
    if(dfSel&&tfSel){
      dfSel.addEventListener('change', updatePreviews);
      tfSel.addEventListener('change', updatePreviews);
      updatePreviews();
    }
    const fileInput=document.querySelector('input[name="logo_file"]');
    if(fileInput){
      fileInput.addEventListener('change', function(){
        const f=this.files && this.files[0];
        if(!f) return;
        const reader=new FileReader();
        reader.onload=function(e){
          const img=document.getElementById('logoPreview');
          if(img){img.style.display='block'; img.src=e.target.result;}
        };
        reader.readAsDataURL(f);
      });
    }
    // Timezone quick select sync
    const tzInput=document.getElementById('tzInput');
    const tzSelect=document.getElementById('tzSelect');
    if(tzInput && tzSelect){
      tzSelect.addEventListener('change', function(){ tzInput.value=this.value; });
    }
  });
  </script>
@endsection
