@extends('layouts.app')

@section('title', 'Tambah Rekomposisi UPA')

@section('content')
<div class="container-fluid">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">
                <i class="fas fa-plus me-2"></i>Tambah Rekomposisi UPA
            </h1>
            <p class="text-muted mb-0">Buat rekomposisi Unit Pembinaan Anggota baru</p>
        </div>
        <div>
            <a href="{{ route('rekomposisi-upa.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-1"></i>Kembali
            </a>
        </div>
    </div>

    <form action="{{ route('rekomposisi-upa.store') }}" method="POST" id="rekomposisiForm">
        @csrf
        
        <!-- Basic Information Card -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-info-circle me-1"></i>Informasi Dasar
                </h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="dpc_id" class="form-label">DPC <span class="text-danger">*</span></label>
                        <select name="dpc_id" id="dpc_id" class="form-select @error('dpc_id') is-invalid @enderror" required>
                            <option value="">Pilih DPC</option>
                            @foreach($dpcList as $dpc)
                                <option value="{{ $dpc->dpc_id }}" {{ old('dpc_id') == $dpc->dpc_id ? 'selected' : '' }}>
                                    {{ $dpc->nama_dpc }}
                                </option>
                            @endforeach
                        </select>
                        @error('dpc_id')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-6">
                        <label for="judul_sk" class="form-label">Judul SK <span class="text-danger">*</span></label>
                        <input type="text" name="judul_sk" id="judul_sk" 
                               class="form-control @error('judul_sk') is-invalid @enderror" 
                               value="{{ old('judul_sk', 'REKOMPOSISI UNIT PEMBINAAN ANGGOTA MADYA DEWAN PENGURUS CABANG') }}" required>
                        @error('judul_sk')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-4">
                        <label for="tanggal_sk" class="form-label">Tanggal SK <span class="text-danger">*</span></label>
                        <input type="date" name="tanggal_sk" id="tanggal_sk" 
                               class="form-control @error('tanggal_sk') is-invalid @enderror" 
                               value="{{ old('tanggal_sk', date('Y-m-d')) }}" required>
                        @error('tanggal_sk')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-4">
                        <label for="tanggal_rapat" class="form-label">Tanggal Rapat <span class="text-danger">*</span></label>
                        <input type="date" name="tanggal_rapat" id="tanggal_rapat" 
                               class="form-control @error('tanggal_rapat') is-invalid @enderror" 
                               value="{{ old('tanggal_rapat', date('Y-m-d')) }}" required>
                        @error('tanggal_rapat')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-4">
                        <label for="ditetapkan_tanggal" class="form-label">Ditetapkan Tanggal <span class="text-danger">*</span></label>
                        <input type="date" name="ditetapkan_tanggal" id="ditetapkan_tanggal" 
                               class="form-control @error('ditetapkan_tanggal') is-invalid @enderror" 
                               value="{{ old('ditetapkan_tanggal', date('Y-m-d')) }}" required>
                        @error('ditetapkan_tanggal')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-4">
                        <label for="ditetapkan_di" class="form-label">Ditetapkan di <span class="text-danger">*</span></label>
                        <input type="text" name="ditetapkan_di" id="ditetapkan_di" 
                               class="form-control @error('ditetapkan_di') is-invalid @enderror" 
                               value="{{ old('ditetapkan_di', 'Jakarta') }}" required>
                        @error('ditetapkan_di')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-4">
                        <label for="nomor_sk_lampiran" class="form-label">Nomor SK Lampiran</label>
                        <input type="text" name="nomor_sk_lampiran" id="nomor_sk_lampiran" 
                               class="form-control @error('nomor_sk_lampiran') is-invalid @enderror" 
                               value="{{ old('nomor_sk_lampiran', '036/D/SK/BK/AI-04-PKS/VII/2024') }}">
                        @error('nomor_sk_lampiran')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>

        <!-- Ketua Information Card -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-user-tie me-1"></i>Informasi Ketua
                </h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="ketua_nama" class="form-label">Nama Ketua <span class="text-danger">*</span></label>
                        <input type="text" name="ketua_nama" id="ketua_nama" 
                               class="form-control @error('ketua_nama') is-invalid @enderror" 
                               value="{{ old('ketua_nama', 'Triyono Mukti') }}" required>
                        @error('ketua_nama')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <div class="col-md-6">
                        <label for="ketua_jabatan" class="form-label">Jabatan Ketua <span class="text-danger">*</span></label>
                        <input type="text" name="ketua_jabatan" id="ketua_jabatan" 
                               class="form-control @error('ketua_jabatan') is-invalid @enderror" 
                               value="{{ old('ketua_jabatan', 'Ketua') }}" required>
                        @error('ketua_jabatan')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
            </div>
        </div>


        <!-- Details Card -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-list me-1"></i>Detail Rekomposisi UPA
                </h6>
                <button type="button" class="btn btn-sm btn-primary" id="addDetailRow">
                    <i class="fas fa-plus me-1"></i>Tambah Baris
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="detailsTable">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">No</th>
                                <th width="15%">Kode UPA</th>
                                <th width="20%">Pembimbing Baru</th>
                                <th width="20%">Anggota</th>
                                <th width="15%">DPRa</th>
                                <th width="15%">Pembimbing Lama</th>
                                <th width="10%">Keterangan</th>
                                <th width="5%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="detailsTableBody">
                            <!-- Rows will be added dynamically -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Submit Button -->
        <div class="card shadow">
            <div class="card-body text-center">
                <button type="submit" class="btn btn-primary btn-lg me-2">
                    <i class="fas fa-save me-1"></i>Simpan Rekomposisi
                </button>
                <a href="{{ route('rekomposisi-upa.index') }}" class="btn btn-secondary btn-lg">
                    <i class="fas fa-times me-1"></i>Batal
                </a>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
let detailRowCount = 0;

$(document).ready(function() {
    console.log('Document ready - Rekomposisi UPA Create page loaded');
    console.log('jQuery version:', $.fn.jquery);
    console.log('DPC element found:', $('#dpc_id').length);
    
    // Add first row
    addDetailRow();
    
    // Add row button
    $('#addDetailRow').click(function() {
        addDetailRow();
    });
    
    // DPC change handler
    $('#dpc_id').change(function() {
        console.log('DPC changed to:', $(this).val());
        loadAnggotaAndPembimbing();
    });
    
    // Load initial data if DPC is selected
    if ($('#dpc_id').val()) {
        console.log('Initial DPC value:', $('#dpc_id').val());
        loadAnggotaAndPembimbing();
    }
});

function addDetailRow() {
    detailRowCount++;
    const row = `
        <tr id="row-${detailRowCount}">
            <td>${detailRowCount}</td>
            <td>
                <input type="text" name="details[${detailRowCount}][kode_upa]" 
                       class="form-control form-control-sm" 
                       placeholder="CK 3101" required>
            </td>
            <td>
                <select name="details[${detailRowCount}][pembimbing_baru_id]" 
                        class="form-select form-select-sm pembimbing-select" required>
                    <option value="">Pilih Pembimbing</option>
                </select>
            </td>
            <td>
                <select name="details[${detailRowCount}][anggota_id]" 
                        class="form-select form-select-sm anggota-select" required>
                    <option value="">Pilih Anggota</option>
                </select>
            </td>
            <td>
                <input type="text" name="details[${detailRowCount}][dpr_id]" 
                       class="form-control form-control-sm" 
                       placeholder="Caktim">
            </td>
            <td>
                <select name="details[${detailRowCount}][pembimbing_lama_id]" 
                        class="form-select form-select-sm pembimbing-lama-select">
                    <option value="">Pilih Pembimbing Lama</option>
                </select>
            </td>
            <td>
                <input type="text" name="details[${detailRowCount}][keterangan]" 
                       class="form-control form-control-sm" 
                       placeholder="Keterangan">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger" 
                        onclick="removeDetailRow(${detailRowCount})">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;
    
    $('#detailsTableBody').append(row);
    // Load data for the new row only
    loadDataForNewRow(detailRowCount);
}

function loadDataForNewRow(rowId) {
    const dpcId = $('#dpc_id').val();
    if (!dpcId) {
        console.log('No DPC selected, skipping data load for new row');
        return;
    }
    
    console.log('Loading data for new row:', rowId, 'DPC:', dpcId);
    
    // Load anggota for the new row
    $.get(`{{ route('rekomposisi-upa.anggota-by-dpc') }}?dpc_id=${dpcId}`)
        .done(function(data) {
            console.log('Anggota data received for new row:', data);
            let anggotaOptions = '<option value="">Pilih Anggota</option>';
            data.forEach(function(anggota) {
                anggotaOptions += `<option value="${anggota.id}">${anggota.nama_lengkap} (${anggota.nomor_identitas_anggota})</option>`;
            });
            $(`#row-${rowId} .anggota-select`).html(anggotaOptions);
            console.log('Anggota dropdown updated for new row');
        })
        .fail(function(xhr, status, error) {
            console.error('Error loading anggota for new row:', error, xhr.responseText);
        });
    
    // Load pembimbing for the new row
    $.get(`{{ route('rekomposisi-upa.pembimbing-by-dpc') }}?dpc_id=${dpcId}`)
        .done(function(data) {
            console.log('Pembimbing data received for new row:', data);
            let pembimbingOptions = '<option value="">Pilih Pembimbing</option>';
            data.forEach(function(pembimbing) {
                pembimbingOptions += `<option value="${pembimbing.id}">${pembimbing.nama_lengkap} (${pembimbing.nomor_identitas_anggota})</option>`;
            });
            $(`#row-${rowId} .pembimbing-select, #row-${rowId} .pembimbing-lama-select`).html(pembimbingOptions);
            console.log('Pembimbing dropdown updated for new row');
        })
        .fail(function(xhr, status, error) {
            console.error('Error loading pembimbing for new row:', error, xhr.responseText);
        });
}

function removeDetailRow(rowId) {
    $(`#row-${rowId}`).remove();
    renumberRows();
}

function renumberRows() {
    $('#detailsTableBody tr').each(function(index) {
        $(this).find('td:first').text(index + 1);
        $(this).attr('id', `row-${index + 1}`);
    });
    detailRowCount = $('#detailsTableBody tr').length;
}

function loadAnggotaAndPembimbing() {
    const dpcId = $('#dpc_id').val();
    
    console.log('loadAnggotaAndPembimbing called with dpcId:', dpcId);
    
    if (!dpcId) {
        console.log('No DPC selected, clearing dropdowns');
        $('.anggota-select, .pembimbing-select, .pembimbing-lama-select').html('<option value="">Pilih DPC terlebih dahulu</option>');
        return;
    }
    
    console.log('Loading anggota for DPC:', dpcId);
    // Load anggota
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    $.get(`{{ route('rekomposisi-upa.anggota-by-dpc') }}?dpc_id=${dpcId}`)
        .done(function(data) {
            console.log('Anggota data received:', data);
            let anggotaOptions = '<option value="">Pilih Anggota</option>';
            data.forEach(function(anggota) {
                anggotaOptions += `<option value="${anggota.id}">${anggota.nama_lengkap} (${anggota.nomor_identitas_anggota})</option>`;
            });
            $('.anggota-select').html(anggotaOptions);
            console.log('Anggota dropdown updated');
        })
        .fail(function(xhr, status, error) {
            console.error('Error loading anggota:', error, xhr.responseText);
        });
    
    console.log('Loading pembimbing for DPC:', dpcId);
    // Load pembimbing
    $.get(`{{ route('rekomposisi-upa.pembimbing-by-dpc') }}?dpc_id=${dpcId}`)
        .done(function(data) {
            console.log('Pembimbing data received:', data);
            let pembimbingOptions = '<option value="">Pilih Pembimbing</option>';
            data.forEach(function(pembimbing) {
                pembimbingOptions += `<option value="${pembimbing.id}">${pembimbing.nama_lengkap} (${pembimbing.nomor_identitas_anggota})</option>`;
            });
            $('.pembimbing-select, .pembimbing-lama-select').html(pembimbingOptions);
            console.log('Pembimbing dropdown updated');
        })
        .fail(function(xhr, status, error) {
            console.error('Error loading pembimbing:', error, xhr.responseText);
        });
}
</script>
@endpush
