<?php

namespace App\Repositories\Eloquent;

use App\Models\Dataset;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;
use DB;
// use App\Models\Dataset\DatasetTable1;
// use App\Imports\DatasetTable1Import;
// use App\Models\Dataset\DatasetTable2;
// use App\Imports\DatasetTable2Import;
// use App\Models\Dataset\DatasetTable3;
// use App\Imports\DatasetTable3Import;
// use App\Models\Dataset\DatasetTable4;
// use App\Imports\DatasetTable4Import;
// use App\Models\Dataset\DatasetTable5;
// use App\Imports\DatasetTable5Import;
// use App\Models\Dataset\DatasetTable6;
// use App\Imports\DatasetTable6Import;
// use App\Models\Dataset\DatasetTable7;
// use App\Imports\DatasetTable7Import;
// use App\Models\Dataset\DatasetTable8;
// use App\Imports\DatasetTable8Import;
// use App\Models\Dataset\DatasetTable9;
// use App\Imports\DatasetTable9Import;
// use App\Models\Dataset\DatasetTable10;
// use App\Imports\DatasetTable10Import;
// use App\Models\Dataset\DatasetTable11;
// use App\Imports\DatasetTable11Import;
// use App\Models\Dataset\DatasetTable12;
// use App\Imports\DatasetTable12Import;
// use App\Models\Dataset\DatasetTable13;
// use App\Imports\DatasetTable13Import;
// use App\Models\Dataset\DatasetTable14;
// use App\Imports\DatasetTable14Import;
// use App\Models\Dataset\DatasetTable15;
// use App\Imports\DatasetTable15Import;
// use App\Models\Dataset\DatasetTable16;
// use App\Imports\DatasetTable16Import;
// use App\Models\Dataset\DatasetTable17;
// use App\Imports\DatasetTable17Import;
// use App\Models\Dataset\DatasetTable18;
// use App\Imports\DatasetTable18Import;
// use App\Models\Dataset\DatasetTable19;
// use App\Imports\DatasetTable19Import;
// use App\Models\Dataset\DatasetTable21;
// use App\Imports\DatasetTable21Import;
// use App\Models\Dataset\DatasetTable22;
// use App\Imports\DatasetTable22Import;
// use App\Models\Dataset\DatasetTable23;
// use App\Imports\DatasetTable23Import;
// use App\Models\Dataset\DatasetTable24;
// use App\Imports\DatasetTable24Import;
// use App\Models\Dataset\DatasetTable25;
// use App\Imports\DatasetTable25Import;
// use App\Models\Dataset\DatasetTable26;
// use App\Imports\DatasetTable26Import;
// use App\Models\Dataset\DatasetTable27;
// use App\Imports\DatasetTable27Import;
// use App\Models\Dataset\DatasetTable28;
// use App\Imports\DatasetTable28Import;
// use App\Models\Dataset\DatasetTable29;
// use App\Imports\DatasetTable29Import;
// use App\Models\Dataset\DatasetTable30;
// use App\Imports\DatasetTable30Import;
// use App\Models\Dataset\DatasetTable31;
// use App\Imports\DatasetTable31Import;
// use App\Models\Dataset\DatasetTable32;
// use App\Imports\DatasetTable32Import;
// use App\Models\Dataset\DatasetTable33;
// use App\Imports\DatasetTable33Import;
// use App\Models\Dataset\DatasetTable34;
// use App\Imports\DatasetTable34Import;
// use App\Models\Dataset\DatasetTable35;
// use App\Imports\DatasetTable35Import;
// use App\Models\Dataset\DatasetTable36;
// use App\Imports\DatasetTable36Import;
// use App\Models\Dataset\DatasetTable37;
// use App\Imports\DatasetTable37Import;
// use App\Models\Dataset\DatasetTable38;
// use App\Imports\DatasetTable38Import;
// use App\Models\Dataset\DatasetTable39;
// use App\Imports\DatasetTable39Import;
// use App\Models\Dataset\DatasetTable39A;
// use App\Imports\DatasetTable39AImport;
// use App\Models\Dataset\DatasetTable40;
// use App\Imports\DatasetTable40Import;
// use App\Models\Dataset\DatasetTable41;
// use App\Imports\DatasetTable41Import;
// use App\Models\Dataset\DatasetTable41A;
// use App\Imports\DatasetTable41AImport;
// use App\Models\Dataset\DatasetTable42;
// use App\Imports\DatasetTable42Import;
// use App\Models\Dataset\DatasetTable43;
// use App\Imports\DatasetTable43Import;
// use App\Models\Dataset\DatasetTable43A;
// use App\Imports\DatasetTable43AImport;
// use App\Models\Dataset\DatasetTable43B;
// use App\Imports\DatasetTable43BImport;
// use App\Models\Dataset\DatasetTable44;
// use App\Imports\DatasetTable44Import;
// use App\Models\Dataset\DatasetTable44A;
// use App\Imports\DatasetTable44AImport;
// use App\Models\Dataset\DatasetTable44B;
// use App\Imports\DatasetTable44BImport;
// use App\Models\Dataset\DatasetTable45;
// use App\Imports\DatasetTable45Import;
// use App\Models\Dataset\DatasetTable46;
// use App\Imports\DatasetTable46Import;
// use App\Models\Dataset\DatasetTable47;
// use App\Imports\DatasetTable47Import;
// use App\Models\Dataset\DatasetTable48;
// use App\Imports\DatasetTable48Import;
// use App\Models\Dataset\DatasetTable48A;
// use App\Imports\DatasetTable48AImport;
// use App\Models\Dataset\DatasetTable49;
// use App\Imports\DatasetTable49Import;
// use App\Models\Dataset\DatasetTable50;
// use App\Imports\DatasetTable50Import;
// use App\Models\Dataset\DatasetTable50A;
// use App\Imports\DatasetTable50AImport;
// use App\Models\Dataset\DatasetTable51;
// use App\Imports\DatasetTable51Import;
// use App\Models\Dataset\DatasetTable52;
// use App\Imports\DatasetTable52Import;
// use App\Models\Dataset\DatasetTable53;
// use App\Imports\DatasetTable53Import;
// use App\Models\Dataset\DatasetTable54;
// use App\Imports\DatasetTable54Import;
// use App\Models\Dataset\DatasetTable55;
// use App\Imports\DatasetTable55Import;
// use App\Models\Dataset\DatasetTable56;
// use App\Imports\DatasetTable56Import;
// use App\Models\Dataset\DatasetTable57;
// use App\Imports\DatasetTable57Import;
// use App\Models\Dataset\DatasetTable58;
// use App\Imports\DatasetTable58Import;
// use App\Models\Dataset\DatasetTable59;
// use App\Imports\DatasetTable59Import;
// use App\Models\Dataset\DatasetTable60;
// use App\Imports\DatasetTable60Import;
// use App\Models\Dataset\DatasetTable60A;
// use App\Imports\DatasetTable60AImport;
// use App\Models\Dataset\DatasetTable61;
use App\Repositories\Contracts\DatasetRepositoryInterface;

class DatasetRepository implements DatasetRepositoryInterface
{
    public function getAll()
    {
        return Dataset::all();
    }

    public function findById($id)
    {
        return Dataset::findOrFail($id);
    }

    public function create(array $data)
    {
        return Dataset::create($data);
    }

    public function update($id, array $data)
    {
        $model = Dataset::findOrFail($id);
        $model->update($data);
        return $model;
    }

    public function delete($id)
    {
        $model = Dataset::findOrFail($id);
        return $model->delete();
    }

    public function createDatasetTable(string $modelClass,string $importClass,$file,array $data)
    {
        
        // pastikan class model ada
        if (!class_exists($modelClass)) {
            throw new \Exception("Model {$modelClass} tidak ditemukan");
        }

        if (!class_exists($importClass)) {
            throw new \Exception("Import {$importClass} tidak ditemukan");
        }

        // dd($data);
        return DB::transaction(function () use ($modelClass, $importClass, $file, $data) {

            $keyId = decode_id($data['secure_id']);
            $json        = [];
            $filePath    = null;
            if(@$file){
                $file        = $file;
                $path        = $file->getRealPath();
                $spreadsheet = IOFactory::load($path);
                $sheet       = $spreadsheet->getActiveSheet();
                $rows        = $sheet->toArray();
                $header      = $rows[4]; // Baris pertama sebagai header
                if (@$file) {
                    $file = $data['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){
                                $key = strtolower(str_replace(' ', '_', $columnName));
                                $assoc[$key] = $row[$j] ?? null;
                            }
                        }

                        $json[] = $assoc;
                    }

                }
            }

            if(@$keyId){
                $masterModel = Dataset::find($keyId);
                $masterModel->instansi_id        = decode_id($data['instansi_id']);
                $masterModel->template_id        = decode_id($data['template_id']);
                $masterModel->name               = $data['name'];
                $masterModel->publik             = $data['publik'];
                $masterModel->tags               = json_encode($data['tags']);
                if(@$file){
                    $masterModel->data               = json_encode($json);
                    $masterModel->file               = $filePath;
                }
                $masterModel->deskripsi          = $data['deskripsi'];
                $masterModel->save();

                if(@$file){
                    $modelClass::where('dataset_id',$masterModel->DatasetId)->delete();
                }
            }else{
                $masterModel = new Dataset;
                $masterModel->instansi_id        = decode_id($data['instansi_id']);
                $masterModel->template_id        = decode_id($data['template_id']);
                $masterModel->tahun              = $data['tahun'];
                $masterModel->name               = $data['name'];
                $masterModel->publik             = $data['publik'];
                $masterModel->tags               = json_encode($data['tags']);
                $masterModel->data               = json_encode($json);
                $masterModel->file               = $filePath;
                $masterModel->deskripsi          = $data['deskripsi'];
                $masterModel->created_by         = auth()->user()->id;
                $masterModel->save();
            }

            if(@$file){
                Excel::import(new $importClass($masterModel->DatasetId,auth()->user()->id),$path.'/'.$newFilename);
            }

            return $masterModel;
        });
    }
}