<?php

namespace App\Http\Controllers;

use App\Models\DataLatih;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ImportController extends Controller
{
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls'
        ]);

        $file = $request->file('file');
        $spreadsheet = IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();

        $dataToInsert = [];

        foreach ($rows as $index => $row) {
            if ($index === 0) continue; // skip header

            $kecamatan = trim($row[1]); // Kolom ke-1: Kecamatan
            if (empty($kecamatan)) continue;

            $dataToInsert[] = [
                'kecamatan'       => $kecamatan,
                'data_tahun'      => is_numeric($row[2]) ? (int)$row[2] : 2023,   // Data Tahun
                'phbs'            => is_numeric($row[3]) ? (float)$row[3] : 0,    // PHBS
                'imunisasi'       => is_numeric($row[4]) ? (float)$row[4] : 0,    // Imunisasi
                'merokok'         => is_numeric($row[5]) ? (float)$row[5] : 0,    // Perilaku Merokok
                'kasus_2023'      => is_numeric($row[6]) ? (int)$row[6] : 0,      // Data Kasus
                'latitude'        => is_numeric($row[7]) ? (float)($row[7] / 1000000) : 0, // Latitude
                'longitude'       => is_numeric($row[8]) ? (float)($row[8] / 1000000) : 0, // Longitude
                'prediksi_tahun'  => isset($row[9]) && is_numeric($row[9]) ? (int)$row[9] : null, // Prediksi Tahun
                'hipotesis'       => isset($row[10]) && $row[10] !== '' ? trim($row[10]) : null, // Status
                'created_at'      => now(),
                'updated_at'      => now(),
            ];
        }

        if (!empty($dataToInsert)) {
            DataLatih::insert($dataToInsert);
        }

        return redirect()->back()->with('success', 'Dataset berhasil diimport!');
    }
}
