<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\BigdataResumeResource;
use App\Models\BigdataResume;
use App\Models\DataSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BigDataResumeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        try{
            $filterDate = $request->get("filterByDate");

            if (!$filterDate || $filterDate === "latest") {
                $big_data_resume = BigdataResume::where('year', now()->year)->latest()->first();
                if (!$big_data_resume) {
                    return $this->response_empty_resume();
                }
            } else {
                $big_data_resume = BigdataResume::whereDate('created_at', $filterDate)
                    ->orderBy('id', 'desc')
                    ->first();

                if (!$big_data_resume) {
                    return $this->response_empty_resume();
                }
            }

            $data_settings = DataSetting::all();
            if($data_settings->isEmpty()){
                return response()->json(['message' => 'No data setting found']);
            }

            function cleanNumber($value) {
            return floatval(str_replace('.', '', $value));
            }

            $target_pad = floatval(optional($data_settings->where('key', 'TARGET_PAD')->first())->value);
            $realisasi_terbit_pbg_sum = cleanNumber(optional($data_settings->where('key', 'REALISASI_TERBIT_PBG_SUM')->first())->value);
            $realisasi_terbit_pbg_count = cleanNumber(optional($data_settings->where('key', 'REALISASI_TERBIT_PBG_COUNT')->first())->value);
            $menunggu_klik_dpmptsp_sum = cleanNumber(optional($data_settings->where('key', 'MENUNGGU_KLIK_DPMPTSP_SUM')->first())->value);
            $menunggu_klik_dpmptsp_count = cleanNumber(optional($data_settings->where('key', 'MENUNGGU_KLIK_DPMPTSP_COUNT')->first())->value);
            $proses_dinas_teknis_sum = cleanNumber(optional($data_settings->where('key', 'PROSES_DINAS_TEKNIS_SUM')->first())->value);
            $proses_dinas_teknis_count = cleanNumber(optional($data_settings->where('key', 'PROSES_DINAS_TEKNIS_COUNT')->first())->value);
            
            $tata_ruang = $big_data_resume->spatial_sum;
            $kekurangan_potensi = $target_pad - $big_data_resume->potention_sum;

            // percentage kekurangan potensi
            $kekurangan_potensi_percentage = $target_pad > 0 && $target_pad > 0 
            ? round(($kekurangan_potensi / $target_pad) * 100, 2) : 0;

            // percentage total potensi
            $total_potensi_percentage = $big_data_resume->potention_sum > 0 && $target_pad > 0 
            ? round(($big_data_resume->potention_sum / $target_pad) * 100, 2) : 0;
            
            // percentage verified document
            $verified_percentage = $big_data_resume->verified_sum > 0 && $big_data_resume->potention_sum > 0 
            ? round(($big_data_resume->verified_sum / $big_data_resume->potention_sum) * 100, 2) : 0;

            // percentage non-verified document
            $non_verified_percentage = $big_data_resume->non_verified_sum > 0 && $big_data_resume->potention_sum > 0 
            ? round(($big_data_resume->non_verified_sum / $big_data_resume->potention_sum) * 100, 2) : 0;

            // percentage business document
            $business_percentage = $big_data_resume->business_sum > 0 && $big_data_resume->non_verified_sum > 0 
            ? round(($big_data_resume->business_sum / $big_data_resume->non_verified_sum) * 100, 2) : 0;

            // percentage non-business document
            $non_business_percentage = $big_data_resume->non_business_sum > 0 && $big_data_resume->potention_sum > 0 
            ? round(($big_data_resume->non_business_sum / $big_data_resume->potention_sum) * 100, 2) : 0;

            // percentage tata ruang
            $tata_ruang_percentage = $tata_ruang > 0 && $big_data_resume->potention_sum > 0 
            ? round(($tata_ruang / $big_data_resume->potention_sum) * 100, 2) : 0;

            // percentage realisasi terbit pbg
            $realisasi_terbit_percentage = $big_data_resume->verified_sum > 0 && $realisasi_terbit_pbg_sum > 0
            ? round(($realisasi_terbit_pbg_sum / $big_data_resume->verified_sum) * 100, 2) : 0;

            // percentage menunggu klik dpmptsp
            $menunggu_klik_dpmptsp_percentage = $big_data_resume->verified_sum > 0 && $menunggu_klik_dpmptsp_sum > 0
            ? round(($menunggu_klik_dpmptsp_sum / $big_data_resume->verified_sum) * 100, 2) : 0;

            // percentage proses_dinas_teknis
            $proses_dinas_teknis_percentage = $big_data_resume->verified_sum > 0 && $proses_dinas_teknis_sum > 0
            ? round(($proses_dinas_teknis_sum / $big_data_resume->verified_sum) * 100, 2) : 0;

            $result = [
                'target_pad' => [
                    'sum' => $target_pad,
                    'percentage' => 100,
                ],
                'tata_ruang' => [
                    'sum' => $big_data_resume->spatial_sum,
                    'count' => $big_data_resume->spatial_count,
                    'percentage' => $tata_ruang_percentage,
                ],
                'kekurangan_potensi' => [
                    'sum' => $kekurangan_potensi,
                    'percentage' => $kekurangan_potensi_percentage
                ],
                'total_potensi' => [
                    'sum' => (float) $big_data_resume->potention_sum,
                    'count' => $big_data_resume->potention_count,
                    'percentage' => $total_potensi_percentage
                ],
                'verified_document' => [
                    'sum' => (float) $big_data_resume->verified_sum,
                    'count' => $big_data_resume->verified_count,
                    'percentage' => $verified_percentage
                ],
                'non_verified_document' => [
                    'sum' => (float) $big_data_resume->non_verified_sum,
                    'count' => $big_data_resume->non_verified_count,
                    'percentage' => $non_verified_percentage
                ],
                'business_document' => [
                    'sum' => (float) $big_data_resume->business_sum,
                    'count' => $big_data_resume->business_count,
                    'percentage' => $business_percentage
                ],
                'non_business_document' => [
                    'sum' => (float) $big_data_resume->non_business_sum,
                    'count' => $big_data_resume->non_business_count,
                    'percentage' => $non_business_percentage
                ],
                'realisasi_terbit' => [
                    'sum' => $realisasi_terbit_pbg_sum,
                    'count' => $realisasi_terbit_pbg_count,
                    'percentage' => $realisasi_terbit_percentage
                ],
                'menunggu_klik_dpmptsp' => [
                    'sum' => $menunggu_klik_dpmptsp_sum,
                    'count' => $menunggu_klik_dpmptsp_count,
                    'percentage' => $menunggu_klik_dpmptsp_percentage
                ],
                'proses_dinas_teknis' => [
                    'sum' => $proses_dinas_teknis_sum,
                    'count' => $proses_dinas_teknis_count,
                    'percentage' => $proses_dinas_teknis_percentage
                ]
            ];
            return response()->json($result);
        }catch(\Exception $e){
            return response()->json(['message' => 'Error when fetching data'], 500);
        }
    }



    public function bigdata_report(Request $request){
        try{
            $query = BigdataResume::query()->orderBy('id', 'desc');
        
            if($request->filled('search')){
                $query->where('year', 'LIKE', '%'.$request->input('search').'%');
            }

            $query = $query->paginate(config('app.paginate_per_page', 50));
            return  BigdataResumeResource::collection($query)->response()->getData(true);
        }catch(\Exception $e){
            Log::error($e->getMessage());
            return response()->json(['message' => 'Error when fetching data'], 500);
        }
    }

    public function payment_recaps(Request $request)
    {
        try {
            $query = BigdataResume::query()->orderBy('id', 'desc');

            if ($request->filled('date')) {
                $query->where('year', 'LIKE', '%' . $request->input('search') . '%');
            }

            $data = $query->paginate(10);

            // Restructure response
            $transformedData = [];

            foreach ($data as $item) {
                $createdAt = $item->created_at;
                $id = $item->id;

                foreach ($item->toArray() as $key => $value) {
                    // Only include columns with "sum" in their names
                    if (strpos($key, 'sum') !== false) {
                        $transformedData[] = [
                            'id' => $id,
                            'category' => $key,
                            'nominal' => $value,
                            'created_at' => $createdAt,
                        ];
                    }
                }
            }

            return response()->json([
                'data' => $transformedData, // Flat array
                'pagination' => [
                    'total' => $data->total(),
                    'per_page' => $data->perPage(),
                    'current_page' => $data->currentPage(),
                    'last_page' => $data->lastPage(),
                ]
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['message' => 'Error when fetching data'], 500);
        }
    }


    private function response_empty_resume(){
        $result = [
            'target_pad' => [
                'sum' => 0,
                'percentage' => 100,
            ],
            'tata_ruang' => [
                'sum' => 0,
                'percentage' => 0,
            ],
            'kekurangan_potensi' => [
                'sum' => 0,
                'percentage' => 0
            ],
            'total_potensi' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'verified_document' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'non_verified_document' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'business_document' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'non_business_document' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'realisasi_terbit' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'menunggu_klik_dpmptsp' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ],
            'proses_dinas_teknis' => [
                'sum' => 0,
                'count' => 0,
                'percentage' => 0
            ]
        ];

        return response()->json($result);
    }
}
