<?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\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");
        }

        try {
            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->tahun_data         = $data['tahun_data'];
                    // $masterModel->publik             = 1;
                    // $masterModel->template_default   = 1;
                    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->tahun_data         = $data['tahun_data'];
                    $masterModel->name               = $data['name'];
                    $masterModel->publik             = 1;
                    $masterModel->template_default   = 1;
                    $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;
            });
        }catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
            $failures = $e->failures();

            foreach ($failures as $failure) {
                // Kolom & baris error
                dump('Row: '.$failure->row());
                dump('Attribute: '.$failure->attribute());
                dump('Errors: ', $failure->errors()); 
                dump('Values: ', $failure->values());
            }

            return $failures;
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }

    public function getChartData($modelClass,$datasetId,$templateId)
    {
        $data = $modelClass::dataChart($modelClass,$datasetId,$templateId);        
        return $data;
    }
}