<?php

namespace Modules\Lpj\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Str;
use Modules\Lpj\Models\KJPP;
use Modules\Lpj\Models\JenisJaminan;
use Modules\Lpj\Models\IjinUsaha;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Village;

class KJPPSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */

    public function run(): void
    {
        $filePath = __DIR__ . '/list-update-kjpp.xlsx';
        // DB::unprepared(file_get_contents(__DIR__ . '/kjpp.sql'));

        if (!file_exists($filePath)) {
            $this->command->error('File excel tidak ditemukan di: ' . $filePath);
            return;
        }

        $this->command->info('Membaca file Excel...');

        try {
            // Baca excel dan tampilkan raw data
            $collection = Excel::toCollection(null, $filePath)->first();
            // Debug: Tampilkan jumlah baris
            $this->command->info('Total baris: ' . $collection->count());

            // Debug: Tampilkan 3 baris pertama (header)
            // $this->command->info('Header data:');
            // foreach($collection->take(3) as $index => $row) {
            //     $this->command->info("Baris $index: " . print_r($row->toArray(), true));
            // }

            // Skip 3 baris header
            $data = $collection->skip(3);


            // Proses setiap baris
            foreach ($data as $index => $row) {
                $this->command->info("Memproses baris ke-$index:");

                // Debug: Tampilkan data mentah
                // $this->command->info('Raw data: ' . print_r($row->toArray(), true));

                // Skip jika baris kosong
                if (empty($row[2])) {
                    $this->command->warn("Baris $index dilewati karena nama KJPP kosong");
                    continue;
                }


                $locationData = $this->checkKota($row[5]);

                $jenisUsaha = $this->checkJenisUsaha($row[18]);
                $jenisAsset = $this->checkJenisAsset($row[19]);

                $detail_email_kantor = $this->checkDanJadikanJson($row[9]);
                $nama_pic_reviewer = $this->checkDanJadikanJson($row[12]);
                $nomor_hp_pic_reviewer = $this->checkDanJadikanJson($row[13]);
                $detail_nama_pic_admin = $this->checkDanJadikanJson($row[14]);

                $nomor_hp_pic_admin = $this->checkDanJadikanJson($row[15]);
                $nama_pic_marketing = $this->checkDanJadikanJson($row[16]);


                $nomor_hp_pic_marketing = $this->checkDanJadikanJson($row[17]);


                try {
                    $dataToInsert = [
                        'code' => $this->generateKJPPCode(),
                        'name' => $row[2],
                        'jenis_kantor' => "Kantor " . $row[3],
                        'nomor_ijin_usaha' => $row[4],
                        'province_code' => $locationData['province'],
                        'city_code' => $locationData['city'],
                        'district_code' => $locationData['district'],
                        'village_code' => $locationData['village'],
                        'address' => $row[7],
                        'postal_code' => $locationData['postal_code'],
                        'nomor_telepon_kantor' => $row[8],
                        'email_kantor' => $detail_email_kantor[0],
                        'detail_email_kantor' => json_encode($detail_email_kantor),
                        'nama_pimpinan' => $row[10],
                        'nomor_hp_pimpinan' => $row[11],
                        'nama_pic_reviewer' => $nama_pic_reviewer[0],
                        'detail_nama_pic_reviewer' => json_encode($nama_pic_reviewer),
                        'nomor_hp_pic_reviewer' => $nomor_hp_pic_reviewer[0],
                        'detail_nomor_hp_pic_reviewer' =>  json_encode($nomor_hp_pic_reviewer),

                        'nama_pic_admin' => $detail_nama_pic_admin[0],
                        'detail_nama_pic_admin' => json_encode($detail_nama_pic_admin),
                        'nomor_hp_pic_admin' => $nomor_hp_pic_admin[0],
                        'detail_nomor_hp_pic_admin' => json_encode($nomor_hp_pic_admin),
                        'nama_pic_marketing' => $nama_pic_marketing[0],
                        'detail_nama_pic_marketing' => json_encode($nama_pic_marketing),
                        'nomor_hp_pic_marketing' => $nomor_hp_pic_marketing[0],
                        'detail_nomor_hp_pic_marketing' => json_encode($nomor_hp_pic_marketing),
                        'ijin_usaha_id' => json_encode($jenisUsaha),
                        'jenis_aset_id' => json_encode($jenisAsset),
                        'attachment' => null,
                    ];




                    // Simpan ke database
                    KJPP::create($dataToInsert);

                    $this->command->info("Berhasil menyimpan data baris $index");

                } catch (\Exception $e) {
                    $this->command->error("Error pada baris $index: " . $e->getMessage());
                    // Lanjut ke baris berikutnya
                    continue;
                }
            }

            $this->command->info('Selesai import data KJPP!');

        } catch (\Exception $e) {
            $this->command->error('Error utama: ' . $e->getMessage());
            $this->command->error('Stack trace: ' . $e->getTraceAsString());
        }
    }

    private function generateKJPPCode()
    {
        do {
            $code = 'K' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
        } while (KJPP::where('code', $code)->exists());

        return $code;
    }

    public function checkKota($data)
    {
        try {
            $city = null;
            if ($data) {
                // Bersihkan data dan ubah ke uppercase
                $cleanData = trim(strtoupper($data));

                $possibleNames = [
                    'KAB. ' . $cleanData,
                    'KOTA ' . $cleanData,
                    'KAB. ADM. ' . $cleanData,
                    'KOTA ADM. ' . $cleanData,
                    $cleanData
                ];

                $city = City::whereIn(DB::raw('UPPER(name)'), $possibleNames)->first();

                if ($city) {
                    // Cari district berdasarkan city_code
                    $district = District::where('city_code', $city->code)->first();
                    if (!$district) {
                        return null;
                    }

                    $village = Village::where('district_code', $district->code)->first();
                    if (!$village) {

                        return null;
                    }
                    return [
                        'province' => $city->province_code,
                        'city' => $city->code,
                        'district' => $district->code,
                        'village' => $village->code,
                        'postal_code' => $village->postal_code
                    ];
                } else {
                    return null;
                }
            }

            return null;

        } catch (\Exception $e) {
            $this->command->error("   ❌ Error: " . $e->getMessage());
            return null;
        }
    }

    public function checkJenisAsset($data)
    {
        try {
            if (!$data) {
                return [];
            }

            // Bersihkan dan ubah ke lowercase
            $cleanData = trim(strtolower($data));

            // Pisahkan berdasarkan koma, titik koma, dan spasi
            $assets = preg_split('/[;,]+|\\s+/', $cleanData);

            // Daftar asset yang valid di database
            $validAssets = JenisJaminan::pluck('code')->toArray();
            $assetIds = [];

            foreach ($assets as $asset) {
                // Hapus spasi di awal dan akhir
                $asset = trim($asset);

                // Cek jika ada tanda kurung
                if (preg_match('/\((.*?)\)/', $asset, $matches)) {
                    // Ambil isi dalam tanda kurung dan pisahkan
                    $insideParentheses = explode(',', $matches[1]);
                    foreach ($insideParentheses as $insideAsset) {
                        $insideAsset = trim($insideAsset);
                        // Cari di database
                        $jenisAsset = JenisJaminan::whereRaw('LOWER(name) = ?', [$insideAsset])->first();
                        if ($jenisAsset && in_array($jenisAsset->code, $validAssets)) {
                            $assetIds[] = $jenisAsset->code;
                        }
                    }
                }

                // Cek jenis aset utama (tanpa tanda kurung)
                $jenisAsset = JenisJaminan::whereRaw('LOWER(name) = ?', [$asset])->first();
                if ($jenisAsset && in_array($jenisAsset->code, $validAssets)) {
                    $assetIds[] = $jenisAsset->code;

                }
            }

            // Menghilangkan duplikat jika ada
            $assetIds = array_unique($assetIds);

            // Sort array untuk konsistensi
            sort($assetIds);

            return $assetIds;

        } catch (\Exception $e) {
            $this->command->error("   ❌ Error pada checkJenisAsset: " . $e->getMessage());
            return [];
        }
    }


    public function checkJenisUsaha($data)
    {
        try {
            if (!$data) {
                return [];
            }

            // Bersihkan dan ubah ke lowercase
            $cleanData = trim(strtolower($data));

            // Pisahkan berdasarkan koma, titik koma, atau garis miring
            $usahas = preg_split('/[\s,;\/]+/', $cleanData);

            // Ambil daftar valid usaha dari database
            $validUsaha = IjinUsaha::pluck('code')->toArray();
            $usahaIds = [];

            foreach ($usahas as $usaha) {
                // Hapus spasi di awal dan akhir
                $usaha = trim($usaha);

                // Cari jenis usaha di database
                $jenisUsaha = IjinUsaha::whereRaw('LOWER(name) = ?', [$usaha])->first();

                if ($jenisUsaha && in_array($jenisUsaha->code, $validUsaha)) {
                    $usahaIds[] = $jenisUsaha->code;
                }
            }

            // Menghilangkan duplikat jika ada
            $usahaIds = array_unique($usahaIds);

            // Sort array untuk konsistensi
            sort($usahaIds);

            return $usahaIds;

        } catch (\Exception $e) {
            $this->command->error("   ❌ Error pada checkJenisUsaha: " . $e->getMessage());
            return [];
        }
    }


    // Fungsi untuk memisahkan dan mengonversi data menjadi array JSON
    public function checkDanJadikanJson($input)
    {
        $input = trim($input);

        // Memisahkan berdasarkan "/", ";", "dan", atau baris baru ("\n")
        $separatedData = preg_split('/\s*\/\s*|\s*;\s*|\s*dan\s*|\s*\n\s*/i', $input);

        // Membersihkan data
        $cleanedData = array_map('trim', $separatedData);

        // Menghapus elemen kosong
        $cleanedData = array_filter($cleanedData, function ($item) {
            return !empty($item);
        });

        // Kembalikan array yang sudah diurutkan ulang (indeks dimulai dari 0)
        return array_values($cleanedData);
    }




}
