<?php

namespace App\Http\Controllers\Api;

use App\Enums\ImportDatasourceStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\PbgTaskMultiStepRequest;
use App\Http\Resources\PbgTaskResource;
use App\Models\DataSetting;
use App\Models\ImportDatasource;
use App\Models\PbgTask;
use App\Models\PbgTaskGoogleSheet;
use App\Services\GoogleSheetService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PbgTaskController extends Controller
{
    protected $googleSheetService;
    public function __construct(GoogleSheetService $googleSheetService){
        $this->googleSheetService = $googleSheetService;
    }
    public function index(Request $request)
    {
        info($request);
        
        $isLastUpdated = filter_var($request->query('isLastUpdated', false), FILTER_VALIDATE_BOOLEAN);

        $query = PbgTask::query();

        if ($isLastUpdated) {
            $query->orderBy('updated_at', 'desc');
        } else {
            $query->where('status', 20);
        }

        // Ambil maksimal 10 data
        $pbg_task = $query->limit(10)->get();
        $totalData = $pbg_task->count();

        // Tambahkan nomor urut
        $data = $pbg_task->map(function ($item, $index) {
            return array_merge($item->toArray(), ['no' => $index + 1]);
        });

        return response()->json([
            'data' => $data,
            'meta' => [
                'total' => $totalData
            ]
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(PbgTaskMultiStepRequest $request)
    {
        try {
            $data = PbgTask::create([
                "uuid" => $request->input("step1Form.uuid"),
                "name" => $request->input("step1Form.name"),
                "owner_name" => $request->input("step1Form.owner_name"),
                "application_type" => $request->input("step1Form.application_type"),
                "application_type_name" => $request->input("step1Form.application_type_name"),
                "condition" => $request->input("step1Form.condition"),
                "registration_number" => $request->input("step1Form.registration_number"),
                "document_number" => $request->input("step1Form.document_number"),
                "address" => $request->input("step1Form.address"),
                "status" => $request->input("step1Form.status"),
                "status_name" => $request->input("step1Form.status_name"),
                "slf_status" => $request->input("step1Form.slf_status"),
                "slf_status_name" => $request->input("step1Form.slf_status_name"),
                "function_type" => $request->input("step1Form.function_type"),
                "consultation_type" => $request->input("step1Form.consultation_type"),
                "due_date" => $request->input("step1Form.due_date"),
                "land_certificate_phase" => $request->input("step1Form.land_certificate_phase"),
                "task_created_at" => $request->input("step1Form.task_created_at"),
            ]);

            return response()->json([
                "success" => true,
                "message" => "Step 1 berhasil disimpan!",
                "data" => $data
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                "success" => false,
                "message" => "Gagal menyimpan data",
                "error" => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        try{
            $pbg_task = PbgTask::with(['pbg_task_retributions','pbg_task_index_integrations','pbg_task_retributions.pbg_task_prasarana'])->findOrFail($id);
            return response()->json([
                "success"=> true,
                "message"=> "Data ditemukan",
                "data"=> $pbg_task
            ]);
        }catch(\Exception $e){
            return response()->json([
                "success"=> false,
                "message"=> $e->getMessage(),
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    protected function validatePbgTask(Request $request){
        return $request->validate([
            "uuid" => $request->input("step1Form.uuid"),
        ]);
    }

    public function syncPbgFromGoogleSheet(){
        $import_datasource = ImportDatasource::create([
            "message" => "initialization",
            "response_body" => null,
            "status" => ImportDatasourceStatus::Processing->value,
        ]);
        try{
            $totalRowCount = $this->googleSheetService->getLastRowByColumn("C");
            $sheetData = $this->googleSheetService->getSheetDataCollection($totalRowCount);
            $sheet_big_data = $this->googleSheetService->get_data_by_sheet();
            $data_setting_result = []; // Initialize result storage
        
            $found_section = null; // Track which section is found
        
            foreach ($sheet_big_data as $row) {
                // Check for section headers
                if (in_array("•PROSES PENERBITAN:", $row)) {
                    $found_section = "MENUNGGU_KLIK_DPMPTSP";
                } elseif (in_array("•BERKAS AKTUAL TERVERIFIKASI DINAS TEKNIS 2024:", $row)) {
                    $found_section = "REALISASI_TERBIT_PBG";
                } elseif (in_array("•TERPROSES DI DPUTR: belum selesai rekomtek'", $row)) {
                    $found_section = "PROSES_DINAS_TEKNIS";
                }
        
                // If a section is found and we reach "Grand Total", save the corresponding values
                if ($found_section && isset($row[0]) && trim($row[0]) === "Grand Total") {
                    if ($found_section === "MENUNGGU_KLIK_DPMPTSP") {
                        $data_setting_result["MENUNGGU_KLIK_DPMPTSP_COUNT"] = $row[2] ?? null;
                        $data_setting_result["MENUNGGU_KLIK_DPMPTSP_SUM"] = $row[3] ?? null;
                    } elseif ($found_section === "REALISASI_TERBIT_PBG") {
                        $data_setting_result["REALISASI_TERBIT_PBG_COUNT"] = $row[2] ?? null;
                        $data_setting_result["REALISASI_TERBIT_PBG_SUM"] = $row[4] ?? null;
                    } elseif ($found_section === "PROSES_DINAS_TEKNIS") {
                        $data_setting_result["PROSES_DINAS_TEKNIS_COUNT"] = $row[2] ?? null;
                        $data_setting_result["PROSES_DINAS_TEKNIS_SUM"] = $row[3] ?? null;
                    }
        
                    // Reset section tracking after capturing "Grand Total"
                    $found_section = null;
                }
            }
            foreach ($data_setting_result as $key => $value) {
                DataSetting::updateOrInsert(
                    ["key" => $key], // Find by key
                    ["value" => $value] // Update or insert value
                );
            }
            $mapToUpsert = [];
            $count = 0;

            foreach($sheetData as $data){
                $mapToUpsert[] = 
                    [
                        'no_registrasi' => $data['no__registrasi'] ?? null,
                        'jenis_konsultasi' => $data['jenis_konsultasi'] ?? null,
                        'fungsi_bg' => $data['fungsi_bg'] ?? null,
                        'tgl_permohonan' => $this->convertToDate($data['tgl_permohonan']),
                        'status_verifikasi' => $data['status_verifikasi'] ?? null,
                        'status_permohonan' => $this->convertToDate($data['status_permohonan']),
                        'alamat_pemilik' => $data['alamat_pemilik'] ?? null,
                        'no_hp' => $data['no__hp'] ?? null,
                        'email' => $data['e_mail'] ?? null,
                        'tanggal_catatan' => $this->convertToDate($data['tanggal_catatan']),
                        'catatan_kekurangan_dokumen' => $data['catatan_kekurangan_dokumen'] ?? null,
                        'gambar' => $data['gambar'] ?? null,
                        'krk_kkpr' => $data['krk_kkpr'] ?? null,
                        'no_krk' => $data['no__krk'] ?? null,
                        'lh' => $data['lh'] ?? null,
                        'ska' => $data['ska'] ?? null,
                        'keterangan' => $data['keterangan'] ?? null,
                        'helpdesk' => $data['helpdesk'] ?? null,
                        'pj' => $data['pj'] ?? null,
                        'kepemilikan' => $data['kepemilikan'] ?? null,
                        'potensi_taru' => $data['potensi_taru'] ?? null,
                        'validasi_dinas' => $data['validasi_dinas'] ?? null,
                        'kategori_retribusi' => $data['kategori_retribusi'] ?? null,
                        'no_urut_ba_tpt' => $data['no__urut_ba_tpt__2024_0001_'] ?? null,
                        'tanggal_ba_tpt' => $this->convertToDate($data['tanggal_ba_tpt']),
                        'no_urut_ba_tpa' => $data['no__urut_ba_tpa'] ?? null,
                        'tanggal_ba_tpa' => $this->convertToDate($data['tanggal_ba_tpa']),
                        'no_urut_skrd' => $data['no__urut_skrd__2024_0001_'] ?? null,
                        'tanggal_skrd' => $this->convertToDate($data['tanggal_skrd']),
                        'ptsp' => $data['ptsp'] ?? null,
                        'selesai_terbit' => $data['selesai_terbit'] ?? null,
                        'tanggal_pembayaran' => $this->convertToDate($data['tanggal_pembayaran__yyyy_mm_dd_']),
                        'format_sts' => $data['format_sts'] ?? null,
                        'tahun_terbit' => (int) $data['tahun_terbit'] ?? null,
                        'tahun_berjalan' => (int) $data['tahun_berjalan'] ?? null,
                        'kelurahan' => $data['kelurahan'] ?? null,
                        'kecamatan' => $data['kecamatan'] ?? null,
                        'lb' => $this->convertToDecimal($data['lb'])  ?? null,
                        'tb' => $this->convertToDecimal($data['tb']) ?? null,
                        'jlb' => (int) $data['jlb'] ?? null,
                        'unit' => (int) $data['unit'] ?? null,
                        'usulan_retribusi' => (int) $data['usulan_retribusi'] ?? null,
                        'nilai_retribusi_keseluruhan_simbg' => $this->convertToDecimal($data['nilai_retribusi_keseluruhan__simbg_']) ?? null,
                        'nilai_retribusi_keseluruhan_pad' => $this->convertToDecimal($data['nilai_retribusi_keseluruhan__pad_']) ?? null,
                        'denda' => $this->convertToDecimal($data['denda']) ?? null,
                        'latitude' => $data['latitude'] ?? null,
                        'longitude' => $data['longitude'] ?? null,
                        'nik_nib' => $data['nik_nib'] ?? null,
                        'dok_tanah' => $data['dok__tanah'] ?? null,
                        'temuan' => $data['temuan'] ?? null,
                    ];
            }

            DB::beginTransaction();

            $batchSize = 1000;
            $chunks = array_chunk($mapToUpsert, $batchSize);

            foreach($chunks as $chunk){
                PbgTaskGoogleSheet::upsert($chunk, ["no_registrasi"],[
                    'jenis_konsultasi',
                    'nama_pemilik',
                    'lokasi_bg',
                    'fungsi_bg',
                    'nama_bangunan',
                    'tgl_permohonan',
                    'status_verifikasi',
                    'status_permohonan',
                    'alamat_pemilik',
                    'no_hp',
                    'email',
                    'tanggal_catatan',
                    'catatan_kekurangan_dokumen',
                    'gambar',
                    'krk_kkpr',
                    'no_krk',
                    'lh',
                    'ska',
                    'keterangan',
                    'helpdesk',
                    'pj',
                    'kepemilikan',
                    'potensi_taru',
                    'validasi_dinas',
                    'kategori_retribusi',
                    'no_urut_ba_tpt',
                    'tanggal_ba_tpt',
                    'no_urut_ba_tpa',
                    'tanggal_ba_tpa',
                    'no_urut_skrd',
                    'tanggal_skrd',
                    'ptsp',
                    'selesai_terbit',
                    'tanggal_pembayaran',
                    'format_sts',
                    'tahun_terbit',
                    'tahun_berjalan',
                    'kelurahan',
                    'kecamatan',
                    'lb',
                    'tb',
                    'jlb',
                    'unit',
                    'usulan_retribusi',
                    'nilai_retribusi_keseluruhan_simbg',
                    'nilai_retribusi_keseluruhan_pad',
                    'denda',
                    'latitude',
                    'longitude',
                    'nik_nib',
                    'dok_tanah',
                    'temuan',
                ]);
            }

            $total_data = count($mapToUpsert);

            $import_datasource->update([
                "message" => "Successfully processed: {$total_data}",
                "status" => ImportDatasourceStatus::Success->value,
            ]);

            DB::commit();

            return response()->json([
                "success" => true,
                "message" => "Data berhasil disimpan ke database"
            ], 200);
        }catch(\Exception $ex){
            DB::rollBack();
            $import_datasource->update([
                "message" => "Failed to importing",
                "response_body" => $ex->getMessage(),
                "status" => ImportDatasourceStatus::Failed->value,
            ]);
            return response()->json([
                "success" => false,
                "message" => "Gagal menyimpan data",
                "error" => $ex->getMessage()
            ], 500);
        }
    }

    protected function convertToDecimal(?string $value): ?float
    {
        if (empty($value)) {
            return null; // Return null if the input is empty
        }

        // Remove all non-numeric characters except comma and dot
        $value = preg_replace('/[^0-9,\.]/', '', $value);

        // If the number contains both dot (.) and comma (,)
        if (strpos($value, '.') !== false && strpos($value, ',') !== false) {
            $value = str_replace('.', '', $value); // Remove thousands separator
            $value = str_replace(',', '.', $value); // Convert decimal separator to dot
        }
        // If only a dot is present (assumed as thousands separator)
        elseif (strpos($value, '.') !== false) {
            $value = str_replace('.', '', $value); // Remove all dots (treat as thousands separators)
        }
        // If only a comma is present (assumed as decimal separator)
        elseif (strpos($value, ',') !== false) {
            $value = str_replace(',', '.', $value); // Convert comma to dot (decimal separator)
        }

        // Ensure the value is numeric before returning
        return is_numeric($value) ? (float) number_format((float) $value, 2, '.', '') : null;
    }

    protected function convertToInteger($value) {
        // Check if the value is an empty string, and return null if true
        if (trim($value) === "") {
            return null;
        }

        // Otherwise, cast to integer
        return (int) $value;
    }

    protected function convertToDate($dateString)
    {
        try {
            // Check if the string is empty
            if (empty($dateString)) {
                return null;
            }

            // Try to parse the date string
            $date = Carbon::parse($dateString);

            // Return the Carbon instance
            return $date->format('Y-m-d');
        } catch (\Exception $e) {
            // Return null if an error occurs during parsing
            return null;
        }
    }
}
