<?php
// import_handler.php - VERSI TANPA TANGGAL (AUTO TIMESTAMP)
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Bersihkan output buffer agar JSON bersih
ob_start();
include 'config.php';
ob_clean(); 

header('Content-Type: application/json; charset=utf-8');

// 1. Cek Koneksi
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Koneksi DB Gagal: ' . $conn->connect_error]);
    exit;
}

// 2. Ambil Data JSON
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['rows'])) {
    echo json_encode(['status' => 'error', 'message' => 'Data JSON tidak valid/kosong']);
    exit;
}

$rows = $data['rows'];

// 3. Eksekusi Database
$conn->begin_transaction();

try {
    // A. Kosongkan Tabel
    if (!$conn->query("TRUNCATE TABLE wakaf_ambulance")) {
        throw new Exception("Gagal Truncate: " . $conn->error);
    }

    // B. Insert Data (TANPA TANGGAL)
    // Kolom `tanggal` (timestamp) akan otomatis terisi waktu sekarang oleh MySQL
    $stmt = $conn->prepare("INSERT INTO wakaf_ambulance (nama, jml_tiket, total_wakaf) VALUES (?, ?, ?)");

    if (!$stmt) {
        throw new Exception("Prepare Gagal: " . $conn->error);
    }

    foreach ($rows as $index => $row) {
        $nama = $row['nama'];
        $jml_tiket = (int)$row['jml_tiket'];
        $total_wakaf = (double)$row['total_wakaf'];

        // Bind: s = string, i = integer, d = double
        if (!$stmt->bind_param("sid", $nama, $jml_tiket, $total_wakaf)) {
            throw new Exception("Bind Gagal pada baris " . ($index+1));
        }

        if (!$stmt->execute()) {
            throw new Exception("Insert Gagal: " . $stmt->error);
        }
    }

    $stmt->close();
    $conn->commit();
    echo json_encode(['status' => 'success', 'message' => 'Sukses import ' . count($rows) . ' data.']);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

$conn->close();
?>