<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class BigdataResume extends Model
{
    protected $table = "bigdata_resumes";

    protected $fillable = [
        'import_datasource_id',
        'potention_count',
        'potention_sum',
        'non_verified_count',
        'non_verified_sum',
        'verified_count',
        'verified_sum',
        'business_count',
        'business_sum',
        'non_business_count',
        'non_business_sum',
        'spatial_count',
        'spatial_sum',
        'year',
        'waiting_click_dpmptsp_count',
        'waiting_click_dpmptsp_sum',
        'issuance_realization_pbg_count',
        'issuance_realization_pbg_sum',
        'process_in_technical_office_count',
        'process_in_technical_office_sum',
    ];

    public function importDatasource()
    {
        return $this->belongsTo(ImportDatasource::class, 'import_datasource_id');
    }

    public static function generateResumeData($import_datasource_id, $year, $data_setting){
        $stats = PbgTask::with(['googleSheet', 'pbg_task_retributions'])
            ->leftJoin('pbg_task_retributions as ptr', 'pbg_task.uuid', '=', 'ptr.pbg_task_uid')
            ->leftJoin('pbg_task_google_sheet as ptgs', 'pbg_task.registration_number', '=', 'ptgs.no_registrasi')
            ->when($year !== 'all', function ($query) use ($year) {
                $query->whereYear('pbg_task.task_created_at', (int) $year);
            })
            ->selectRaw("
                COUNT(CASE WHEN LOWER(TRIM(ptgs.status_verifikasi)) = 'selesai verifikasi' THEN 1 END) AS verified_count,
                SUM(CASE WHEN LOWER(TRIM(ptgs.status_verifikasi)) = 'selesai verifikasi' THEN ptr.nilai_retribusi_bangunan ELSE 0 END) AS verified_total,
                
                COUNT(CASE WHEN LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL THEN 1 END) AS non_verified_count,
                SUM(CASE WHEN LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL THEN ptr.nilai_retribusi_bangunan ELSE 0 END) AS non_verified_total,
                
                COUNT(CASE WHEN (LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL) 
                        AND LOWER(TRIM(pbg_task.function_type)) = 'sebagai tempat usaha' THEN 1 END) AS business_count,
                SUM(CASE WHEN (LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL) 
                        AND LOWER(TRIM(pbg_task.function_type)) = 'sebagai tempat usaha' THEN ptr.nilai_retribusi_bangunan ELSE 0 END) AS business_total,

                COUNT(CASE WHEN (LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL) 
                        AND (LOWER(TRIM(pbg_task.function_type)) != 'sebagai tempat usaha' OR pbg_task.function_type IS NULL) THEN 1 END) AS non_business_count,
                SUM(CASE WHEN (LOWER(TRIM(ptgs.status_verifikasi)) != 'selesai verifikasi' OR ptgs.status_verifikasi IS NULL) 
                        AND (LOWER(TRIM(pbg_task.function_type)) != 'sebagai tempat usaha' OR pbg_task.function_type IS NULL) THEN ptr.nilai_retribusi_bangunan ELSE 0 END) AS non_business_total
            ")
            ->first();

        // Assign Results
        $verified_count = $stats->verified_count ?? 0;
        $verified_total = $stats->verified_total ?? 0;
        $non_verified_count = $stats->non_verified_count ?? 0;
        $non_verified_total = $stats->non_verified_total ?? 0;
        $business_count = $stats->business_count ?? 0;
        $business_total = $stats->business_total ?? 0;
        $non_business_count = $stats->non_business_count ?? 0;
        $non_business_total = $stats->non_business_total ?? 0;

        $query_potention = once(function () use ($year) {
            $query = PbgTask::leftJoin('pbg_task_retributions as ptr', 'pbg_task.uuid', '=', 'ptr.pbg_task_uid')
                ->selectRaw('COUNT(DISTINCT pbg_task.id) as task_count, SUM(ptr.nilai_retribusi_bangunan) as total_retribution');

            if ($year !== 'all') {
                $query->whereYear('pbg_task.task_created_at', (int) $year);
            }

            return $query->first();
        });

        $potention_count = $query_potention->task_count ?? 0;
        $potention_total = $query_potention->total_retribution ?? 0;

        $query_spatial_plannings = once(function () use ($year) {
            $query = PbgTask::leftJoin('spatial_plannings as sp', 'pbg_task.document_number', '=', 'sp.number')
                ->leftJoin('pbg_task_retributions as ptr', 'ptr.pbg_task_uid', '=', 'pbg_task.uuid')
                ->selectRaw('
                    CASE 
                        WHEN COUNT(DISTINCT sp.id) > 0 THEN COUNT(DISTINCT sp.id)
                        ELSE (SELECT COUNT(*) FROM spatial_plannings) 
                    END as task_count,
                    SUM(CASE WHEN sp.id IS NOT NULL AND ptr.id IS NOT NULL THEN ptr.nilai_retribusi_bangunan ELSE 0 END) as total_retribution
                ');

            if ($year !== 'all') {
                $query->whereYear('pbg_task.task_created_at', (int) $year);
            }

            return $query->first();
        });

        $spatial_planning_count = $query_spatial_plannings->task_count ?? 0;
        $spatial_planning_total = $query_spatial_plannings->total_retribution;

        $potention_count -= $spatial_planning_count;
        $potention_total -= $spatial_planning_total;

        return self::create([
            'import_datasource_id' => $import_datasource_id,
            'spatial_count' => $spatial_planning_count,
            'spatial_sum' => $spatial_planning_total ?? 0.00,
            'potention_count' => $potention_count ?? 0,
            'potention_sum' => $potention_total ?? 0.00,
            'non_verified_count' => $non_verified_count ?? 0,
            'non_verified_sum' => $non_verified_total ?? 0.00,
            'verified_count' => $verified_count ?? 0,
            'verified_sum' => $verified_total ?? 0.00,
            'business_count' => $business_count ?? 0,
            'business_sum' => $business_total ?? 0.00,
            'non_business_count' => $non_business_count ?? 0,
            'non_business_sum' => $non_business_total ?? 0.00,
            'year' => $year,
            'waiting_click_dpmptsp_count' => $data_setting['MENUNGGU_KLIK_DPMPTSP_COUNT'] ?? 0,
            'waiting_click_dpmptsp_sum' => $data_setting['MENUNGGU_KLIK_DPMPTSP_SUM'] ?? 0.00,
            'issuance_realization_pbg_count' => $data_setting['REALISASI_TERBIT_PBG_COUNT'] ?? 0,
            'issuance_realization_pbg_sum' => $data_setting['REALISASI_TERBIT_PBG_SUM'] ?? 0.00,
            'process_in_technical_office_count' => $data_setting['PROSES_DINAS_TEKNIS_COUNT'] ?? 0,
            'process_in_technical_office_sum' => $data_setting['PROSES_DINAS_TEKNIS_SUM'] ??0.00,
        ]);
    }
}
