@extends('layouts.appmin')

@section('tajuk')
Permohonan Lesen Penjaja
@endsection

@section('css')

    <!-- Select2 -->
    <link rel="stylesheet" href="{{ asset('plugins/select2/css/select2.min.css') }}">
    <link rel="stylesheet" href="{{ asset('plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css') }}">
<link href="{{ asset('css/jsapi-template-main.css') }}" rel="stylesheet" type="text/css"/>
<link href="https://js.arcgis.com/4.25/esri/css/main.css" rel="stylesheet" type="text/css" />
<style>
#viewDiv {
  padding: 0;
  margin: 0;
  height: 50vh;
  width: 100%;  
  touch-action: none;
}
</style>
@endsection

@section('breadcrumb')
    <ul class="breadcrumbs mb-3">
        <li class="nav-home">
            <a href="#">
            <i class="icon-home"></i>
            </a>
        </li>
        <li class="separator">
            <i class="icon-arrow-right"></i>
        </li>
        <li class="nav-item">
            <a href="#">Penjaja</a>
        </li>
        <li class="separator">
            <i class="icon-arrow-right"></i>
        </li>
        <li class="nav-item">
            <a href="#">Permohonan Baru</a>
        </li>
    </ul>
@endsection

@section('content')

    @if (session('success'))
        <div class="alert alert-success" role="alert">
            {{ session('success') }}
        </div>
    @endif
<form action="{{route('penjaja-simpan_mohon')}}" method="post" enctype="multipart/form-data">
    @csrf
    <input type="hidden" name="pemohon_id" value="{{$user->id}}">
    <input type="hidden" name="mohon_id" value="{{$permohonan?->id}}">
    <div class="row mt-4">
        <div class="col-sm-12 col-lg-6">
            <div class="card mb-3">
                <div class="card-header">
                    <h3 class="card-title">MAKLUMAT PERIBADI PEMOHON</h3>
                </div> <!-- /.card-header -->
                <div class="card-body">
                    <dl class="row">
                        <dt class="col-sm-3 col-md-2">No KP</dt>
                        <dd class="col-sm-9 col-md-10">{{ old('nokp', $user->nokp) }}</dd>
                        <dt class="col-sm-3 col-md-2">Nama</dt>
                        <dd class="col-sm-9 col-md-10">{{ old('name', $user->name) }}</dd>
                        <dt class="col-sm-3 col-md-2">Email</dt>
                        <dd class="col-sm-3 col-md-4">{{ old('email', $user->email) }}</dd>
                        <dt class="col-sm-3 col-md-2">No Telefon</dt>
                        <dd class="col-sm-3 col-md-4">{{ old('notelefon', $user->notelefon) }}</dd>
                        <dt class="col-sm-3 col-md-2">Alamat</dt>
                        <dd class="col-sm-9 col-md-10">{{ old('alamat', $user->alamat) }}</dd>
                        <dt class="col-sm-6 col-md-2">Jantina</dt>
                        <dd class="col-sm-6 col-md-4">{{ old('jantina', $user->jantina) }}</dd>
                        <dt class="col-sm-6 col-md-2">Bangsa</dt>
                        <dd class="col-sm-6 col-md-4">{{ old('bangsa', $user->bangsa) }}</dd>
                    </dl>                            
                </div>
            </div>
            <div class="card mb-3">
                <div class="card-header">
                    <h3 class="card-title">MAKLUMAT PERNIAGAAN ( SSM )</h3>
                </div> <!-- /.card-header -->
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="nossm">No SSM</label>
                            <input id="nossm" name="nossm" type="text"
                                value="{{ old('nossm', $permohonan?->syarikat?->nossm) }}" autofocus 
                                    class="form-control @error('nossm') is-invalid @enderror">
                            @error('nossm')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="jenis_perniagaan">Jenis Perniagaan</label>
                            <select id="jenis_perniagaan" name="jenis_perniagaan" class="form-select @error('jenis_perniagaan') is-invalid @enderror" required>
                                <option value=""></option>    
                                <option value="milikan tunggal" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'milikan tunggal' ? 'selected' : ''}}>milikan tunggal</option>
                                <option value="perkongsian" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'perkongsian' ? 'selected' : ''}}>perkongsian</option>
                                <option value="perkongsian liabiliti terhad" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'perkongsian liabiliti terhad' ? 'selected' : ''}}>perkongsian liabiliti terhad</option> 
                                <option value="sendirian berhad" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'sendirian berhad' ? 'selected' : ''}}>sendirian berhad</option>
                                <option value="berhad" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'berhad' ? 'selected' : ''}}>berhad</option>
                                <option value="koperasi" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'koperasi' ? 'selected' : ''}}>koperasi</option>
                                <option value="pertubuhan/persatuan/kelab" {{ old('jenis_perniagaan', $permohonan?->syarikat?->jenis_perniagaan) == 'pertubuhan/persatuan/kelab' ? 'selected' : ''}}>pertubuhan/persatuan/kelab</option>
                            </select>
                                @error('jenis_perniagaan')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror 
                        </div>
                    </div>
                    <div class="row">
                        <div class="mb-3">
                            <label for="nama_perniagaan">Nama Perniagaan</label>
                            <input id="nama_perniagaan" name="nama_perniagaan" type="text"  
                                value="{{ old('nama_perniagaan', $permohonan?->syarikat?->name) }}" required autofocus autocomplete="nama_perniagaan"
                                class="form-control @error('nama_perniagaan') is-invalid @enderror">
                                @error('nama_perniagaan')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror 
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                                <label for="alamat_perniagaan">Alamat Perniagaan</label>
                                <textarea id="alamat_perniagaan" name="alamat_perniagaan" type="text" class="form-control" required>{{ old('alamat_perniagaan', $permohonan?->syarikat?->alamat) }}</textarea>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="notelefon_perniagaan">No Telefon</label>
                            <input id="notelefon_perniagaan" name="notelefon_perniagaan" type="text" class="form-control" value="{{ old('notelefon_perniagaan', $permohonan?->syarikat?->notelefon) }}" required autofocus autocomplete="notelefon_perniagaan" />
                        </div>
                        <div class="col-md-6">
                            <label for="bil_cawangan">Bil Cawangan</label>
                            <input id="bil_cawangan" name="bil_cawangan" type="text" class="form-control" value="{{ old('bil_cawangan', $permohonan?->syarikat?->bil_cawangan) }}" required autofocus autocomplete="bil_cawangan" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="card mb-3">
                <div class="card-header">
                    <h3 class="card-title">PERMOHONAN LESEN PENJAJA</h3>
                </div> <!-- /.card-header -->
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="jenis_penjaja">Jenis Penjaja</label>
                                <select id="jenis_penjaja" class="form-select @error('jenis_penjaja') is-invalid @enderror" name="jenis_penjaja">
                                    <option value="">Pilih Jenis Penjaja</option>
                                @foreach($jenis_penjajas as $jenis_penjaja)
                                    <option value="{{ $jenis_penjaja->id }}" 
                                        data-kategori="{{ strtolower($jenis_penjaja->kategori) }}"
                                        data-jenis="{{ strtolower($jenis_penjaja->jenis) }}"
                                        @selected(old('jenis_penjaja', $permohonan?->jenis_penjaja_id) == $jenis_penjaja->id)>
                                        {{ ucwords($jenis_penjaja->kategori) }} ({{ $jenis_penjaja->jenis }})
                                    </option>
                                @endforeach
                                    <option value="999"
                                        data-kategori="lain"
                                        data-jenis="lain" 
                                        {{ old('jenis_penjaja', $permohonan?->jenis_penjaja_id) == '0' ? 'selected' : '' }}>Lain-lain</option>
                                </select>

                            @error('jenis_penjaja')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror                              
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="jenis_penjaja_lain">Nyatakan Jenis Penjaja Lain</label>
                                <input id="jenis_penjaja_lain" class="form-control @error('jenis_penjaja_lain') is-invalid @enderror" type="text" name="jenis_penjaja_lain" disabled value="{{ old('jenis_penjaja_lain', $permohonan?->jenis_lain) }}" autofocus autocomplete="jenis_penjaja_lain">                               

                            @error('jenis_penjaja_lain')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror                              
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="jenis_kenderaan">Jenis Kenderaan</label>
                                <select id="jenis_kenderaan" class="form-select @error('jenis_kenderaan') is-invalid @enderror" name="jenis_kenderaan" >
                                    <option value=""></option>
                                    <option value="kereta sorong" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'kereta sorong' ? 'selected' : ''}}>kereta sorong</option>
                                    <option value="basikal" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'basikal' ? 'selected' : ''}}>basikal</option>
                                    <option value="motosikal" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'motosikal' ? 'selected' : ''}}>motosikal</option>
                                    <option value="beca / basikal roda tiga" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'beca / basikal roda tiga' ? 'selected' : ''}}>beca / basikal roda tiga</option>
                                    <option value="motosikal roda tiga" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'motosikal roda tiga' ? 'selected' : ''}}>motosikal roda tiga</option>
                                    <option value="kereta / wagon" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'kereta / wagon' ? 'selected' : ''}}>kereta / wagon</option>
                                    <option value="van" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'van' ? 'selected' : ''}}>van</option>
                                    <option value="lori" {{ old('jenis_kenderaan', $permohonan?->jenis_kenderaan) == 'lori' ? 'selected' : ''}}>lori</option>
                                </select>  

                                @error('jenis_kenderaan')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                                <small>Penjaja berkenderaan / Foodtruck / Car boot Sale sahaja</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="no_pendaftaran">No Pendaftaran Kenderaan</label>
                                <input id="no_pendaftaran" class="form-control @error('no_pendaftaran') is-invalid @enderror" type="text" name="no_pendaftaran" value="{{ old('no_pendaftaran', $permohonan?->no_pendaftaran) }}" autofocus autocomplete="no_pendaftaran">
                                @error('no_pendaftaran')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="status_tanah">Status Tanah</label>
                                <select id="status_tanah" class="form-select @error('status_tanah') is-invalid @enderror" name="status_tanah">
                                    <option value="">Pilih Status Tanah</option>
                                    <option value="hak milik persendirian" {{ old('status_tanah', $permohonan?->status_tanah) == 'hak milik persendirian' ? 'selected' : '' }}>hak milik persendirian</option>                                        
                                    <option value="tanah kerajaan(rezab)" {{ old('status_tanah', $permohonan?->status_tanah) == 'tanah kerajaan(rezab)' ? 'selected' : '' }}>tanah kerajaan(rezab)</option>
                                    <option value="tanah sewa" {{ old('status_tanah', $permohonan?->status_tanah) == 'tanah sewa' ? 'selected' : '' }}>tanah sewa</option>
                                    <option value="tapak parkir" {{ old('status_tanah', $permohonan?->status_tanah) == 'tapak parkir' ? 'selected' : '' }}>tapak parkir</option>
                                    <option value="lain-lain" {{ old('status_tanah', $permohonan?->status_tanah) == 'lain-lain' ? 'selected' : '' }}>lain-lain</option>
                                </select>

                                @error('status_tanah')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror      
                            </div>
                        </div>
                        <div class="col-md-8">
                            <div class="row">
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="penempatan">Pusat Penempatan(jika ada)</label>
                                        <select name="penempatan" id="penempatan" class="form-select">
                                        </select>                             
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="kawasan">Kawasan Penjajaan</label>
                                        <select name="kawasan" id="kawasan" class="form-select" required>
                                        </select>
                                        @error('kawasan')
                                            <div class="invalid-feedback">
                                                {{ $message }}
                                            </div>
                                        @enderror      
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="taman">Taman</label>
                                        <select id="taman" name="taman" class="form-select"  disabled>
                                            <option value="">-- Sila Pilih Taman --</option>
                                        </select>
                                        @error('taman')
                                            <div class="invalid-feedback">
                                                {{ $message }}
                                            </div>
                                        @enderror      
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="jalan">Jalan</label>
                                        <select id="jalan" class="form-select" name="jalan"  disabled>
                                            <option value="">-- Sila Pilih Jalan --</option>
                                        </select>
                                        @error('jalan')
                                            <div class="invalid-feedback">
                                                {{ $message }}
                                            </div>
                                        @enderror      
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="masa_jualan_mula">Masa Mula Jualan</label>
                                        <input id="masa_jualan_mula" class="form-control @error('masa_jualan_mula') is-invalid @enderror" type="time" name="masa_jualan_mula" value="{{ old('masa_jualan_mula', $permohonan?->masa_jualan_mula) }}" autofocus autocomplete="masa_jualan_mula">

                                        @error('masa_jualan_mula')
                                            <div class="invalid-feedback">
                                                {{ $message }}
                                            </div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="masa_jualan_tamat">Masa Tamat Jualan</label>
                                        <input id="masa_jualan_tamat" class="form-control @error('masa_jualan_tamat') is-invalid @enderror" type="time" name="masa_jualan_tamat" value="{{ old('masa_jualan_tamat', $permohonan?->masa_jualan_tamat) }}" autofocus autocomplete="masa_jualan_tamat">

                                        @error('masa_jualan_tamat')
                                            <div class="invalid-feedback">
                                                {{ $message }}
                                            </div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12"><small>Kosongkan jika tidak berkaitan</small></div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="makanan">Makanan</label>
                                <textarea id="makanan" class="form-control @error('makanan') is-invalid @enderror" name="makanan" autofocus autocomplete="makanan" rows="3" cols="40" placeholder="Nyatakan jenis jualan">{{ old('makanan', $permohonan?->makanan) }}</textarea>
                                
                                @error('makanan')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror   
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="minuman">Minuman</label>
                                <textarea id="minuman" class="form-control @error('minuman') is-invalid @enderror" name="minuman" autofocus autocomplete="minuman" rows="3" cols="40" placeholder="Nyatakan jenis jualan" >{{ old('minuman', $permohonan?->minuman) }}</textarea>
                                
                                @error('minuman')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror   
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="lain">Lain-lain</label>
                                <textarea id="lain" class="form-control @error('lain') is-invalid @enderror" name="lain" autofocus autocomplete="lain" rows="3" cols="40" placeholder="Nyatakan jenis jualan" >{{ old('lain', $permohonan?->lain) }}</textarea>
                                
                                @error('lain')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror   
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> <!-- /.col -->   
        <div class="col-sm-12 col-lg-6">
            <div class="card mb-3">
                <div class="card-header">
                    <h3 class="card-title">DOKUMEN DIPERLUKAN</h3>
                </div> <!-- /.card-header -->
                <div class="card-body">    
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_kad_pengenalan">Salinan Kad Pengenalan</label>
                                <input id="doc_kad_pengenalan" class="form-control @error('doc_kad_pengenalan') is-invalid @enderror" type="file" name="doc_kad_pengenalan" value="{{ old('doc_kad_pengenalan') }}" autofocus autocomplete="doc_kad_pengenalan"/>
                                 @error('doc_kad_pengenalan')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-sm-12">
                            @if(!is_null($doc_kad_pengenalan))
                                @if ($doc_kad_pengenalan->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_kad_pengenalan->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_kad_pengenalan->pivot->path]) }}" alt="Salinan IC" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_gambar">Gambar Berukuran Passport</label>
                                <input id="doc_gambar" class="form-control @error('doc_gambar') is-invalid @enderror" type="file" name="doc_gambar" value="{{ old('doc_gambar') }}" autofocus autocomplete="doc_gambar"/>
                                @error('doc_gambar')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div> 
                        <div class="col-sm-12">
                            @if(!is_null($doc_gambar))
                                @if ($doc_gambar->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_gambar->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_gambar->pivot->path]) }}" alt="Gambar Passport" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_lokasi">Gambar Lokasi / Pelan</label>
                                <input id="doc_lokasi" class="form-control @error('doc_lokasi') is-invalid @enderror" type="file" name="doc_lokasi" value="{{ old('doc_lokasi') }}" autofocus autocomplete="doc_lokasi"/>
                                @error('doc_lokasi')
                                    <div class="invalid-feedback">
                                        {{ $message }}
                                    </div>
                                @enderror
                            </div>
                        </div> 
                        <div class="col-sm-12">
                            @if(!is_null($doc_lokasi))
                                @if ($doc_lokasi->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_lokasi->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_lokasi->pivot->path]) }}" alt="Gambar Lokasi" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_kebenaran">Surat kebenaran pemilik tanah / pemegang rezab /perjanjian yang sah</label>
                                <input id="doc_kebenaran" class="form-control" type="file" name="doc_kebenaran" value="{{ old('doc_kebenaran') }}" autofocus autocomplete="doc_kebenaran"/>
                            </div>
                        </div>
                        <div class="col-sm-12">
                            @if(!is_null($doc_kebenaran))
                                @if ($doc_kebenaran->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_kebenaran->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_kebenaran->pivot->path]) }}" alt="Surat Kebenaran" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_kenderaan">Gambar Kenderaan</label>
                                <input id="doc_kenderaan" class="form-control" type="file" name="doc_kenderaan" value="{{ old('doc_kenderaan') }}" autofocus autocomplete="doc_kenderaan"/>
                            </div>
                        </div> 
                        <div class="col-sm-12">
                            @if(!is_null($doc_kenderaan))
                                @if ($doc_kenderaan->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_kenderaan->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_kenderaan->pivot->path]) }}" alt="Gambar Kenderaan" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_kenderaan_geran">Salinan Geran Kenderaan</label>
                                <input id="doc_kenderaan_geran" class="form-control" type="file" name="doc_kenderaan_geran" value="{{ old('doc_kenderaan_geran') }}" autofocus autocomplete="doc_kenderaan_geran"/>
                            </div>
                        </div> 
                        <div class="col-sm-12">
                            @if(!is_null($doc_kenderaan_geran))
                                @if ($doc_kenderaan_geran->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_kenderaan_geran->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_kenderaan_geran->pivot->path]) }}" alt="Gambar Kenderaan" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_suntikan_ty2">Salinan Sijil Suntikan TY2 (Pengendali makanan sahaja)</label>
                                <input id="doc_suntikan_ty2" class="form-control" type="file" name="doc_suntikan_ty2" value="{{ old('doc_suntikan_ty2') }}" autofocus autocomplete="doc_suntikan_ty2"/>
                            </div>
                        </div>
                        <div class="col-sm-12">
                            @if(!is_null($doc_suntikan_ty2))
                                @if ($doc_suntikan_ty2->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_suntikan_ty2->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_suntikan_ty2->pivot->path]) }}" alt="Salinan Suntikan" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                        <div class="col-sm-12">
                            <div class="mb-3">
                                <label for="doc_kursus_makanan">Salinan Sijil Kursus Pengendalian Makanan</label>
                                <input id="doc_kursus_makanan" class="form-control" type="file" name="doc_kursus_makanan" value="{{ old('doc_kursus_makanan') }}" autofocus autocomplete="doc_kursus_makanan"/>
                            </div>
                        </div> 
                        <div class="col-sm-12">
                            @if(!is_null($doc_kursus_makanan))
                                @if ($doc_kursus_makanan->pivot->jenis_dokumen === 'pdf')
                                    <a href="{{ route('dokumen.stream', [$permohonan?->id, $doc_kursus_makanan->pivot->path]) }}" target="_blank">View PDF</a>
                                @else
                                    <img src="{{ route('dokumen.stream', [$permohonan?->id, $doc_kursus_makanan->pivot->path]) }}" alt="Salinan Sijil Kursus Pengendalian Makanan" style="max-width: 100px;">
                                @endif
                            @endif
                        </div>
                    </div> 
                </div>
            </div>
            <div class="card mb-3">
                <div class="card-header">
                    <h3 class="card-title">LOKASI PENJAJAAN</h3>
                </div> <!-- /.card-header -->
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="longitude">Longitud</label>
                                <input id="longitude" class="form-control" type="text" name="longitude" value="{{ old('longitude', $permohonan?->longitude) }}" autofocus autocomplete="longitude"/>
                            </div>
                        </div> 
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="latitude">Latitud</label>
                                <input id="latitude" class="form-control" type="text" name="latitude" value="{{ old('latitude', $permohonan?->latitude) }}" autofocus autocomplete="latitude"/>
                            </div>
                        </div>
                    </div> 

                    <div class="mt-3">
                        <label>Cari Lokasi (Nominatim)</label>
                        <input type="text" id="searchBox" class="form-control" placeholder="Taip nama tempat… (contoh: Taman Sutera)">
                        <button id="searchBtn" type="button" class="btn btn-primary mt-2"><i class="fa-regular fa-magnifying-glass-location"></i> Cari</button>
                    </div>
                    <div id="viewDiv" style="height: 450px;" class="mt-4"></div>
                </div>
            </div>
        </div> <!-- /.col -->                   
    </div> <!--end::Row-->
    <div class="row mt-4">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body text-center">
                <input id="hantar" class="btn btn-primary" type="submit" value="Simpan"/>
                </div> <!-- /.card-header -->
            </div> <!-- /.card-header -->
        </div> <!-- /.col -->               
    </div> <!--end::Row-->
</form>
@endsection

@section('js')
<script src="{{ asset('plugins/select2/js/select2.full.min.js') }}"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
    // Preload value dari Blade
    const defaultKawasanId    = "{{ $permohonan->kawasan_id ?? '' }}";
    const defaultTamanId      = "{{ $permohonan->taman_id ?? '' }}";
    const defaultJalanId      = "{{ $permohonan->jalan_id ?? '' }}";
    const defaultPenempatanId = "{{ $permohonan->penempatan_id ?? '' }}";
</script>

<script>
$(function() {

    /* ============================================================
     * 1. FIELD TOGGLE HANDLER (Jenis Penjaja & Jenis Kenderaan)
     * ============================================================ */
    function resetFields() {
        $('#jenis_kenderaan')
            .prop('disabled', true)
            .val('');

        $('#penempatan')
            .prop('disabled', true)
            .val('');

        $('#jenis_penjaja_lain')
            .prop('disabled', true)
            .val('');
    }

    /*function handleJenisPenjaja() {
        let selected = $("#jenis_penjaja").val();
        $("#jenis_penjaja_lain").prop("disabled", selected !== "lain-lain");

        if (selected !== "lain-lain") $("#jenis_penjaja_lain").val("");
    }*/

    function handleJenisPenjaja() {
        resetFields();

        const selected = $('#jenis_penjaja option:selected');

        const kategori = selected.data('kategori');
        const jenis    = selected.data('jenis');

        // Kategori: lain
        if (kategori === 'lain') {
            $('#jenis_penjaja_lain').prop('disabled', false);
            $("#jenis_penjaja_lain").val("");
        }

        // Kategori: Berkenderaan
        if (kategori === 'berkenderaan') {
            $('#jenis_kenderaan').prop('disabled', false);
        }

        // Kategori: Statik + Jenis: Penempatan Berpusat
        if (kategori === 'statik' && jenis === 'penempatan berpusat') {
            $('#penempatan').prop('disabled', false);
        }
    }

    function handleJenisKenderaan() {
        let jenis = $("#jenis_kenderaan").val();
        let disable = (jenis === "kereta sorong" || jenis === "basikal" || jenis === "");

        $("#no_pendaftaran").prop("disabled", disable);

        if (disable) $("#no_pendaftaran").val("");
    }

    // Run on load
    handleJenisPenjaja();
    handleJenisKenderaan();

    // Event listener
    $("#jenis_penjaja").on("change", handleJenisPenjaja);
    $("#jenis_kenderaan").on("change", handleJenisKenderaan);


    /* ============================================================
     * 2. LEAFLET MAP + NOMINATIM SEARCH
     * ============================================================ */

    let defaultLat  = {{ $permohonan?->latitude ?? 1.494314512652013 }};
    let defaultLng  = {{ $permohonan?->longitude ?? 103.63506317138673 }};
    let defaultZoom = {{ isset($permohonan?->latitude) ? 16 : 12 }};
    let marker;

    // Init map
    let map = L.map('viewDiv').setView([defaultLat, defaultLng], defaultZoom);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '&copy; OpenStreetMap'
    }).addTo(map);

    // Letak marker awal jika edit
    if ("{{ $permohonan?->latitude ?? '' }}") {
        marker = L.marker([defaultLat, defaultLng], { draggable: true }).addTo(map);
        marker.on('dragend', updateInputByMarker);
    }

    // Click = create / move marker
    map.on('click', function(e) {
        placeMarker(e.latlng);
        updateInputFromLatLng(e.latlng);
    });

    function placeMarker(latlng) {
        if (!marker) {
            marker = L.marker(latlng, { draggable: true }).addTo(map);
            marker.on('dragend', updateInputByMarker);
        } else {
            marker.setLatLng(latlng);
        }
    }

    function updateInputByMarker(e) {
        updateInputFromLatLng(e.target.getLatLng());
    }

    function updateInputFromLatLng(latlng) {
        $("#latitude").val(latlng.lat);
        $("#longitude").val(latlng.lng);
    }


    /* ============================================================
     * 3. FUNGSI CARI KOORDINAT (NOMINATIM API)
     * ============================================================ */

    function normalizeToIskandarPuteri(query) {
        const kawasanIP = ['Skudai', 'Gelang Patah', 'Kangkar Pulai', 'Lima Kedai', 'Ulu Choh','Teknologi Johor', 'Pelabuhan Johor'];
        const regex = new RegExp(',\\s*(' + kawasanIP.join('|') + ')$', 'i');
        return query.replace(regex, ', Iskandar Puteri');
    }

    function nominatimSearch(q) {
        const url = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(q);
        return fetch(url, {
            headers: {
                // Nominatim best practice: identify your app (kalau server-side lagi bagus)
                'Accept': 'application/json'
            }
        }).then(r => r.json());
    }

    function applyLocation(place) {
        const lat = parseFloat(place.lat);
        const lon = parseFloat(place.lon);

        map.setView([lat, lon], 17);
        placeMarker({ lat, lng: lon });
        updateInputFromLatLng({ lat, lng: lon });
    }

    async function cariKoordinat() {
        let query = $("#searchBox").val().trim();

        if (query.length < 3) {
            alert("Masukkan nama tempat yang lebih spesifik.");
            return;
        }

        // Candidate 1: asal
        // Candidate 2: fallback IP (hanya kalau memang berubah)
        const q2 = normalizeToIskandarPuteri(query);
        const candidates = (q2 !== query) ? [query, q2] : [query];

        try {
            for (const q of candidates) {
                const data = await nominatimSearch(q);
                if (Array.isArray(data) && data.length > 0) {
                    applyLocation(data[0]);
                    return;
                }
            }

            alert("Lokasi tak dijumpai: " + candidates[candidates.length - 1]);
        } catch (err) {
            console.error(err);
        }
    }


    $("#searchBtn").on("click", cariKoordinat);


    /* ============================================================
     * 4. CASCADING DROPDOWN: KAWASAN → TAMAN → JALAN
     * ============================================================ */


    function loadPenempatan(defaultPenempatanId = null) {
        $.getJSON('/get_penempatan', function (data) {

            // reset dulu
            const $penempatan = $('#penempatan');
            $penempatan.empty().append('<option value="">-- Sila Pilih Penempatan --</option>');

            data.forEach(p => {
                $penempatan.append(
                    $('<option>', {
                        value: p.id,
                        text: p.nama
                    })
                    .attr('data-taman',   p.taman_id ?? '')
                    .attr('data-kawasan', p.kawasan_id ?? '')
                    .attr('data-jalan', p.jalan_id ?? '')
                    .prop('selected', defaultPenempatanId && (String(p.id) === String(defaultPenempatanId)))
                );
            });

            // kalau ada default selected, trigger change supaya auto select kawasan/taman
            if (defaultPenempatanId) {
                $penempatan.trigger('change');
            }
        });
    }

/*     function setSelectValue($select, value) {
        if (value === null || value === undefined || value === '') return false;

        $select.val(String(value));

        // kalau option tu tak wujud (e.g. list kawasan belum load), val() tak akan melekat
        return $select.val() === String(value);
    } */

    function loadKawasan() {
        $.getJSON('/get_kawasan', function(data) {
            $('#kawasan').append('<option value="">-- Sila Pilih Kawasan --</option>');
            data.forEach(k => {
                $('#kawasan').append(
                    $('<option>', {
                        value: k.id,
                        text: k.nama,
                        selected: k.id == defaultKawasanId
                    })
                );
            });

            if (defaultKawasanId && defaultTamanId) {
                loadTaman(defaultKawasanId, defaultTamanId);
            }
        });
    }

    function loadTaman(kawasanId, selectedId = null, done = null) {
        $.getJSON('/get_taman', { kawasan_id: kawasanId }, function(data) {
            $('#taman').empty().append('<option value="">-- Sila Pilih Taman --</option>');
            data.forEach(t => {
                $('#taman').append(
                    $('<option>', {
                        value: t.id,
                        text: t.nama,
                        selected: selectedId && (String(t.id) === String(selectedId))
                    })
                );
            });

            $('#taman').prop('disabled', false);

            // Kekalkan logic asal (default jalan) kalau kau still guna untuk edit page
            if (selectedId && typeof defaultJalanId !== 'undefined' && defaultJalanId) {
                loadJalan(selectedId, defaultJalanId);
            }

            if (typeof done === 'function') done();
        });
    }

    function loadJalan(tamanId, selectedId = null, done = null) {
        $.getJSON('/get_jalan', { taman_id: tamanId }, function(data) {
            $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>');
            data.forEach(j => {
                $('#jalan').append(
                    $('<option>', {
                        value: j.id,
                        text: j.nama,
                        selected: selectedId && (String(j.id) === String(selectedId))
                    })
                );
            });
            $('#jalan').prop('disabled', false);

            if (typeof done === 'function') done();
        });
    }

    /* === EVENT LISTENER KAWASAN/TAMAN/JALAN === */

    $("#kawasan").change(function() {
        let kawasanId = $(this).val();

        $('#taman').empty().append('<option value="">-- Sila Pilih Taman --</option>').prop('disabled', !kawasanId);
        $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>').prop('disabled', true);

        if (kawasanId) loadTaman(kawasanId);
    });

    $("#taman").change(function() {
        let tamanId = $(this).val();
        let namaTaman = $(this).find("option:selected").text() || '';
        let namaKawasan = $("#kawasan option:selected").text() || '';

        $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>').prop('disabled', !tamanId);

        if (tamanId) {
            loadJalan(tamanId);

            // kalau ada penempatan, gabung bagi geocode lagi tepat
            const q = namaTaman ? (namaTaman + "," + namaKawasan) : false;
            if (q) {
                $("#searchBox").val(q);
                cariKoordinat();
            }
        }
    });

    $("#jalan").change(function() {
        let textJalan = $(this).find("option:selected").text() || '';
        let textTaman = $("#taman option:selected").text() || '';

        if (textJalan) {
            // susunan boleh ikut taste; ni aku letak jalan+taman+penempatan
            const parts = [textJalan, textTaman].filter(Boolean);
            $("#searchBox").val(parts.join(", "));
            cariKoordinat();
        }
    });


    $("#penempatan").on('change', function() {
        $('#kawasan').val('');
        $("#searchBox").val('');


        const $opt = $("#penempatan option:selected");

        const kawasanId = $opt.data('kawasan');   // required
        const tamanId   = $opt.data('taman');     // optional (boleh kosong)
        const jalanId   = $opt.data('jalan');     // optional (boleh kosong)


        // Set kawasan dulu
        $('#kawasan').val('');
        $('#kawasan').val(kawasanId ? String(kawasanId) : '');

        // Trigger logic kawasan (tapi kita tak rely event async)
        $('#taman').empty().append('<option value="">-- Sila Pilih Taman --</option>').prop('disabled', true);

        // Load taman & auto select kalau ada tamanId
        loadTaman(kawasanId, tamanId ? String(tamanId) : null, function () {

            // Kalau taman wujud & berjaya dipilih, trigger change taman untuk load jalan + search
            if (tamanId && $('#taman').val() === String(tamanId)) {
                $('#taman').trigger('change');
            } else {
                // taman optional / tak wujud dalam list -> update searchBox based on penempatan
                const textPenempatan = ['#kawasan']
                        .map(id => $(id).val() && $(id + ' option:selected').text())
                        .filter(Boolean)
                        .join(', ');
                if (textPenempatan) {
                    $("#searchBox").val(textPenempatan);
                    cariKoordinat();
                }
            }
        });

        // Trigger logic kawasan (tapi kita tak rely event async)
        $('#jalan').empty().append('<option value="">-- Sila Pilih Jalan --</option>').prop('disabled', true);

        // Load taman & auto select kalau ada tamanId
        loadJalan(tamanId, jalanId ? String(jalanId) : null, function () {

            // Kalau taman wujud & berjaya dipilih, trigger change taman untuk load jalan + search
            if (jalanId && $('#jalan').val() === String(jalanId)) {
                $('#jalan').trigger('change');
            } else {
                // taman optional / tak wujud dalam list -> update searchBox based on penempatan
                const textPenempatan = ['#taman', '#kawasan']
                        .map(id => $(id).val() && $(id + ' option:selected').text())
                        .filter(Boolean)
                        .join(', ');
                if (textPenempatan) {
                    $("#searchBox").val(textPenempatan);
                    cariKoordinat();
                }
            }
        });
    });


    /* ============================================================
     * 5. PAGE INIT LOAD
     * ============================================================ */

    loadKawasan();
    loadPenempatan();

});
</script>
@endsection
