<?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\DatasetTambahan;
use App\Models\DatasetCatatan;

class DatasetTambahanController extends Controller
{
    protected $title = 'Dataset Tambahan';
    protected $template = 'modules.opendata.dataset-tambahan';
    protected $route = 'modules.opendata.dataset-tambahan';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        permission('is_read', $this->route, 'module',true);
        
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Dataset SLHD'],
            ['name' => 'Dataset Tambahan','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);
        $item = DatasetTambahan::find($keyId); // atau pakai ->pluck(), ->find(), dll

        $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 = DatasetTambahan::with(['tabelData']);
        }else{
            $data = DatasetTambahan::with(['tabelData'])->whereIn('instansi_id',[session('instansi_id')]);
        }
        if(@$request->tahun){
            $data->where('tahun',$request->tahun);
        }else{
            $data->where('tahun',date('Y'));
        }
        $data->orderBy('DatasetTambahanId','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-tambahan/update/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" title="Ubah Data" class="p-2 rounded text-white bg-blue-500">Edit</a>';
                    }
                }
                $action .= '<a href="'.url('opendata/dataset-tambahan/view/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" 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-tambahan/update/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" title="Ubah Data" class="p-2 rounded text-white bg-blue-500">Edit</a>';
                    $action .= '<a href="#" data-href="'.url('opendata/dataset-tambahan/delete/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data p-2 rounded text-white bg-red-500">Hapus</a>';
                    // $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" data-toggle="tooltip" title="Force Login" class="forcelogin p-2 rounded text-white bg-success"><i class="ri-user-2-line text-white"></i></a>';
                    if($row->status == 1){
                        // $action .= '<a href="#" data-href="'.url('opendata/dataset-tambahan/delete/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data p-2 rounded text-white bg-red-500"><i class="ri-delete-bin-line text-white"></i></a>';
                    }else{
                        // $action .= '<a href="#" data-href="'.url('opendata/dataset-tambahan/aktif/'.encode_id($row->DatasetTambahanId)).'" data-toggle="tooltip" title="Aktifkan Data" class="aktif_data p-2 rounded text-white bg-emerald-500"><i class="ri-check-line text-white"></i></a>';
                    }
                }
                $action .= '</div>';
            }
            $status = '';
            if($row->status == 1){
                $status = '<small class="p-1 w-full items-center justify-center flex bg-emerald-500 text-white rounded" title="Valid">Valid</small>';
            }elseif($row->status == 0){
                $status = '<small class="p-1 w-full items-center justify-center flex bg-yellow-500 text-white rounded" title="Tidak Valid">Menunggu Verifikasi</small>';
            }elseif($row->status == 2){
                $status = '<small class="p-1 w-full items-center justify-center 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->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);
            $data        = [];
            $filePath    = null;
            if(@$request->file){
                $file        = $request->file('file');
                $path        = $file->getRealPath();
                // $spreadsheet = IOFactory::load($path);
                // $sheet       = $spreadsheet->getActiveSheet();
                // $rows        = $sheet->toArray();
                // $header      = $rows[4]; // Baris pertama sebagai header
                
                $destinationPath = public_path('uploads/dataset');
                $current = Carbon::now()->format('Y/m/d');
                $path = $destinationPath . '/' . $current;
                $fileName = $file->getClientOriginalName();
                $fileMime = $file->getClientMimeType();
                $fileExtension = $file->getClientOriginalExtension();
                $fileSize = $file->getSize();
                if(($fileExtension != 'xls') && ($fileExtension != 'xlsx') && ($fileExtension != 'pdf') && ($fileExtension != 'docx')){
                    return redirect()->back()->with([
                        'message' => 'Maaf File Harus Berupa pdf,docx,xls,xlsx!',
                        'type'    => "error"
                    ]);   
                }
                $newFilename = session('id').'_'.uniqid('file_') . '.' . $fileExtension;

                if (!File::exists($path)) {
                    File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                }

                $filePath = 'dataset/' . $current . '/' . $newFilename;
                $uploaded = $file->move($path, $newFilename);
            }


            if(@$keyId){
                
                $insert = DatasetTambahan::find($keyId);
                $insert->name               = $request->name;
                if(@$request->hasFile('file')){
                    $insert->file               = $filePath;
                }
                $insert->deskripsi          = $request->deskripsi;
                $insert->tahun_data         = $request->tahun_data;
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){

                }else{
                    $insert->status             = 0;
                }
                $insert->save();
            }else{
                if(!@$request->hasFile('file')){
                    return redirect()->back()->with([
                        'message' => 'File Harus Diupload',
                        'type'    => "error"
                    ]);
                }
                // dd($request->all());
                Validator::make($request->all(), [
                    // 'name'        => 'required',
                    // 'instansi_id' => 'required',
                    // 'template_id' => 'required',
                    // 'template_default' => 'required',
                    // 'publik'      => 'required',
                    // 'tags'        => 'required',
                    // 'file'        => 'required|file',
                    // 'topik'       => 'required',
                ])->validate();
                
            
                $insert = new DatasetTambahan;
                $insert->instansi_id        = decode_id($request->instansi_id);
                $insert->template_id        = decode_id($request->template_id);
                $insert->template_default   = 0;
                $insert->name               = $request->name;
                $insert->publik             = 1;
                $insert->tags               = json_encode($request->tags);
                if(@$request->hasFile('file')){
                    $insert->file           = $filePath;
                }
                if((session('group_id') == 1) || (session('group_alias') == 'admin') || (session('group_alias') == 'admin_ta') ){
                    $insert->status         = 1;
                }else{
                    $insert->status         = 0;
                }
                $insert->deskripsi          = $request->deskripsi;
                $insert->tahun              = $request->tahun;
                $insert->tahun_data         = $request->tahun_data;
                $insert->created_by         = auth()->user()->id;
                $insert->save();
            }

            return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);
        } catch (\Throwable $e) {
            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 SLHD'],
            ['name' => 'Dataset Tambahan','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = DatasetTambahan::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['template'] = TabelData::all();
        return view($this->template.'.form',$data);
    }

    public function view($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Dataset SLHD'],
            ['name' => 'Dataset Tambahan','active' => true],
        ];
        $keyId = decode_id($id);
        $data['title'] = $this->title;
        $data['route'] = $this->route;
        $data['keyId'] = $id;
        $data['item'] = DatasetTambahan::find($keyId);
        $data['instansi'] = Instansi::all();
        $data['topik'] = Topik::all();
        $data['template'] = Template::all();
        $data['catatan'] = DatasetCatatan::where('dataset_id',$keyId)->orderBy('created_at','DESC')->first();

        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 = DatasetTambahan::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 = DatasetTambahan::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 = DatasetTambahan::find($keyId);
        $dataset->status = $request->verifikasi;
        $dataset->save();

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

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