<?php
// Aktifkan error logging untuk debugging
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    $fileName = $_FILES['file']['name'];
    $fileType = $_FILES['file']['type'];
    $tmpFile = $_FILES['file']['tmp_name'];

    // Validasi nama file harus dalam format ddmmyyyy.txt (contoh: 19072025.txt)
    if (preg_match('/^\d{8}\.txt$/', $fileName)) {
        if ($fileType == 'text/plain') {
            $fileContent = file_get_contents($tmpFile);

            // Backup winners.txt ke format backup_ddmmyyyy.txt
            if (file_exists('winners.txt')) {
                $timestamp = date('dmY'); // Format: 19072025
                copy('winners.txt', "backup_$timestamp.txt");
            }

            // Pecah data berdasarkan baris
            $lines = explode("\n", $fileContent);

            // Hapus baris kosong atau data yang tidak valid
            $validNames = array_filter($lines, function($name) {
                return !empty(trim($name));  // Pastikan nama tidak kosong
            });

            // Simpan data baru ke winners.txt
            file_put_contents('winners.txt', implode("\n", $validNames) . "\n");
            echo "✅ Upload sukses dan file berhasil disimpan!";
        } else {
            echo "❌ Jenis file tidak valid. Harap upload file .txt.";
        }
    } else {
        echo "❌ Nama file harus dalam format ddmmyyyy.txt (contoh: 19072025.txt)";
    }
} else {
    echo "❌ Gagal upload file.";
}
?>



