<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('max_execution_time', 300); // Set timeout to 5 minutes
ini_set('memory_limit', '256M');    // Increase memory limit if needed

// Database connection with error handling
try {
    $koneksi = mysqli_connect("localhost", "akutans1", "kh", "pt_gadai_online");
    if (!$koneksi) {
        throw new Exception(mysqli_connect_error());
    }
    
    // Set wait_timeout dan interactive_timeout
    mysqli_query($koneksi, "SET session wait_timeout=600");
    mysqli_query($koneksi, "SET session interactive_timeout=600");
    
    // Start transaction
    mysqli_autocommit($koneksi, FALSE);
    
    // Validasi input data
    if (!isset($_POST['rekening']) || !isset($_POST['tgl']) || !isset($_POST['kol'])) {
        throw new Exception("Data yang diperlukan tidak lengkap");
    }
    
    $rekening = $_POST['rekening'];
    $tgl = $_POST['tgl'];
    $kol = $_POST['kol'];
    $total_records = count($rekening);
    
    if ($total_records === 0) {
        throw new Exception("Tidak ada data untuk diproses");
    }
    
    // Hapus data lama
    if (!mysqli_query($koneksi, "DELETE FROM kolek")) {
        throw new Exception("Gagal menghapus data lama: " . mysqli_error($koneksi));
    }
    
    // Buat query batch insert
    $batch_size = 500; // Jumlah record per batch
    $success_count = 0;
    $values = array();
    $query_base = "INSERT INTO kolek (tgl, rekening, kol) VALUES ";
    
    for ($i = 0; $i < $total_records; $i++) {
        // Escape string untuk mencegah SQL injection
        $safe_rekening = mysqli_real_escape_string($koneksi, $rekening[$i]);
        $safe_kol = mysqli_real_escape_string($koneksi, $kol[$i]);
        $safe_tgl = mysqli_real_escape_string($koneksi, $tgl);
        
        $values[] = "('$safe_tgl', '$safe_rekening', '$safe_kol')";
        
        // Eksekusi query setiap mencapai batch_size atau di akhir data
        if (count($values) >= $batch_size || $i == $total_records - 1) {
            $query = $query_base . implode(",", $values);
            
            if (!mysqli_query($koneksi, $query)) {
                throw new Exception("Gagal menyimpan batch data: " . mysqli_error($koneksi));
            }
            
            $success_count += count($values);
            $values = array(); // Reset array untuk batch berikutnya
            
            // Commit setiap batch
            mysqli_commit($koneksi);
        }
    }
    
    // Final commit
    mysqli_commit($koneksi);
    
    // Log hasil
    $log_message = "Berhasil memproses $success_count dari $total_records record";
    error_log($log_message);
    
    // Redirect dengan pesan sukses
    echo "<script type='text/javascript'>
        alert('$log_message');
        window.location = '../home.php?home=d1335ae7d5e6736c8ceda87fbded4aa1';
    </script>";

} catch (Exception $e) {
    // Rollback jika terjadi error
    if (isset($koneksi)) {
        mysqli_rollback($koneksi);
    }
    
    $error_message = "Error: " . $e->getMessage();
    error_log($error_message);
    
    echo "<script type='text/javascript'>
        alert('" . addslashes($error_message) . "');
        window.location = '../home.php?home=d1335ae7d5e6736c8ceda87fbded4aa1';
    </script>";
} finally {
    // Cleanup
    if (isset($koneksi)) {
        mysqli_close($koneksi);
    }
}
?>