<?php
	include '../aksi/koneksi.php';

if (isset($_POST['import'])) {
    $file = $_FILES['file_csv']['tmp_name'];

    if (($handle = fopen($file, "r")) !== FALSE) {
        
        // 1. Lewati Baris Pertama (Judul: "LAPORAN SERVICE 2026")
        fgetcsv($handle, 1000, ",");
        
        // 2. Lewati Baris Kedua (Header: "No, Nama, No Telp, ...")
        fgetcsv($handle, 1000, ",");

        $berhasil = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            
            // Cek jika kolom nama (index 1) kosong atau berisi ringkasan, maka lewati
            if (empty($data[1]) || strpos($data[1], 'Total') !== false) continue;

            $nama_customer = mysqli_real_escape_string($conn, $data[1])
            $no_telp       = mysqli_real_escape_string($conn, $data[2]);
            
            // 3. Konversi Tanggal (DD/MM/YY ke YYYY-MM-DD)
            $tgl_raw       = str_replace('/', '-', $data[3]);
            $tgl_nota      = date('Y-m-d', strtotime($tgl_raw));

            $ket           = mysqli_real_escape_string($conn, $data[7]);
            
            // 4. Bersihkan Harga (Hapus "Rp", Titik, dan Koma)
            $harga_raw     = $data[9]; // Sesuai kolom "Harga" di CSV
            $harga         = preg_replace("/[^0-9]/", "", $harga_raw);

            $query = "INSERT INTO data_servis (nama_customer, no_telp, tgl_masuk, keterangan, total_biaya) 
                      VALUES ('$nama_customer', '$no_telp', '$tgl_nota', '$ket', '$harga')";
            
            if (mysqli_query($conn, $query)) {
                $berhasil++;
            }
        }
        fclose($handle);

        echo "<script>
                alert('$berhasil Data berhasil diimport!');
                document.location.href = 'import-service.php';
              </script>";
    } else {
        echo "Gagal membuka file.";
    }
}
?>