<?php

namespace App\Http\Controllers\Opendata;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Models\Master\Instansi;
use App\Models\Master\Topik;
use App\Models\Master\Template;
use App\Models\Master\TabelData;
use App\Models\Master\TabelDataKolom;
use App\Models\Dataset;
use App\Models\DatasetCatatan;
use App\Models\TxDataset;
use App\Repositories\Eloquent\DatasetRepository;
use DB;
use Excel;
use App\Imports\Import;

class DatasetController extends Controller
{
    protected $title        = 'Dataset Utama';
    protected $template     = 'modules.opendata.dataset';
    protected $route        = 'modules.opendata.dataset';
    private $datasetRepository;

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

    public function index()
    {
        permission('is_read', $this->route, 'module',true);
        
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Dataset Utama'],
            ['name' => 'Dataset','active' => true],
        ];
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        return view($this->template.'.index',$data);
    }

    public function gridDetail(Request $request)
    {
        $id = $request->query('id'); 
        $keyId = decode_id($id);
        $limit  = $request->get('limit', 10);
        $offset = $request->get('offset', 0);

        $item = Dataset::find($keyId); // atau pakai ->pluck(), ->find(), dll
        // 
        $_data = [];
        $data = TxDataset::where('dataset_id', $keyId)
            ->orderBy('row_id')
            ->orderBy('ms_tabel_data_kolom_id')
            ->get()
            ->groupBy('row_id');
        $total = $data->count();
        $data = $data->slice($offset, $limit);

        foreach ($data as $rowId => $rows) {

            $rowData = [
                'no' => $rowId
            ];

            foreach ($rows as $cell) {
                $rowData[$cell->ms_tabel_data_kolom_id] = $cell->value;
            }

            $_data[] = $rowData;
        }

        return response()->json([
            'total' => $total,
            'rows' => array_values($_data)
        ]);
        

        // $json = json_decode($item->data, true);
        // $limit = $request->input('limit', 10);
        // $offset = $request->input('offset', 0);

        

        // $rows = array_slice($json, $offset, $limit);
        // return response()->json([
        //     'total' => count($json),
        //     'rows' => $rows
        // ]);

    }

    public function grid(Request $request)
    {
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data = Dataset::with(['tabelData']);
        }else{
            $data = Dataset::with(['tabelData'])->whereIn('instansi_id',[session('instansi_id')]);
        }
        if(@$request->tahun){
            $data->where('tahun',$request->tahun);
        }else{
            $data->where('tahun',date('Y'));
        }
        $data->orderBy('DatasetId','DESC');
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];


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


            $action = '';

            if(access('is_read', $this->route.'.*','module',false)){
                $action .= '<div class="flex gap-1 justify-center items-center flex-row">';

                if((access('is_update', $this->route.'.*','module',false))){
                    if(($row->created_by == auth()->user()->id) && ($row->status == 2)){
                        $action .= '<a href="'.url('opendata/dataset/update/'.encode_id($row->DatasetId)).'" title="Ubah Data" class="p-2 w-full rounded text-white bg-blue-600">Edit</a>';
                    }
                }
                $action .= '<a href="'.url('opendata/dataset/view/'.encode_id($row->DatasetId)).'" title="Lihat Data" class="p-2 w-full rounded text-white bg-slate-600">Detail</a>';
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){

                    $action .= '<a href="'.url('opendata/dataset/update/'.encode_id($row->DatasetId)).'" title="Ubah Data" class="p-2 w-full rounded text-white bg-blue-600">Edit</a>';
                    $action .= '<a href="#" data-href="'.url('opendata/dataset/delete/'.encode_id($row->DatasetId)).'" title="Hapus Data" class="remove_data p-2 w-full rounded bg-red-600 text-white">Hapus</a>';

                    // $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" title="Force Login" class="forcelogin btn btn-sm btn-block bg-success"><i class="ri-user-2-line text-white"></i></a>';
                    if($row->status == 1){
                        // $action .= '<a href="#" data-href="'.url('opendata/dataset/delete/'.encode_id($row->DatasetId)).'" title="Hapus Data" class="remove_data p-2 w-full rounded bg-red-600 text-white">Tolak Verifikasi</a>';
                    }else{
                        // $action .= '<a href="#" data-href="'.url('opendata/dataset/aktif/'.encode_id($row->DatasetId)).'" title="Aktifkan Data" class="aktif_data p-2 w-full rounded bg-emerald-600 text-white">Verifikasi</a>';
                    }
                }
                $action .= '</div>';
            }
            $status = '';
            if($row->status == 1){
                $status = '<small class="p-1 w-full flex bg-emerald-500 text-white rounded" title="Valid">Valid</small>';
            }elseif($row->status == 0){
                $status = '<small class="p-1 w-full flex bg-yellow-500 text-white rounded" title="Tidak Valid">Menunggu Verifikasi</small>';
            }elseif($row->status == 2){
                $status = '<small class="p-1 w-full flex bg-red-500 text-white rounded" title="Tidak Valid">Verifikasi Ditolak</small>';
            }
            
           $_data[] = [
            'no'                => $key+1,
            'id'                => encode_id($row->id),
            'name'              => @$row->name,
            'publik'            => @$row->publik,
            'tahun'             => @$row->tahun,
            'template'          => (@$row->tahun == '2026' ? @$row->tabelData->name : '-'),
            'created_at'        => date('d-m-Y',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);

    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd(request()->all());
        try {
            $keyId = decode_id($request->secure_id);
            DB::beginTransaction();
            if(@$keyId){
                //INSERT DATASET;
                    $dataset = Dataset::find($keyId);
                    $dataset->tahun              = $request->tahun;
                    $dataset->tahun_data         = $request->tahun_data;
                    $dataset->name               = $request->name;
                    $dataset->deskripsi          = $request->deskripsi;
                    if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){

                    }else{
                        $dataset->status             = 0;
                    }
                    $dataset->save();
                
            }else{
                //INSERT DATASET;
                    $dataset = new Dataset;
                    $dataset->instansi_id        = decode_id($request->instansi_id);
                    $dataset->ms_tabel_data_id   = decode_id($request->template_id);
                    $dataset->tahun              = $request->tahun;
                    $dataset->tahun_data         = $request->tahun_data;
                    $dataset->name               = $request->name;
                    $dataset->publik             = 1;
                    $dataset->template_default   = 1;
                    $dataset->data               = null;
                    $dataset->file               = null;
                    $dataset->deskripsi          = $request->deskripsi;
                    if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
                        $dataset->status             = 1;
                    }else{
                        $dataset->status             = 0;
                    }
                    
                    $dataset->created_by         = auth()->user()->id;
                    $dataset->save();
            }

            if(@$request->file){
                // dd($dataset);
                $tabelData = TabelData::find($dataset->ms_tabel_data_id);
                // dd($tabelData);

                $import = new Import;
                Excel::import($import, $request->file('file'));
                $data = $import->getData();
                $count = 0;
                // dd($data);
                foreach ($data as $rowIndex => $row) {
                    $rowId = $row[preg_replace('/[^a-z0-9]+/', '_', strtolower($tabelData->name)).'_'.date('Y')-1];
                    unset($row[preg_replace('/[^a-z0-9]+/', '_', strtolower($tabelData->name)).'_'.date('Y')-1]);
                    $count++;
                    foreach ($row as $columnIndex => $value) {
                            TxDataset::updateOrCreate([
                            'dataset_id' => $dataset->DatasetId,
                            'row_id'     => $rowIndex + 1, // nomor baris
                            'ms_tabel_data_kolom_id' => $columnIndex,
                        ],[
                            'dataset_id'       => $dataset->DatasetId,
                            'ms_tabel_data_id' => $dataset->ms_tabel_data_id,
                            'row_id'           => $rowIndex + 1,
                            'ms_tabel_data_kolom_id' => $columnIndex,
                            'value'            => $value,
                        ]);
                    }
                }
            }

            DB::commit();

            return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);

        } catch (\Throwable $e) {
            DB::rollback();
            return redirect()->back()->with([
                     'message' => $e->getMessage(),
                     'type'    => "error"
                ]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Dataset Utama'],
            ['name' => 'Dataset','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = 'Form '.$this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = Dataset::find($keyId);
        if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
            $data['instansi'] = Instansi::all();
        }else{
            $data['instansi'] = Instansi::where('MsInstansiId',session('instansi_id'))->get();
        }
        
        
        $data['topik'] = Topik::all();
        $data['tabel'] = TabelData::all();
        return view($this->template.'.form',$data);
    }

    public function view($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Dataset Utama'],
            ['name' => 'Dataset','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = Dataset::find($keyId);

        $template = TabelData::find($data['item']->ms_tabel_data_id);
        $data['catatan'] = DatasetCatatan::where('dataset_id',$keyId)->orderBy('DatasetCatatanId','DESC')->first();
        $data['tabel'] = TabelDataKolom::where('ms_tabel_data_id',$template->MsTabelDataId)->orderBy('order','ASC')->get();
        // $filename = pathinfo($tabelData->template_url, PATHINFO_FILENAME); 
        // $data['modelClass'] = "App\\Models\\Dataset\\Dataset" . ucfirst($filename);

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

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

    public function delete($id)
    {
        $keyId = decode_id($id);
        $dataset = Dataset::find($keyId);
        // $dataset->status = 0;
        $dataset->delete();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }
    public function aktif($id)
    {
        $keyId = decode_id($id);
        $dataset = Dataset::find($keyId);
        $dataset->status = 1;
        $dataset->save();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }
    public function verifikasi(Request $request,$id)
    {
        $keyId = decode_id($id);
        $dataset = Dataset::find($keyId);
        $dataset->status = $request->verifikasi;
        $dataset->save();

        if($request->catatan){
            $cat = new DatasetCatatan;
            $cat->dataset_id = $keyId;
            $cat->type = 'dataset';
            $cat->catatan = $request->catatan;
            $cat->status = 1;
            $cat->save();
        }

        return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);
    }

    function generateTemplate($id){
        $keyId = decode_id($id);

        if(@$keyId){
            $data['tabel'] = TabelData::find($keyId);
            $data['kolom'] = TabelDataKolom::where('ms_tabel_data_id',$keyId)->orderBy('order','ASC')->get();

            return view($this->template.'.template',$data);
        }else{
            return redirect()->back()->with([
                    'message' => 'Silahkan Pilih Instansi dan Template Tabel Terlebih Dahulu',
                    'type'    => 'error',
                ]);
        }

        
    }

    function download($id){
        $keyId = decode_id($id);

        $data['dataset'] = Dataset::with(['tabelData'])->find($keyId);
        $data['txdataset'] =TxDataset::where('dataset_id', $keyId)
            ->orderBy('row_id')
            ->orderBy('ms_tabel_data_kolom_id')
            ->get()
            ->groupBy('row_id');

        $data['tabel'] = TabelDataKolom::where('ms_tabel_data_id',$data['dataset']->ms_tabel_data_id)->orderBy('order','ASC')->get();

        // $data['tabel'] = TabelData::find($keyId);
        // $data['kolom'] = TabelDataKolom::where('ms_tabel_data_id',$keyId)->orderBy('order','ASC')->get();

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