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

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

/* ===============================
   VALIDASI FILE
=============================== */
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== 0) {
    die("File tidak valid");
}

$file = fopen($_FILES['file']['tmp_name'], "r");
if (!$file) {
    die("Gagal membuka CSV");
}

/* ===============================
   DETEKSI DELIMITER
=============================== */
$firstLine = fgets($file);
$delimiter = (substr_count($firstLine, ';') > substr_count($firstLine, ',')) ? ';' : ',';
rewind($file);

/* ===============================
   LEWATI HEADER + HAPUS BOM
=============================== */
$header = fgetcsv($file, 3000, $delimiter);
if (isset($header[0])) {
    $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', $header[0]);
}

/* ===============================
   PREPARE SQL
=============================== */
$sql = "INSERT INTO kwitansi
(npsn, tanggal, kode_kegiatan, kode_rekening, nobukti, uraian, jumb, satuanb, pengeluaran, yang_menerima)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Prepare gagal: " . $conn->error);
}

$berhasil = 0;
$gagal    = 0;
$errorLog = [];

/* ===============================
   LOOP CSV
=============================== */
while (($row = fgetcsv($file, 8000, $delimiter)) !== false) {

    if (count(array_filter($row)) === 0) continue;

    if (count($row) < 10) {
        $gagal++;
        continue;
    }

    $npsn = trim($row[0]);

    /* ===============================
       FORMAT TANGGAL (AMAN)
    =============================== */
    if (is_numeric($row[1])) {
        $tanggal = date('Y-m-d', ($row[1] - 25569) * 86400);
    } else {
        $tanggal = date('Y-m-d', strtotime($row[1]));
    }

    if (!$tanggal || $tanggal === '1970-01-01') {
        $gagal++;
        continue;
    }

    $kode_kegiatan = trim($row[2]);
    $kode_rekening = trim($row[3]);
    $nobukti       = trim($row[4]);
    $uraian        = trim($row[5]);

    $jumb = (int) $row[6];
    $satuanb = trim($row[7]);

    /* ===============================
       FORMAT ANGKA (FIX)
    =============================== */
    $pengeluaran = str_replace(['.', ','], ['', '.'], $row[8]);
    $pengeluaran = (float)$pengeluaran;

    $yang_menerima = trim($row[9]);

    $stmt->bind_param(
        "ssssssisds",
        $npsn,
        $tanggal,
        $kode_kegiatan,
        $kode_rekening,
        $nobukti,
        $uraian,
        $jumb,
        $satuanb,
        $pengeluaran,
        $yang_menerima
    );

    if ($stmt->execute()) {
        $berhasil++;
    } else {
        $gagal++;
        $errorLog[] = $stmt->error; // simpan error
    }
}

$stmt->close();
fclose($file);

/* ===============================
   SIMPAN HASIL + ERROR
=============================== */
$_SESSION['import_result'] = [
    'berhasil' => $berhasil,
    'gagal'    => $gagal,
    'error'    => $errorLog
];

header("Location: list_kwitansi.php");
exit;