<?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 (index 1 karena id di kolom 0)
            if (empty($kecamatan)) continue;

            $dataToInsert[] = [
                'kecamatan'       => $kecamatan,
                'jumlah_penduduk' => is_numeric($row[2]) ? (int)$row[2] : 0,      // kolom 2
                'data_tahun'      => is_numeric($row[3]) ? (int)$row[3] : 2023,   // kolom 3
                'phbs'            => is_numeric($row[4]) ? (float)$row[4] : 0,
                'pcv1'            => is_numeric($row[5]) ? (float)$row[5] : 0,
                'pcv2'            => is_numeric($row[6]) ? (float)$row[6] : 0,
                'imunisasi'       => is_numeric($row[7]) ? (float)$row[7] : 0,
                'merokok'         => is_numeric($row[8]) ? (float)$row[8] : 0,
                'kasus_2023'      => is_numeric($row[9]) ? (int)$row[9] : 0,
                'latitude'        => is_numeric($row[10]) ? (float)($row[10] / 1000000) : 0,
                'longitude'       => is_numeric($row[11]) ? (float)($row[11] / 1000000) : 0,
                'prediksi_tahun'  => isset($row[12]) && is_numeric($row[12]) ? (int)$row[12] : null,
                'hipotesis'       => isset($row[13]) && $row[13] !== '' ? trim($row[13]) : null,
                'created_at'      => now(),
                'updated_at'      => now(),
            ];
        }

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

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