<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Dataset;
use App\Models\DatasetTambahan;
use App\Models\Master\Topik;
use App\Models\Master\Instansi;
use App\Models\Master\Template;
use App\Models\Master\TabelData;
use App\Models\Master\Group;
use App\Repositories\Eloquent\DatasetRepository;

class HomeController extends Controller
{
    protected $template = 'modules.dashboard';
    protected $route = 'modules.dashboard';
    private $datasetRepository;

    public function __construct(DatasetRepository $datasetRepository){
        $this->middleware('auth');
        $this->repository = $datasetRepository;
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function dashboard()
    {
        $data['title']   = 'Dashboard';
        $data['route']   = $this->route;
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data['dataset'] = Dataset::orderBy('DatasetId','DESC')->where('tahun',date('Y'))->where('status',1)->count();
            $data['datasetTambahan'] = DatasetTambahan::where('status',1)->orderBy('DatasetId','DESC')->where('tahun',date('Y'))->count();
            $data['datasetInstansi'] = Instansi::selectRaw("
                                            SUM(
                                                CASE
                                                    WHEN resource_data IS NULL 
                                                        OR json_array_length(resource_data) = 0
                                                    THEN 1
                                                    ELSE json_array_length(resource_data)
                                                END
                                            ) as total_resource
                                        ")
                                        ->value('total_resource');
            $data['total'] = Instansi::join('dataset as d', 'd.instansi_id', '=', 'ms_instansi.MsInstansiId')
                                        ->whereRaw("ms_instansi.resource_data IS NOT NULL
                                        AND EXISTS (
                                            SELECT 1
                                            FROM jsonb_array_elements_text(ms_instansi.resource_data::jsonb) AS r(value)
                                            WHERE r.value = d.ms_tabel_data_id::text
                                        )
                                    ")->distinct('ms_instansi.MsInstansiId')
                                    ->count('ms_instansi.MsInstansiId');

        }else{
            $data['dataset'] = Dataset::where('status',1)->orderBy('DatasetId','DESC')->whereIn('instansi_id',[session('instansi_id')])->where('tahun',date('Y'))->count();
            $data['datasetTambahan'] = DatasetTambahan::where('status',1)->whereIn('instansi_id',[session('instansi_id')])->where('tahun',date('Y'))->count();
            $data['datasetInstansi'] = Instansi::where('MsInstansiId',session('instansi_id'))->selectRaw("
                                            SUM(
                                                CASE
                                                    WHEN resource_data IS NULL 
                                                        OR json_array_length(resource_data) = 0
                                                    THEN 1
                                                    ELSE json_array_length(resource_data)
                                                END
                                            ) as total_resource
                                        ")
                                        ->value('total_resource');
                                        
            $data['total'] = Dataset::where('instansi_id', session('instansi_id'))
                            ->where('status',1)
                            ->where('tahun',date('Y'))
                            ->whereIn('ms_tabel_data_id', json_decode(session('resource_data')))->count();
                            
            // $data['total'] = Instansi::where('MsInstansiId',session('instansi_id'))->join('dataset as d', 'd.instansi_id', '=', 'ms_instansi.MsInstansiId')
            //                             ->whereRaw("ms_instansi.resource_data IS NOT NULL
            //                             AND EXISTS (
            //                                 SELECT 1
            //                                 FROM jsonb_array_elements_text(ms_instansi.resource_data::jsonb) AS r(value)
            //                                 WHERE r.value = d.ms_tabel_data_id::text
            //                             )
            //                         ")->distinct('ms_instansi.MsInstansiId')
            //                         ->count('ms_instansi.MsInstansiId');
            
        }
        $data['instansi'] = Instansi::count();
        $data['tabelData'] = tabelData::count();

        return view($this->template.'.dashboard',$data);
    }

    public function dataset($alias)
    {
        $data['title']   = 'Dashboard';
        $data['dataset'] = Dataset::orderBy('DatasetId','DESC')->limit(10)->get();
        $data['group']   = Group::where('MsGroupId','!=',1)->get();
        $data['alias']   = $alias;

        return view($this->template.'.dataset',$data);
    }

    function gridInstansiUtama(Request $request){
        $instansi = Instansi::where('MsInstansiId',session('instansi_id'))->first();
        $data = TabelData::whereIn('MsTabelDataId',json_decode($instansi->resource_data))->get();

        $_data = [];
        foreach ($data as $key => $row) {
            //cek upload
            $status = '';
            $cek = Dataset::where('instansi_id',session('instansi_id'))->where('ms_tabel_data_id',$row->MsTabelDataId)->where('tahun',date('Y'))->first();
            if(@$cek){
                if(@$cek->status == 1){
                    $status = ' <small class="p-1 w-full flex bg-emerald-500 text-white rounded" title="Valid">Valid</small>';
                }elseif(@$cek->status == 0){
                    $status = '<small class="p-1 w-full flex bg-yellow-500 text-white rounded" title="Tidak Valid">Menunggu Verifikasi</small>';
                }elseif(@$cek->status == 2){
                    $status = '<small class="p-1 w-full flex bg-red-500 text-white rounded" title="Tidak Valid">Verifikasi Ditolak</small>';
                }
                $action = '';
            }else{
                $status = '<span class="flex bg-red-500 rounded w-100 p-1 text-[10px] text-white">Belum Unggah</spa>';
                $action = '<a href="'.url('opendata/dataset/update').'" title="Buat Dataset" class="flex p-2 rounded  bg-emerald-500 text-white"><i class="ri-add-line"></i></a>';
            }

            $_data[] = [
                'no'                => $key+1,
                'action'            => $action,
                'name'              => 'Tabel '.@$row->nomor_tabel.' - '.@$row->name,
                'pic'               => @$row->pic,
                'status'            => @$status,
            ];
        }   

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

    function gridInstansiTambahan(Request $request){
        $data = DatasetTambahan::whereIn('instansi_id',[session('instansi_id')])->get();

        $_data = [];
        foreach ($data as $key => $row) {

            $_data[] = [
                'no'                => $key+1,
                'name'              => @$row->name,
            ];
        }   

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

    public function gridTabel(Request $request)
    {
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data = Instansi::all();
        }else{
            $data = Instansi::where('MsInstansiId',session('instansi_id'))->get();
        }
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];

        foreach ($data as $key => $row) {

            $resource = json_decode($row->resource_data);
            $countresource = @$resource ? count($resource) : '0';
            $dataset = 0;
            if(@$resource){
                $dataset = Dataset::where('instansi_id',$row->MsInstansiId)->where('status',1)->whereIn('ms_tabel_data_id',$resource)->where('tahun',date('Y'))->count();
            }
            $persentase = $countresource > 0 ? round(($dataset/$countresource)*100) : '0';
            $btn = '<a href="#" data-id="'.encode_id($row->MsInstansiId).'" data-name="'.$row->name.'" class="p-2 rounded btnModal bg-blue-500 text-white">'.$dataset.'/'.$countresource.'</a>';
            if($persentase == 0){
                $percent = '<span class="p-2 rounded bg-red-500 text-white">'.$persentase.'%</span>';
            }elseif($persentase > 0 && $persentase <= 50){
                $percent = '<span class="p-2 rounded bg-yellow-500 text-white">'.$persentase.'%</span>';
            }else{
                $percent = '<span class="p-2 rounded bg-emerald-500 text-white">'.$persentase.'%</span>';
            }
                
            $_data[] = [
                'no'                => $key+1,
                'name'              => @$row->name,
                // 'dataset'           => tabelInstansi(@$row->MsInstansiId),
                'dataset'           => $btn,
                'persentase'        => $percent,
            ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    public function grid(Request $request)
    {
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data = Dataset::orderBy('DatasetId','DESC')->limit(10)->get();
        }else{
            $data = Dataset::orderBy('DatasetId','DESC')->limit(10)->whereIn('created_by',[auth()->user()->id,1])->get();
        }
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];

        foreach ($data as $key => $row) {

                $action = '';
                $action .= '<div class="flex gap-3 justify-center items-center flex-row">';
                $action .= '<a href="'.url('opendata/dataset/view/'.encode_id($row->DatasetId)).'" data-toggle="tooltip" title="Lihat Data" class="btn btn-sm btn-block bg-info"><i class="ri-eye-line text-white"></i></a>';
                $action .= '</div>';
                $status = '';
                
                if($row->status == 1){
                    $status = '<small class="p-1 w-full bg-success text-white rounded" title="Aktif"><i class="ri-check-line"></i></small>';
                }else{
                    $status = '<small class="p-1 w-full bg-danger text-white rounded" title="Tidak Aktif"><i class="ri-close-line"></i></small>';
                }
                
            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'name'              => @$row->name,
                'publik'            => @$row->publik,
                'tahun'            => @$row->tahun,
                'created_at'            => date('d-m-Y H:i:s',strtotime(@$row->created_at)),
                'instansi'            => @$row->instansi->name,
                'action'            => @$action,
                'status'            => @$status,
            ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    public function gridResource(Request $request)
    {
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data = TabelData::with(['dataset'])->where('show_dashboard',1)->get();
        }else{
            $data = TabelData::with(['dataset'])->whereHas('dataset',function($query){
                $query->where('instansi_id',session('instansi_id'));
            })->where('show_dashboard',1)->get();
        }
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];

        foreach ($data as $key => $row) {

                $action = '';
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
                    $action .= '<a href="'.url('dashboard/dataset/resource/'.encode_id($row->MsTemplateId)) .'" class="btn w-full bg-success text-white">Lihat Data</a>';
                }else{
                    $action .= '<a href="'.url('dashboard/dataset/resource/instansi/'.encode_id(session('instansi_id')).'/'.encode_id($row->MsTemplateId)).'" class="btn w-full bg-success text-white">Lihat Data</a>';
                }
                
            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'name'              => @$row->name,
                'jumlah'            => $row->dataset->count(),
                'action'            => @$action,
            ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    public function datasetGrid($alias,Request $request)
    {
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data = Dataset::whereHas('instansi',function($query) use ($alias){
                $query->where('parent','ilike','%'.$alias.'%');
            })->orderBy('DatasetId','DESC')->get();
        }else{
            $data = Dataset::whereHas('instansi',function($query) use ($alias){
                $query->where('parent','ilike','%'.$alias.'%');
            })->orderBy('DatasetId','DESC')->whereIn('created_by',[auth()->user()->id,1])->get();
        }
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];

        foreach ($data as $key => $row) {

                $action = '';
                $action .= '<div class="flex gap-3 justify-center items-center flex-row">';
                $action .= '<a href="'.url('opendata/dataset/view/'.encode_id($row->DatasetId)).'" data-toggle="tooltip" title="Lihat Data" class="btn btn-sm btn-block bg-info"><i class="ri-eye-line text-white"></i></a>';
                $action .= '</div>';
                $status = '';
                
                if($row->status == 1){
                    $status = '<small class="p-1 w-full bg-success text-white rounded" title="Aktif"><i class="ri-check-line"></i></small>';
                }else{
                    $status = '<small class="p-1 w-full bg-danger text-white rounded" title="Tidak Aktif"><i class="ri-close-line"></i></small>';
                }
                
            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->id),
                'name'              => @$row->name,
                'publik'            => @$row->publik,
                'tahun'            => @$row->tahun,
                'created_at'            => date('d-m-Y H:i:s',strtotime(@$row->created_at)),
                'instansi'            => @$row->instansi->name,
                'action'            => @$action,
                'status'            => @$status,
            ];

        }

        // return response()->json($_data);  // Return the data as a JSON response
        return response()->json($_data);

    }

    function resource($id){
        $keyId = decode_id($id);
        $data['id'] = $id;

        $data['title']   = 'Dashboard';
        $data['dataset']  = Dataset::where('template_id',$keyId)->pluck('instansi_id')->toArray();
        $data['instansi']  = Instansi::whereIn('MsInstansiId',$data['dataset'])->paginate(9);

        return view($this->template.'.resource',$data);
    }
    function resource_instansi($instansi_id,$id){
        $data['id']          = decode_id($id);
        $data['instansi_id'] = decode_id($instansi_id);
        $data['dataset']     = Dataset::with(['template'])->where('instansi_id',decode_id($instansi_id))->where('template_id',decode_id($id))->first();
        $data['template']    = TabelData::where('MsTemplateId',decode_id($id))->first();
        $data['title']       = 'Dashboard '.@$data['dataset']->template->name;

        return view($this->template.'.resource_detail',$data);
    }

    function apiChart($templateId,$instansi_id){
        $template   = TabelData::where('MsTemplateId',decode_id($templateId))->first();
        $dataset    = Dataset::with(['template'])->where('instansi_id',decode_id($instansi_id))->where('template_id',decode_id($templateId))->first();
        $filename   = pathinfo($template->template_url, PATHINFO_FILENAME); 
        $modelClass = "App\\Models\\Dataset\\Dataset" . ucfirst($filename);
        $insert     = $this->repository->getChartData($modelClass,$dataset->DatasetId,decode_id($templateId));

        return $insert;
    }
}
