<?php
session_start();
require_once '../config.php';

/* ================= DEBUG MODE ================= */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/* ================= CEK LOGIN ================= */
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Akses ditolak");
}

/* ================= PROSES IMPORT ================= */
if (isset($_POST['import'])) {

    if (!isset($_FILES['file_csv']) || $_FILES['file_csv']['error'] != 0) {
        die("File tidak terkirim dari form");
    }

    $file = $_FILES['file_csv']['tmp_name'];

    if (!is_uploaded_file($file)) {
        die("Upload gagal");
    }

    echo "<pre>MEMULAI IMPORT...\n";

    /* ===== deteksi separator ===== */
    $sample = file_get_contents($file);
    $separator = (substr_count($sample, ";") > substr_count($sample, ",")) ? ";" : ",";

    $handle = fopen($file, "r");
    if (!$handle) die("File tidak bisa dibuka");

    $baris = 0;
    $berhasil = 0;
    $gagal = 0;

    $pdo->beginTransaction();

    while (($data = fgetcsv($handle, 2000, $separator)) !== FALSE) {

        $baris++;

        /* lewati header */
        if ($baris == 1) continue;

        /* lewati baris kosong */
        if (empty(trim($data[0]))) continue;

        try {

            /* ================= FORMAT TANGGAL ================= */
            $tgl = trim($data[2]);
            $tgl = str_replace('/', '-', $tgl);
            $parts = explode('-', $tgl);

            if (count($parts) == 3) {
                if (strlen($parts[0]) == 4) {
                    $tgl_final = $tgl;
                } else {
                    $tgl_final = $parts[2] . '-' . $parts[1] . '-' . $parts[0];
                }
            } else {
                throw new Exception("Format tanggal salah");
            }

            /* ================= NIK AMAN ================= */
            $nik_balita = substr(preg_replace('/[^0-9]/', '', $data[1]), 0, 16);
            $nik_ibu    = substr(preg_replace('/[^0-9]/', '', $data[6]), 0, 16);

            /* ================= CEK POSYANDU ================= */
            $cek = $pdo->prepare("SELECT id_posyandu FROM posyandu WHERE id_posyandu=?");
            $cek->execute([$data[13]]);
            if (!$cek->fetch()) throw new Exception("ID Posyandu tidak ada");

            /* ================= INSERT ================= */
            $sql = "INSERT INTO balita (
                nama_balita, nik_balita, tgl_lahir, jenis_kelamin,
                nama_ayah, nama_ibu, nik_ibu_kunci, anak_ke,
                bb_lahir, pb_lahir, rt, rw, dusun, id_posyandu
            ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                trim($data[0]),
                $nik_balita,
                $tgl_final,
                strtoupper(trim($data[3])),
                trim($data[4]),
                trim($data[5]),
                $nik_ibu,
                (int)$data[7],
                (float)$data[8],
                (float)$data[9],
                trim($data[10]),
                trim($data[11]),
                trim($data[12]),
                (int)$data[13]
            ]);

            $berhasil++;

        } catch (Exception $e) {
            $gagal++;
            echo "Baris $baris gagal: " . $e->getMessage() . "\n";
        }
    }

    fclose($handle);
    $pdo->commit();

    echo "\nSELESAI\n";
    echo "Berhasil : $berhasil\n";
    echo "Gagal    : $gagal\n";
    echo "</pre>";

    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Import Data Balita</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-5">
    <div class="card mx-auto shadow border-0 rounded-4" style="max-width:500px;">
        <div class="card-body p-4">

            <h5 class="fw-bold text-center mb-4">Import Data Balita</h5>

            <div class="alert alert-info small">
                Format CSV:<br>
                Nama | NIK | Tgl Lahir | JK | Ayah | Ibu | NIK Ibu | Anak Ke | BB | PB | RT | RW | Dusun | ID Posyandu
            </div>

            <form method="POST" enctype="multipart/form-data">
                <input type="file" name="file_csv" class="form-control mb-3" accept=".csv" required>
                <button type="submit" name="import" class="btn btn-success w-100">
                    IMPORT SEKARANG
                </button>
            </form>

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

</body>
</html>
