<div class='row mb-2'>
    <div class="col-12 text-end">
        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#createContactModal">
            <i class="fa-solid fa-plus"></i> Add Contact
        </button>
    </div>
</div>

<div class="modal fade" id="createContactModal" tabindex="-1" aria-labelledby="createContactModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="createContactModalLabel">Contact Editor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <form id="formCreateContact" action="<?= base_url('/contacts/create'); ?>" method="POST">
                <div class="modal-body">
                    <input type='hidden' name='siteid' id='siteid' value='<?= $siteid; ?>' />

                    <div class="row mb-3 align-items-center">
                        <label for="firstname" class="col-sm-3 col-form-label">First Name <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="firstname" name="firstname" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="lastname" class="col-sm-3 col-form-label">Last Name </label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="lastname" name="lastname">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="initial" class="col-sm-3 col-form-label">Initial <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="initial" name="initial" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="title" class="col-sm-3 col-form-label">Title</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="title" name="title">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="birthdate" class="col-sm-3 col-form-label">Birthdate</label>
                        <div class="col-sm-9">
                            <input type="date" class="form-control form-control-sm" id="birthdate" name="birthdate">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="email_1" class="col-sm-3 col-form-label">Email 1 <span class="text-danger">*</span></label>
                        <div class="col-sm-9">
                            <input type="email" class="form-control form-control-sm" id="email_1" name="email_1" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="email_2" class="col-sm-3 col-form-label">Email 2</label>
                        <div class="col-sm-9">
                            <input type="email" class="form-control form-control-sm" id="email_2" name="email_2">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="phone" class="col-sm-3 col-form-label">Phone</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="phone" name="phone">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="mobile_1" class="col-sm-3 col-form-label">Mobile 1</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="mobile_1" name="mobile_1">
                        </div>
                    </div>
                    
                    <div class="row mb-3 align-items-center">
                        <label for="mobile_2" class="col-sm-3 col-form-label">Mobile 2</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control form-control-sm" id="mobile_2" name="mobile_2">
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer border-top-0">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Contact</button>
                </div>
            </form>

        </div>
    </div>
</div>

<input type='hidden' name='trainingid_delete' id='trainingid_delete' />
<div class="row g-3 align-items-end mb-3">
    <div class="col-12 col-md-4">
        <label for="trainingname" class="form-label border-start border-5 border-primary ps-1 mb-1">Participant Name</label>
        <select name="trainingname" id="trainingname" class="form-select form-select-sm select2 trainingname">
            <option value="">-- Choose one --</option>
            <?php 
                if(!empty($sitecontacts)) {
                    foreach ($sitecontacts as $data) {
                        $qcontactid = $data['contactid'];
                        $qcontactname = $data['firstname'] . " " . $data['lastname'];
                        
                        // Siapkan data tambahannya
                        $qcontactinitial = $data['initial'];
                        $qcontacttitle = $data['title'];
                        $qcontactemail = $data['email_1'];
                        
                        // Simpan di data-attribute
                        echo "<option value='$qcontactid' data-name='$qcontactname' data-initial='$qcontactinitial' data-title='$qcontacttitle' data-email='$qcontactemail'>$qcontactname</option>"; 
                    }
                }
            ?>
        </select>
    </div>
    <div class="col-12 col-md-3">
        <label for="trainingdate" class="form-label mb-1">Training Date</label>
        <input type="text" name="trainingdate" id="trainingdate" class="form-control form-control-sm trainingdate"
            placeholder="YYYY-MM-DD" />
    </div>

    <div class="col-12 col-md-2">
        <div class="form-check mb-md-1">
            <input class="form-check-input" type="checkbox" value="1" id="validatealltraining"
                name="validatealltraining" checked>
            <label class="form-check-label" for="validatealltraining" style="font-size: 0.875rem;">
                Validate All
            </label>
        </div>
    </div>
    <div class="col-12 col-md-3 d-grid">
        <button type="button" class="btn btn-sm btn-success" onclick="addTrainingRow();">Add</button>
    </div>
</div>
<hr />
<div class='table-responsive'>
    <table class='table table-bordered table-sm' id='training_table'>
        <thead>
            <tr>
                <th style='width:2%;'>No</th>
                <th style='width:8%;'>Initial</th>
                <th style='width:30%;'>Participant Name</th>
                <th style='width:15%;'>Title</th>
                <th style='width:25%;'>Email</th>
                <th style='width:15%;'>Training Date</th>
                <th style='width:11%;' class='text-center'>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            // Cek apakah ada data $traininguser
            if(isset($traininguser) && !empty($traininguser)): 
                $no = 1;
                foreach ($traininguser as $tu): 
            ?>
                <tr>
                    <td class="text-center"><?= $no++ ?></td>
                    <td><?= esc($tu['initial']) ?></td>
                    <td>
                        <?= esc($tu['firstname']) ?> <?= esc($tu['lastname']) ?>
                        <input type="hidden" name="trainingids[]" value="<?= esc($tu['contactid']) ?>">
                        <input type="hidden" name="trainingnames[]" value="<?= esc($tu['firstname']) ?> <?= esc($tu['lastname']) ?>">
                        <input type="hidden" name="trainingdates[]" value="<?= esc($tu['issued_date']) ?>">
                    </td>
                    <td><?= esc($tu['title']) ?></td>
                    <td><?= esc($tu['email_1']) ?></td>
                    <td><?= esc($tu['issued_date']) ?></td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteTrainingRow(this, '<?= esc($tu['contactid']) ?>')">Delete</button>
                    </td>
                </tr>
            <?php 
                endforeach; 
            endif; 
            ?>
        </tbody>
    </table>
</div>


<script>
function addTrainingRow() {
    var selectEl = $('#trainingname');
    var selectedOption = selectEl.find('option:selected');

    var contactid = selectEl.val();
    var trainingname = selectedOption.data('name');
    var trainingdate = $('#trainingdate').val();

    if (!contactid || !trainingdate) {
        alert("Participant Name atau Tanggal tidak boleh kosong.");
        return;
    }

    // Agar Tidak Double Check
    var exists = false;
    // Selektor ini tetap berfungsi dengan baik karena mencari awalan 'trainingids'
    $("input[name^='trainingids']").each(function(){
        if($(this).val() == contactid){
            exists = true;
        }
    });
    
    if(exists){
        alert("Participant sudah ditambahkan.");
        return;
    }

    var initial = selectedOption.data('initial') || '-';
    var title = selectedOption.data('title') || '-';
    var email = selectedOption.data('email') || '-';

    var rowIndex = $('#training_table tbody tr').length;

    var newRow = `
    <tr>
        <td class="text-center">${rowIndex + 1}</td>
        <td>${initial}</td>
        <td>
            ${trainingname}
            <input type="hidden" name="trainingids[]" value="${contactid}">
            <input type="hidden" name="trainingnames[]" value="${trainingname}">
            <input type="hidden" name="trainingdates[]" value="${trainingdate}">
        </td>
        <td>${title}</td>
        <td>${email}</td>
        <td>${trainingdate}</td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-danger" onclick="deleteTrainingRow(this)">Delete</button>
        </td>
    </tr>`;

    $("#training_table tbody").append(newRow);

    // reset input
    selectEl.val('').trigger('change');
}
function deleteTrainingRow(btn, contactid) {
    if(confirm('Apakah Anda yakin ingin menghapus data ini?')) {
        $(btn).closest('tr').remove();
        
        // Update nomor urut tabel otomatis untuk tampilan
        $('#training_table tbody tr').each(function(index) {
            $(this).find('td:first').text(index + 1);
        });
        
        // Memasukkan ID yang dihapus ke input hidden 'trainingid_delete'
        if (contactid > 0) {
            var d = $('#trainingid_delete');
            var currentVal = d.val();
            d.val(currentVal ? currentVal + ',' + contactid : contactid);
        }
    }
}
flatpickr(".trainingdate", { allowInput: true, dateFormat: "Y-m-d" });


// $('#formCreateContact').submit(function(e) {
//     // 1. Cegah form melakukan reload halaman bawaan HTML
//     e.preventDefault(); 
    
//     // 2. Ambil URL action dan data dari form
//     var url = $(this).attr('action');
//     var formData = $(this).serialize();

//     // 3. Kirim data ke controller menggunakan AJAX POST
//     $.ajax({
//         type: "POST",
//         url: url,
//         data: formData,
//         success: function(response) {
//             // Tutup modal dan bersihkan isian formnya
//             $('#createContactModal').modal('hide');
//             $('#formCreateContact')[0].reset();
            
//             // Tampilkan pesan sukses
//             alert('Contact berhasil ditambahkan!');
            
//             // --- INI BAGIAN REFRESH-NYA ---
//             var siteid = $('#siteid').val();
//             var current_actid = $('#current_actid').val();
            
//             // Siapkan format url untuk current_actid (sama seperti logika sebelumnya)
//             if (current_actid !== '' && current_actid !== undefined) {
//                 current_actid = '/' + current_actid;
//             } else {
//                 current_actid = '';
//             }

//             // Jalankan ulang $.get milikmu khusus untuk training_form
//             if(siteid !== '') {
//                 $.get("<?=base_url();?>/activities/getsitecontact/" + siteid + current_actid, function(data) {
//                     $('#training_form').html(data);
                    
//                     // Re-inisialisasi select2 agar tampilannya kembali rapi
//                     $('.select2').select2({
//                         theme: 'bootstrap-5',
//                         width: '100%'
//                     });
//                 });
//             }
//         },
//         error: function(xhr, status, error) {
//             alert('Terjadi kesalahan saat menyimpan data!');
//             console.error(xhr.responseText);
//         }
//     });
// });
$('#formCreateContact').submit(function(e) {
    // 1. Cegah form melakukan reload halaman bawaan HTML
    e.preventDefault(); 
    
    // 2. Ambil URL action dan data dari form
    var url = $(this).attr('action');
    var formData = $(this).serialize();

    // 3. Kirim data ke controller menggunakan AJAX POST
    $.ajax({
        type: "POST",
        url: url,
        data: formData,
        dataType: "json", // [UBAHAN 1] Beritahu AJAX bahwa kita mengharapkan balasan JSON
        success: function(response) {
            // Tutup modal dan bersihkan isian formnya
            $('#createContactModal').modal('hide');
            $('#formCreateContact')[0].reset();
            
            // Tampilkan pesan sukses
            alert('Contact berhasil ditambahkan!');
            
            // --- INI BAGIAN REFRESH-NYA (TIDAK ADA YANG DIUBAH) ---
            var siteid = $('#siteid').val();
            var current_actid = $('#current_actid').val();
            
            // Siapkan format url untuk current_actid (sama seperti logika sebelumnya)
            if (current_actid !== '' && current_actid !== undefined) {
                current_actid = '/' + current_actid;
            } else {
                current_actid = '';
            }

            // Jalankan ulang $.get milikmu khusus untuk training_form
            if(siteid !== '') {
                $.get("<?=base_url();?>/activities/getsitecontact/" + siteid + current_actid, function(data) {
                    $('#training_form').html(data);
                    
                    // Re-inisialisasi select2 agar tampilannya kembali rapi
                    $('.select2').select2({
                        theme: 'bootstrap-5',
                        width: '100%'
                    });
                });
            }
        },
        error: function(xhr, status, error) {
            // [UBAHAN 2] Tangkap error 400 dari validasi Controller
            if (xhr.status === 400 && xhr.responseJSON && xhr.responseJSON.errors) {
                var errorMessages = "Gagal menyimpan data karena:\n\n";
                
                // Looping semua error (misal firstname kosong, atau initial duplikat)
                $.each(xhr.responseJSON.errors, function(key, value) {
                    errorMessages += "• " + value + "\n";
                });
                
                alert(errorMessages);
            } else {
                // Error sistem lainnya (misal server down atau koneksi putus)
                alert('Terjadi kesalahan saat menyimpan data!');
                console.error(xhr.responseText);
            }
        }
    });
});
</script>