<?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\DatasetTambahan;

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' => 'Open Data'],
            ['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){
            $data = DatasetTambahan::orderBy('DatasetId','DESC')->get();
        }else{
            $data = DatasetTambahan::orderBy('DatasetId','DESC')->whereIn('instansi_id',[auth()->user()->ms_instansi_id])->get();
        }
        // $data = User::with(['group'])->orderBy('id','DESC')->get();
        $_data = [];


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


            $action = '';

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<div class="flex gap-3 justify-center items-center flex-row">';
                if($row->created_by == auth()->user()->id){
                    $action .= '<a href="'.url('opendata/dataset-tambahan/update/'.encode_id($row->DatasetId)).'" data-toggle="tooltip" title="Ubah Data" class="btn btn-sm btn-block bg-primary"><i class="ri-pencil-line text-white"></i></a>';
                }
                $action .= '<a href="'.url('opendata/dataset-tambahan/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>';
                if(session('group_id') == 1){
                    // $action .= '<a href="#" data-href="'.url('management/user/forcelogin/'.encode_id($row->id)).'" data-toggle="tooltip" 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-tambahan/delete/'.encode_id($row->DatasetId)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data btn btn-sm btn-block bg-danger"><i class="ri-delete-bin-line text-white"></i></a>';
                    }else{
                        $action .= '<a href="#" data-href="'.url('opendata/dataset-tambahan/aktif/'.encode_id($row->DatasetId)).'" data-toggle="tooltip" title="Aktifkan Data" class="aktif_data btn btn-sm btn-block bg-success"><i class="ri-check-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);

    }

    /**
     * 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
                if (@$request->hasFile('file')) {
                    $file = $request->file('file');
                    $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')){
                        return redirect()->back()->with([
                            'message' => 'Maaf File Harus Berupa 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);
                

                
                    for ($i = 5; $i < count($rows); $i++) {
                        $row = $rows[$i];

                        // Skip baris kosong
                        if (collect($row)->filter()->isEmpty()) continue;

                        $assoc = [];
                        foreach ($header as $j => $columnName) {
                            if($columnName != null){
                                $assoc[strtolower(str_replace(' ','_',$columnName))] = $row[$j] ?? null;
                            }
                        }

                        $data[] = $assoc;
                    }

                }
            }


            if(@$keyId){
                Validator::make($request->all(), [
                    'name'        => 'required',
                    'instansi_id' => 'required',
                    'template_id' => 'required',
                    // 'template_default' => 'required',
                    'publik'      => 'required',
                    'tags'        => 'required',
                    'topik'       => 'required',
                ])->validate();
                
                $insert = DatasetTambahan::find($keyId);
                $insert->instansi_id        = decode_id($request->instansi_id);
                $insert->template_id        = decode_id($request->template_id);
                // $insert->template_default   = $request->template_default;
                $insert->name               = $request->name;
                $insert->publik             = $request->publik;
                $insert->tags               = json_encode($request->tags);
                if(@$request->hasFile('file')){
                    $insert->file               = $filePath;
                }
                $insert->deskripsi          = $request->deskripsi;
                $insert->tahun              = $request->tahun;
                $insert->save();
            }else{
                // 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 Dataset;
                $insert->instansi_id        = decode_id($request->instansi_id);
                $insert->template_id        = decode_id($request->template_id);
                $insert->template_default   = $request->template_default;
                $insert->tahun              = $request->tahun;
                $insert->name               = $request->name;
                $insert->publik             = $request->publik;
                $insert->tags               = json_encode($request->tags);
                $insert->file               = $filePath;
                $insert->deskripsi          = $request->deskripsi;
                $insert->created_by         = auth()->user()->id;
                $insert->save();
            }

            return redirect()->back()->with([
                    'message' => 'Berhasil update data',
                    'type'    => 'success',
                ]);
        } catch (Exception $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' => 'Open Data'],
            ['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_alias') == 'administrator'){
            $data['instansi'] = Instansi::all();
        }else{
            $data['instansi'] = Instansi::where('MsInstansiId',session('instansi_id'))->get();
        }
        
        $data['topik'] = Topik::all();
        $data['template'] = Template::all();
        return view($this->template.'.form',$data);
    }

    public function view($id = null)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Open Data'],
            ['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();

        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->save();

        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']);
    }
}
