<?php
include_once "./class/testing.php";
include_once "./class/kriteria.php";
include_once "./class/kriteria_nilai.php";
include_once "./class/penilaian.php";
include_once "./class/mKNN.php";

$crud       = new testing();
$_kriteria  = new kriteria();
$_penilaian = new penilaian();
$_knn       = new mKNN();

$pesan        = "";
$tipe_pesan   = "";
$hasil_import = [];

$list_kriteria  = $_kriteria->tampil_kriteria();
$kriteria_angka = [];
foreach ($list_kriteria as $k) {
    if ($k['masukan'] == 3) $kriteria_angka[] = $k;
}

// =========================================================
// PROSES UPLOAD CSV
// =========================================================
if (isset($_FILES['file_csv']) && $_FILES['file_csv']['error'] == 0) {
    $ext = strtolower(pathinfo($_FILES['file_csv']['name'], PATHINFO_EXTENSION));
    if ($ext !== 'csv') {
        $pesan = "File harus berformat CSV (.csv)!";
        $tipe_pesan = "danger";
    } else {
        $nk_global = (int)($_POST['nk'] ?? 3);
        $handle    = fopen($_FILES['file_csv']['tmp_name'], 'r');
        fgetcsv($handle, 1000, ',');
        $berhasil = 0; $gagal = 0;

        while (($row = fgetcsv($handle, 1000, ',')) !== false) {
            $nama = trim($row[0] ?? '');
            if ($nama == '') continue;

            $data    = [];
            $data[0] = ''; $data[1] = $nama;
            $data[4] = date('Y-m-d H:i:s'); $data[6] = $nk_global;
            $arr_kriteria = []; $arr_nilai = []; $arr_masukan = [];

            foreach ($kriteria_angka as $idx => $krit) {
                $id_krit               = $krit['id_kriteria'];
                $arr_kriteria[]        = $id_krit;
                $arr_nilai[$id_krit]   = isset($row[$idx+1]) ? floatval(trim($row[$idx+1])) : 0;
                $arr_masukan[$id_krit] = 3;
            }
            $data[7] = $arr_kriteria; $data[8] = $arr_nilai; $data[9] = $arr_masukan;

            $id_testing = (int)$crud->tambah($data);
            if ($id_testing > 0) {
                $data_testing = [];
                foreach ($kriteria_angka as $krit)
                    $data_testing[$krit['id_kriteria']] = $arr_nilai[$krit['id_kriteria']];

                $hasil = $_knn->_knn($data_testing, $nk_global);
                $crud->simpan_hasil($id_testing, $hasil['hasil']);
                $berhasil++;
                $hasil_import[] = ['nama'=>$nama,'nilai'=>$arr_nilai,'hasil'=>$hasil['hasil'],
                    'data_terdekat'=>$hasil['data_terdekat'],'jumlah'=>$hasil['jumlah'],'status'=>'Berhasil'];
            } else {
                $gagal++;
                $hasil_import[] = ['nama'=>$nama,'nilai'=>$arr_nilai,'hasil'=>'-',
                    'data_terdekat'=>[],'jumlah'=>[],'status'=>'Gagal'];
            }
        }
        fclose($handle);
        $pesan      = "Import selesai: <b>$berhasil data berhasil</b>" . ($gagal > 0 ? ", <b>$gagal gagal</b>" : "") . ".";
        $tipe_pesan = ($gagal == 0) ? "success" : "warning";
    }
}
?>

<style>
.tbl-knn { width:100%; border-collapse:collapse; font-size:13px; margin-bottom:0; }
.tbl-knn th { background:#343a40; color:#fff; padding:8px 10px; text-align:center; border:1px solid #dee2e6; white-space:nowrap; }
.tbl-knn td { padding:7px 10px; border:1px solid #dee2e6; text-align:center; vertical-align:middle; }
.tbl-knn tr:nth-child(even) td { background:#f8f9fa; }
.tbl-klass { width:auto; border-collapse:collapse; font-size:13px; }
.tbl-klass th { background:#343a40; color:#fff; padding:7px 16px; border:1px solid #dee2e6; text-align:center; }
.tbl-klass td { padding:6px 16px; border:1px solid #dee2e6; text-align:center; }
</style>

<div class="row">
<div class="col-md-12">

<div class="card">
    <div class="card-header"><h4 class="m-0">Import Data Testing (CSV)</h4></div>
    <div class="card-body">
        <?php if ($pesan): ?>
        <div class="alert alert-<?= $tipe_pesan ?> alert-dismissable">
            <button type="button" class="close" data-dismiss="alert">&times;</button><?= $pesan ?>
        </div>
        <?php endif; ?>

        <div class="alert alert-info">
            <strong>Format CSV:</strong> Baris pertama = header, kolom berikutnya = data.<br>
            Urutan: <code>Nama Produk, <?= implode(', ', array_column($kriteria_angka, 'kriteria')) ?></code><br><br>
            <pre style="background:#fff;padding:8px;border-radius:4px;font-size:12px;margin:0">Nama,<?= implode(',', array_column($kriteria_angka, 'kriteria')) ?>

Beras Pulen 5kg,65,70,81.3
Minyak Curah 1L,10,14,16.7</pre>
        </div>

        <form method="POST" enctype="multipart/form-data">
            <div class="form-group row">
                <label class="col-sm-3 col-form-label"><b>Nilai K</b></label>
                <div class="col-sm-3"><input type="number" name="nk" class="form-control" value="3" min="1" required></div>
            </div>
            <div class="form-group row">
                <label class="col-sm-3 col-form-label"><b>Pilih File CSV</b></label>
                <div class="col-sm-5">
                    <input type="file" name="file_csv" class="form-control-file" accept=".csv" required>
                    <small class="text-muted">Hanya file .csv</small>
                </div>
            </div>
            <div class="form-group row">
                <div class="col-sm-8 offset-sm-3">
                    <button type="submit" class="btn btn-primary">Upload & Proses Sekarang</button>
                    <a href="?p=testing" class="btn btn-secondary ml-2">Kembali</a>
                </div>
            </div>
        </form>
    </div>
</div>

<?php if (!empty($hasil_import)): ?>

<?php foreach ($hasil_import as $no => $h): ?>
<?php $warna = (stripos($h['hasil'], 'tidak') !== false) ? 'danger' : 'success'; ?>
<div class="card mt-3">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="m-0">Data Uji <?= $no+1 ?>: <b><?= htmlspecialchars($h['nama']) ?></b></h5>
        <span class="badge badge-<?= $warna ?>" style="font-size:14px;padding:6px 14px;">
            Hasil KNN: <?= htmlspecialchars($h['hasil']) ?>
        </span>
    </div>
    <div class="card-body">

        <!-- Nilai input -->
        <p class="mb-2"><strong>Nilai yang Diinput:</strong></p>
        <table class="tbl-knn mb-3" style="width:auto;">
            <thead>
                <tr>
                    <?php foreach ($kriteria_angka as $krit): ?>
                    <th><?= htmlspecialchars($krit['kriteria']) ?></th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <?php foreach ($kriteria_angka as $krit): ?>
                    <td><?= $h['nilai'][$krit['id_kriteria']] ?></td>
                    <?php endforeach; ?>
                </tr>
            </tbody>
        </table>

        <!-- Tabel tetangga terdekat -->
        <p class="mb-1"><strong>Hasil Perhitungan — <?= count($h['data_terdekat']) ?> Tetangga Terdekat (K=<?= count($h['data_terdekat']) ?>):</strong></p>
        <div class="table-responsive mb-3">
        <table class="tbl-knn">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Kode Data Latih</th>
                    <?php foreach ($kriteria_angka as $krit): ?>
                    <th><?= htmlspecialchars($krit['kriteria']) ?></th>
                    <?php endforeach; ?>
                    <th>Klasifikasi</th>
                    <th>Jarak (Euclidean)</th>
                </tr>
            </thead>
            <tbody>
                <?php $nb=1; foreach ($h['data_terdekat'] as $kode_latih => $dt): ?>
                <?php $wk = (stripos($dt['hasil'], 'tidak') !== false) ? 'danger' : 'success'; ?>
                <tr>
                    <td><?= $nb++ ?></td>
                    <td><?= htmlspecialchars($kode_latih) ?></td>
                    <?php foreach ($kriteria_angka as $krit): ?>
                    <td><?= isset($dt['nilai_asli'][$krit['id_kriteria']]) ? $dt['nilai_asli'][$krit['id_kriteria']] : '-' ?></td>
                    <?php endforeach; ?>
                    <td><span class="badge badge-<?= $wk ?>"><?= htmlspecialchars($dt['hasil']) ?></span></td>
                    <td><?= number_format($dt['jarak'], 15) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>

        <!-- Total kelas -->
        <p class="mb-1"><strong>Total Setiap Kelas:</strong></p>
        <table class="tbl-klass">
            <thead><tr><th>Kelas</th><th>Total</th></tr></thead>
            <tbody>
                <?php foreach ($h['jumlah'] as $kls => $total): ?>
                <tr><td><?= htmlspecialchars($kls) ?></td><td><?= $total ?></td></tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    </div>
</div>
<?php endforeach; ?>

<!-- Tombol bawah -->
<div class="card mt-3">
    <div class="card-body">
        <a href="?p=testing" class="btn btn-primary">Lihat Semua Data Testing</a>
        <a href="?p=hasil" class="btn btn-success ml-2">Lihat Halaman Hasil</a>
        <button onclick="downloadExcel()" class="btn btn-warning ml-2">Download Hasil ke Excel</button>
    </div>
</div>

<script>
function downloadExcel() {
    var kriteriaAngka = <?= json_encode(array_map(function($k){
        return ['id'=>(string)$k['id_kriteria'],'nama'=>$k['kriteria']];
    }, $kriteria_angka)) ?>;
    var hasilImport = <?= json_encode($hasil_import) ?>;

    // Buat XML Spreadsheet (format .xls yang dibaca Excel dengan kolom rapi)
    var xml = '<' + '?xml version="1.0" encoding="UTF-8"?' + '>\n';
    xml += '<' + '?mso-application progid="Excel.Sheet"?' + '>\n';
    xml += '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"\n';
    xml += ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"\n';
    xml += ' xmlns:x="urn:schemas-microsoft-com:office:excel">\n';

    // Style
    xml += '<Styles>\n';
    xml += '<Style ss:ID="header"><Font ss:Bold="1"/><Interior ss:Color="#D9D9D9" ss:Pattern="Solid"/><Borders><Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/></Borders></Style>\n';
    xml += '<Style ss:ID="judul"><Font ss:Bold="1" ss:Size="11"/></Style>\n';
    xml += '<Style ss:ID="data"><Borders><Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/><Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/></Borders></Style>\n';
    xml += '<Style ss:ID="tebal"><Font ss:Bold="1"/></Style>\n';
    xml += '</Styles>\n';

    xml += '<Worksheet ss:Name="Hasil KNN">\n<Table>\n';

    // Lebar kolom
    xml += '<Column ss:Width="30"/>\n'; // No
    xml += '<Column ss:Width="100"/>\n'; // Kode
    kriteriaAngka.forEach(function(){ xml += '<Column ss:Width="110"/>\n'; });
    xml += '<Column ss:Width="90"/>\n'; // Klasifikasi
    xml += '<Column ss:Width="160"/>\n'; // Jarak

    function cell(val, styleId, type) {
        type = type || 'String';
        styleId = styleId || '';
        var s = styleId ? ' ss:StyleID="'+styleId+'"' : '';
        var v = String(val === null || val === undefined ? '' : val)
                    .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
        return '<Cell'+s+'><Data ss:Type="'+type+'">'+v+'</Data></Cell>';
    }
    function emptyRow(n) {
        var r = '<Row>';
        for(var i=0;i<n;i++) r += '<Cell><Data ss:Type="String"></Data></Cell>';
        return r + '</Row>\n';
    }

    hasilImport.forEach(function(h, idx) {
        // Judul data uji
        xml += '<Row>' + cell('DATA UJI '+(idx+1)+': '+h.nama,'judul') + '</Row>\n';

        // Nilai input — header
        var hdrInput = '<Row>' + cell('','header');
        kriteriaAngka.forEach(function(k){ hdrInput += cell(k.nama,'header'); });
        hdrInput += '</Row>\n';
        xml += hdrInput;

        // Nilai input — isi
        var rowInput = '<Row>' + cell('Nilai Diinput','tebal');
        kriteriaAngka.forEach(function(k){
            var v = h.nilai[k.id] !== undefined ? h.nilai[k.id] : '-';
            xml += ''; // placeholder
            rowInput += cell(v,'data','Number');
        });
        rowInput += '</Row>\n';
        xml += rowInput;

        xml += emptyRow(1);

        // Header tabel tetangga
        var hdr = '<Row>';
        hdr += cell('No','header');
        hdr += cell('Kode Data Latih','header');
        kriteriaAngka.forEach(function(k){ hdr += cell(k.nama,'header'); });
        hdr += cell('Klasifikasi','header');
        hdr += cell('Jarak (Euclidean)','header');
        hdr += '</Row>\n';
        xml += hdr;

        // Baris tetangga
        var nb = 1;
        var terdekat = h.data_terdekat;
        Object.keys(terdekat).forEach(function(kode) {
            var dt = terdekat[kode];
            var row = '<Row>';
            row += cell(nb++,'data','Number');
            row += cell(kode,'data');
            kriteriaAngka.forEach(function(k){
                var v = dt.nilai_asli && dt.nilai_asli[k.id] !== undefined ? dt.nilai_asli[k.id] : '-';
                row += cell(v,'data','Number');
            });
            row += cell(dt.hasil,'data');
            row += cell(dt.jarak,'data','Number');
            row += '</Row>\n';
            xml += row;
        });

        xml += emptyRow(1);

        // Total kelas
        xml += '<Row>' + cell('Total Setiap Kelas','tebal') + '</Row>\n';
        xml += '<Row>' + cell('Kelas','header') + cell('Total','header') + '</Row>\n';
        Object.keys(h.jumlah).forEach(function(kls){
            xml += '<Row>' + cell(kls,'data') + cell(h.jumlah[kls],'data','Number') + '</Row>\n';
        });

        xml += emptyRow(1);

        // Kesimpulan
        xml += '<Row>' + cell('Kesimpulan','tebal') + cell(h.nama + ' -> ' + h.hasil,'data') + '</Row>\n';
        xml += emptyRow(2);
    });

    xml += '</Table>\n</Worksheet>\n</Workbook>';

    var blob = new Blob([xml], {type:'application/vnd.ms-excel;charset=utf-8;'});
    var url  = URL.createObjectURL(blob);
    var a    = document.createElement('a');
    a.href = url; a.download = 'hasil_klasifikasi_knn.xls';
    document.body.appendChild(a); a.click();
    document.body.removeChild(a); URL.revokeObjectURL(url);
}
</script>

<?php endif; ?>

</div>
</div>