<?php
require_once "koneksi.php";
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =========================
   PREVIEW
========================= */
if(isset($_POST['preview'])){

    if($_FILES['file']['error'] != 0){
        die("Upload gagal!");
    }

    $file = $_FILES['file']['tmp_name'];
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    if(!in_array($ext, ['xls','xlsx'])){
        die("File harus Excel!");
    }

    $spreadsheet = IOFactory::load($file);
    $rows = $spreadsheet->getActiveSheet()->toArray(null,false,false,false);

    $previewData = [];

    foreach($rows as $key => $row){

        if($key == 0) continue; // skip header
        if(empty($row[1])) continue;

        $previewData[] = [
            'nomor' => trim($row[0] ?? ''),
            'nama'  => trim($row[1] ?? ''),
            'kelas' => trim($row[2] ?? ''),
            'ptn'   => trim($row[3] ?? ''),
            'prodi' => trim($row[4] ?? ''),
            'kip'   => trim($row[5] ?? '')
        ];
    }

    $_SESSION['preview_snbp'] = $previewData;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Import SNBP</title>
<link rel="stylesheet" href="adminlte/dist/css/adminlte.min.css">
</head>
<body class="p-4">

<div class="card">
<div class="card-header bg-primary text-white">
Import Data SNBP
</div>

<div class="card-body">

<form method="post" enctype="multipart/form-data">
<input type="file" name="file" required class="form-control mb-2">
<button name="preview" class="btn btn-info">Preview</button>
</form>

<hr>

<?php if(!empty($_SESSION['preview_snbp'])): ?>
<form method="post">

<table class="table table-bordered table-sm">
<thead>
<tr>
<th>Nama</th>
<th>Kelas</th>
<th>PTN</th>
<th>Prodi</th>
<th>KIP</th>
</tr>
</thead>

<tbody>
<?php foreach($_SESSION['preview_snbp'] as $row): ?>
<tr>
<td><?= htmlspecialchars($row['nama']) ?></td>
<td><?= htmlspecialchars($row['kelas']) ?></td>
<td><?= htmlspecialchars($row['ptn']) ?></td>
<td><?= htmlspecialchars($row['prodi']) ?></td>
<td><?= htmlspecialchars($row['kip']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<button name="simpan" class="btn btn-success">
Simpan ke Database
</button>

</form>
<?php endif; ?>

<?php
/* =========================
   INSERT
========================= */
if(isset($_POST['simpan']) && !empty($_SESSION['preview_snbp'])){

    $jumlah = 0;

    foreach($_SESSION['preview_snbp'] as $data){

        if(empty($data['nama'])) continue;

        // CEK DUPLIKAT (nama + ptn)
        $cek = $koneksi->prepare("
            SELECT id FROM snbp 
            WHERE nama=? AND ptn=?
        ");
        $cek->bind_param("ss", $data['nama'], $data['ptn']);
        $cek->execute();
        $result = $cek->get_result();

        if($result->num_rows == 0){

            $insert = $koneksi->prepare("
                INSERT INTO snbp
                (nomor,nama,kelas,ptn,prodi,kip)
                VALUES (?,?,?,?,?,?)
            ");

            $insert->bind_param(
                "ssssss",
                $data['nomor'],
                $data['nama'],
                $data['kelas'],
                $data['ptn'],
                $data['prodi'],
                $data['kip']
            );

            if(!$insert->execute()){
                echo "Error: ".$insert->error;
                exit;
            }

            $jumlah++;
        }
    }

    unset($_SESSION['preview_snbp']);

    echo "<script>
    alert('Import SNBP berhasil! $jumlah data masuk.');
    window.location='dashboard_adm_infokarirdanbeasiswa.php';
    </script>";
}
?>

</div>
</div>

</body>
</html>