<?php
include '../../config/conn.php';

/* FUNGSI VALIDASI */
function validasiDataSantri($conn, $id_santri) {
    $hasilValidasi = array();
    $query = mysqli_query($conn, "SELECT * FROM santri WHERE id_santri='$id_santri'");
    $dataSantri = mysqli_fetch_assoc($query);
    
    if (!$dataSantri) return false;

    // Definisikan semua field dan aturan validasinya
    $fieldRules = [
        // Data Pribadi
        'id_santri' => ['required' => true, 'type' => 'string'],
        'nama' => ['required' => true, 'type' => 'string', 'min_length' => 3],
        'alamat' => ['required' => true, 'type' => 'string', 'min_length' => 10],
        'jenkel' => ['required' => true, 'type' => 'enum', 'values' => ['l', 'p']],
        'tempat_lahir' => ['required' => true, 'type' => 'string'],
        'tanggal_lahir' => ['required' => true, 'type' => 'date'],
        'tanggal_masuk' => ['required' => true, 'type' => 'date'],
        'statuus' => ['required' => true, 'type' => 'number'],
        'status_aktif' => ['required' => true, 'type' => 'number'],
        'nisn' => ['required' => true, 'type' => 'number', 'length' => 10],
        'prog_kelas' => ['required' => true, 'type' => 'number'],
        
        // Data Keluarga
        'nama_ayah' => ['required' => true, 'type' => 'string'],
        'nama_ibu' => ['required' => true, 'type' => 'string'],
        'nik_ayah' => ['required' => true, 'type' => 'number', 'length' => 16],
        'nik_ibu' => ['required' => true, 'type' => 'number', 'length' => 16],
        'nik_santri' => ['required' => true, 'type' => 'number', 'length' => 16],
        'no_kk' => ['required' => true, 'type' => 'number', 'length' => 16],
        'no_hp' => ['required' => true, 'type' => 'number', 'min_length' => 10],
        
        // Data Orang Tua
        'status_ayah' => ['required' => false, 'type' => 'string'],
        'status_ibu' => ['required' => false, 'type' => 'string'],
        'tpt_lahir_ayah' => ['required' => false, 'type' => 'string'],
        'tpt_lahir_ibu' => ['required' => false, 'type' => 'string'],
        'tanggal_lahir_ayah' => ['required' => false, 'type' => 'date'],
        'tanggal_lahir_ibu' => ['required' => false, 'type' => 'date'],
        'pend_ayah' => ['required' => false, 'type' => 'string'],
        'pend_ibu' => ['required' => false, 'type' => 'string'],
        'peng_ayah' => ['required' => false, 'type' => 'string'],
        'peng_ibu' => ['required' => false, 'type' => 'string'],
        'pek_ayah' => ['required' => false, 'type' => 'string'],
        'pek_ibu' => ['required' => false, 'type' => 'string'],
        
        // Data Keuangan
        'biaya_spp' => ['required' => true, 'type' => 'number'],
        'biaya_dam' => ['required' => true, 'type' => 'number'],
        'biaya_dut' => ['required' => true, 'type' => 'number'],
        'status_emoney' => ['required' => false, 'type' => 'string'],
        
        // Data Lainnya
        'no_kip' => ['required' => false, 'type' => 'string'],
        'id_junio' => ['required' => false, 'type' => 'number'],
        'kelas_sekarang' => ['required' => true, 'type' => 'number'],
        'kelasawalmasuk' => ['required' => true, 'type' => 'number'],
        'baruataupindahan' => ['required' => true, 'type' => 'number'],
        'alasankeluar' => ['required' => false, 'type' => 'string'],
        'tgl_keluar' => ['required' => false, 'type' => 'date'],
        'cttn_khusus' => ['required' => false, 'type' => 'string'],
        'riwayat_sakit' => ['required' => false, 'type' => 'string']
    ];

    foreach ($fieldRules as $field => $rules) {
        // Ambil nilai asli dari database
        $rawValue = isset($dataSantri[$field]) ? $dataSantri[$field] : null;
        
        // Default: gunakan nilai asli
        $displayValue = $rawValue;
    
        // Konversi nilai berdasarkan field
        switch ($field) {
            case 'status_aktif':
                $converted = statusaktif($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;
                
            case 'jenkel':
                $converted = jeniskelamin($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;
                
            case 'prog_kelas':
                $converted = namajurusan($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;

            case 'kelas_sekarang':
                $converted = namakelas($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;

            case 'kelasawalmasuk':
                $converted = namakelas($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;

            case 'baruataupindahan':
                $converted = baruataupindahan($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;

            case 'statuus':
                $converted = statuus($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break;
                
            case 'status_ayah':
            case 'status_ibu':
            case 'pend_ayah':
            case 'pend_ibu':
            case 'peng_ayah':
            case 'peng_ibu':
            case 'pek_ayah':
            case 'pek_ibu':
            
                $converted = statusortu($rawValue);
                $displayValue = ($converted !== 'Tidak Diketahui') ? $converted : $rawValue;
                break; 
           
                
            // Tambahkan case lain sesuai kebutuhan
            default:
                // Untuk field yang tidak memiliki konversi, tetap gunakan nilai asli
                $displayValue = $rawValue;
        }
    
        // Validasi menggunakan nilai asli (raw value)
        $validation = validateField($rawValue, $rules);
        
        $hasilValidasi[$field] = [
            'status' => $validation['status'],
            'nilai' => $displayValue,  // Nilai yang akan ditampilkan (sudah dikonversi atau asli)
            'nilai_raw' => $rawValue,  // Nilai asli dari database
            'keterangan' => $validation['message'],
            'wajib' => $rules['required']
        ];
    }
    
    return $hasilValidasi;
}

function validateField($value, $rules) {
    if ($rules['required'] && (is_null($value) || $value === '')) {
        return ['status' => 'Belum diisi', 'message' => 'Wajib diisi'];
    }
    
    if (!$rules['required'] && (is_null($value) || $value === '')) {
        return ['status' => 'Tidak wajib', 'message' => 'Field opsional'];
    }
    
    switch ($rules['type']) {
        case 'number':
            if (!is_numeric($value)) return ['status' => 'Tidak valid', 'message' => 'Harus angka'];
            if (isset($rules['length']) && strlen($value) != $rules['length']) 
                return ['status' => 'Tidak valid', 'message' => 'Harus '.$rules['length'].' digit'];
            if (isset($rules['min_length']) && strlen($value) < $rules['min_length']) 
                return ['status' => 'Tidak valid', 'message' => 'Min. '.$rules['min_length'].' digit'];
            break;
            
        case 'date':
            if (strtotime($value) === false) 
                return ['status' => 'Tidak valid', 'message' => 'Format tanggal salah'];
            break;
            
        case 'enum':
            if (!in_array($value, $rules['values'])) 
                return ['status' => 'Tidak valid', 'message' => 'Nilai tidak sesuai'];
            break;
            
        case 'string':
            if (isset($rules['min_length']) && strlen($value) < $rules['min_length']) 
                return ['status' => 'Tidak valid', 'message' => 'Min. '.$rules['min_length'].' karakter'];
            break;
    }
    
    return ['status' => 'Valid', 'message' => ''];
}

/* TAMPILAN VALIDASI */
function tampilkanHasilValidasi($conn, $id_santri) {
    $hasilValidasi = validasiDataSantri($conn, $id_santri);
    
    if ($hasilValidasi === false) {
        echo '<div class="alert alert-danger">Data santri tidak ditemukan</div>';
        return;
    }
    
    $query = mysqli_query($conn, "SELECT * FROM santri WHERE id_santri='$id_santri'");
    $dataSantri = mysqli_fetch_assoc($query);
    
    echo '<div class="x_panel">
            <div class="x_title">
                <h2><i class="fa fa-check-circle"></i> Validasi Data Santri: '.htmlspecialchars($dataSantri['nama']).'</h2>
                <div class="clearfix"></div>
            </div>
            <div class="x_content">
                <div class="row">
                    <div class="col-md-6">
                        <div class="panel panel-info">
                            <div class="panel-heading">Informasi Santri</div>
                            <div class="panel-body">
                                <table class="table table-condensed">
                                    <tr><th width="30%">ID Santri</th><td>'.htmlspecialchars($dataSantri['id_santri']).'</td></tr>
                                    <tr><th>Nama</th><td>'.htmlspecialchars($dataSantri['nama']).'</td></tr>
                                    <tr><th>Kelas</th><td>'.namakelas($dataSantri['kelas_sekarang']).'</td></tr>
                                    <tr><th>Status</th><td>'.statusaktif($dataSantri['status_aktif']).'</td></tr>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="panel panel-info">
                            <div class="panel-heading">Ringkasan Validasi</div>
                            <div class="panel-body">';
    
    // Hitung statistik
    $total = count($hasilValidasi);
    $valid = 0; $invalid = 0; $empty = 0; $optional = 0;
    
    foreach ($hasilValidasi as $field) {
        if ($field['status'] === 'Valid') $valid++;
        elseif ($field['status'] === 'Tidak valid') $invalid++;
        elseif ($field['status'] === 'Belum diisi') $empty++;
        else $optional++;
    }
    
    echo '<div class="progress" style="height: 25px;">
            <div class="progress-bar progress-bar-success" style="width: '.($valid/$total*100).'%" title="Valid: '.$valid.'">
                '.round(($valid/$total)*100).'%
            </div>
            <div class="progress-bar progress-bar-warning" style="width: '.($invalid/$total*100).'%" title="Tidak valid: '.$invalid.'">
                '.round(($invalid/$total)*100).'%
            </div>
            <div class="progress-bar progress-bar-danger" style="width: '.($empty/$total*100).'%" title="Belum diisi: '.$empty.'">
                '.round(($empty/$total)*100).'%
            </div>
            <div class="progress-bar progress-bar-info" style="width: '.($optional/$total*100).'%" title="Opsional: '.$optional.'">
                '.round(($optional/$total)*100).'%
            </div>
          </div>
          <div class="row" style="margin-top:10px;">
            <div class="col-md-3"><span class="label label-success"><i class="fa fa-check"></i> Valid</span> '.$valid.'</div>
            <div class="col-md-3"><span class="label label-warning"><i class="fa fa-exclamation"></i> Invalid</span> '.$invalid.'</div>
            <div class="col-md-3"><span class="label label-danger"><i class="fa fa-times"></i> Kosong</span> '.$empty.'</div>
            <div class="col-md-3"><span class="label label-info"><i class="fa fa-info"></i> Opsional</span> '.$optional.'</div>
          </div>
          </div></div></div></div>';
    
    // Tampilkan detail validasi
    echo '<div class="row"><div class="col-md-12"><div class="panel panel-default">
          <div class="panel-heading"><h3 class="panel-title"><i class="fa fa-list"></i> Detail Validasi</h3></div>
          <div class="panel-body"><div class="table-responsive">
          <table class="table table-bordered table-striped table-hover">
          <thead><tr>
            <th width="20%">Field</th>
            <th width="10%">Status</th>
            <th width="30%">Nilai</th>
            <th width="40%">Keterangan</th>
          </tr></thead><tbody>';
    
    $kategori = [
        'Data Pribadi' => ['id_santri', 'nama', 'alamat', 'jenkel', 'tempat_lahir', 'tanggal_lahir', 'tanggal_masuk', 'statuus', 'status_aktif', 'nisn'],
        'Data Pendidikan' => ['prog_kelas', 'kelas_sekarang', 'kelasawalmasuk', 'baruataupindahan'],
        'Data Keluarga' => ['nama_ayah', 'nama_ibu', 'nik_ayah', 'nik_ibu', 'nik_santri', 'no_kk', 'no_hp'],
        'Data Orang Tua' => ['status_ayah', 'status_ibu', 'tpt_lahir_ayah', 'tpt_lahir_ibu', 'tanggal_lahir_ayah', 'tanggal_lahir_ibu', 'pend_ayah', 'pend_ibu',
                            'peng_ayah','peng_ibu','pek_ayah','pek_ibu',],
        'Data Keuangan' => ['biaya_spp', 'biaya_dam', 'biaya_dut', 'status_emoney'],
        'Data Lainnya' => ['no_kip', 'id_junio', 'alasankeluar', 'tgl_keluar', 'cttn_khusus', 'riwayat_sakit']
    ];
    
    foreach ($kategori as $namaKategori => $fields) {
        echo '<tr class="active"><td colspan="4"><strong><i class="fa fa-folder-open"></i> '.$namaKategori.'</strong></td></tr>';
        
        foreach ($fields as $field) {
            if (!isset($hasilValidasi[$field])) continue;
            
            $data = $hasilValidasi[$field];
            $statusClass = $data['status'] === 'Valid' ? 'success' : 
               ($data['status'] === 'Tidak valid' ? 'warning' :
               ($data['status'] === 'Belum diisi' ? 'danger' : 'info'));
            
            $icon = $data['status'] === 'Valid' ? 'fa-check' : 
                   ($data['status'] === 'Tidak valid' ? 'fa-exclamation' : 
                   ($data['status'] === 'Belum diisi' ? 'fa-times' : 'fa-info-circle'));
            
            echo '<tr>
                    <td>'.ucwords(str_replace('_', ' ', $field)).'</td>
                    <td><span class="label label-'.$statusClass.'"><i class="fa '.$icon.'"></i> '.$data['status'].'</span></td>
                    <td>'.htmlspecialchars($data['nilai']).'</td>
                    <td>'.($data['wajib'] ? '<span class="label label-primary">Wajib</span> ' : '').htmlspecialchars($data['keterangan']).'</td>
                  </tr>';
        }
    }
    
    echo '</tbody></table></div></div></div></div></div></div></div>';
}

function tampilkanRingkasanValidasi($conn, $statusAktif) {
    if (empty($statusAktif)) {
        $where = "WHERE status_aktif='1'";
        
    } elseif ($statusAktif === 'all') {
        $where = "";
    } else {
        $where = "WHERE status_aktif='$statusAktif'";
    }
       $query = mysqli_query($conn, "SELECT id_santri, nama, status_aktif FROM santri $where ORDER BY nama");
    $queryStatus = mysqli_query($conn, "SELECT * FROM status_aktif ORDER BY id");
    
    echo '<div class="x_panel">
            <div class="x_title">
                <h2><i class="fa fa-check-square"></i> Ringkasan Validasi Data Santri</h2>
                <div class="clearfix"></div>
                <form method="post" class="form-inline">
                    <div class="form-group">
                        <label>Filter Status: </label>
                        <select name="status_filter" class="form-control" onchange="this.form.submit()">
                            <option value="all">-- Semua Status --</option>';
    
    while ($status = mysqli_fetch_assoc($queryStatus)) {
        $selected = ($statusAktif == $status['id']) ? 'selected' : '';
        echo '<option value="'.$status['id'].'" '.$selected.'>'.$status['nama'].'</option>';
    }
    
    echo '</select>
                    </div>
                </form>
            </div>
            <div class="x_content">
                <table class="table table-bordered table-striped table-hover" id="datatable-validasi">
                    <thead>
                        <tr>
                            <th width="5%">No</th>
                            <th width="15%">ID Santri</th>
                            <th width="25%">Nama</th>
                            <th width="15%">Status</th>
                            <th width="25%">Kelengkapan</th>
                            <th width="15%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>';
    
    $no = 0;
    while ($row = mysqli_fetch_assoc($query)) {
        $no++;
        $hasilValidasi = validasiDataSantri($conn, $row['id_santri']);
        if ($hasilValidasi === false) continue;
        
        $total = count($hasilValidasi);
        $valid = 0;
        foreach ($hasilValidasi as $field) {
            if ($field['status'] === 'Valid') $valid++;
        }
        $persentase = round(($valid / $total) * 100, 0);
        
        $warna = ($persentase >= 80) ? 'success' : (($persentase >= 50) ? 'warning' : 'danger');
        
        echo '<tr>
                <td>'.$no.'</td>
                <td>'.$row['id_santri'].'</td>
                <td>'.$row['nama'].'</td>
                <td>'.statusaktif($row['status_aktif']).'</td>
                <td>
                    <div class="progress" style="height: 20px; margin-bottom:5px;">
                        <div class="progress-bar progress-bar-'.$warna.'" style="width: '.$persentase.'%;">
                            '.$persentase.'%
                        </div>
                    </div>
                    <small>'.$valid.' dari '.$total.' field valid</small>
                </td>
                <td>
                    <a href="?module=cek-data-santri&aksi=validasi&id='.$row['id_santri'].'" class="btn btn-info btn-xs">
                        <i class="fa fa-search"></i> Detail
                    </a>
                    <a href="?module=santri&aksi=edit&id='.$row['id_santri'].'" class="btn btn-warning btn-xs">
                        <i class="fa fa-edit"></i> Edit
                    </a>
                </td>
              </tr>';
    }
    
    echo '</tbody></table></div></div>';
}



/* INTEGRASI DENGAN SISTEM */
if ($_GET['aksi'] == '') { ?>
    <div class="row">
        <div class="col-md-12">
            <ul class="nav nav-tabs">
                <li class="active"><a href="#data-santri" data-toggle="tab"><i class="fa fa-list"></i> Data Santri</a></li>
                <li><a href="#validasi-data" data-toggle="tab"><i class="fa fa-check-circle"></i> Validasi Data</a></li>
            </ul>
            
            <div class="tab-content">
            <div class="tab-pane" id="validasi-data">
                    <!-- Kode asli tampilan data santri -->
                    <?php //include 'data_santri_original.php'; ?>
                </div>
                
                
                <div class="tab-pane active" id="data-santri">
                    <?php 
                    $statusAktif = isset($_POST['status_filter']) ? $_POST['status_filter'] : null;
                    tampilkanRingkasanValidasi($conn, $statusAktif); 
                    ?>
                </div>
            </div>
        </div>
    </div>
<?php } elseif ($_GET['aksi'] == 'validasi' && isset($_GET['id'])) { ?>
    <div class="col" role="main">
        <div class="">
            <div class="clearfix"></div>
            <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <a href="?module=cek-data-santri" class="btn btn-default btn-sm">
                        <i class="fa fa-arrow-left"></i> Kembali ke Daftar
                    </a>
                    <?php tampilkanHasilValidasi($conn, $_GET['id']); ?>
                </div>
            </div>
        </div>
    </div>
<?php } ?>

<!-- CSS Tambahan -->
<style>
    .label-success { background-color: #5cb85c; }
    .label-danger { background-color: #d9534f; }
    .label-warning { background-color: #f0ad4e; }
    .label-info { background-color: #5bc0de; }
    .label-primary { background-color: #337ab7; }
    .progress-bar-success { background-color: #5cb85c; }
    .progress-bar-danger { background-color: #d9534f; }
    .progress-bar-warning { background-color: #f0ad4e; }
    .progress-bar-info { background-color: #5bc0de; }
    .progress { margin-bottom: 10px; background-color: #f5f5f5; }
    .nav-tabs { margin-bottom: 20px; }
    .table-hover tbody tr:hover { background-color: #f5f5f5; }
</style>

<!-- JavaScript untuk DataTable -->
<script>
    $(document).ready(function() {
        $('#datatable-validasi').DataTable({
            responsive: true,
            "pageLength": 25,
            "order": [[2, "asc"]],
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Indonesian.json"
            }
        });
    });
</script>

<script>
$(document).ready(function() {
    console.log('Tab Content:', $('#validasi-data').length);
    if ($('#validasi-data').length === 0) {
        alert('Elemen tab validasi tidak ditemukan!');
    }
});
</script>