<?php

namespace App\Http\Controllers\Modules\Konten;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
use App\Models\Konten\Kegiatan;

class KegiatanController extends Controller
{

    private $template = 'modules.konten.kegiatan';
    private $route = 'modules.konten.kegiatan';
    private $title = 'Konten Kegiatan';

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Konten'],
            ['name' => 'Kegiatan','active' => true],
        ];

        $data['route'] = $this->route;
        $data['title'] = $this->title;

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

    public function grid(Request $request)
    {
        $data = Kegiatan::all();
        
        
        foreach ($data as $key => $row) {

            $action = '';

            if((permission('is_create', $this->route.'.*','module',false)) || (permission('is_update', $this->route.'.*','module',false))){
                $action .= '<a href="'.url('konten/kegiatan/update/'.encode_id($row->KegiatanId)).'" data-toggle="tooltip" title="Edit Data" class="btn btn-xs btn-block btn-primary"><i class="fal fa-pencil text-white"></i></a>';
                $action .= '<a href="#" data-href="'.url('konten/kegiatan/delete/'.encode_id($row->KegiatanId)).'" data-toggle="tooltip" title="Hapus Data" class="remove_data btn btn-xs btn-block btn-danger"><i class="fal fa-trash text-white"></i></a>';
            }
            $image = json_decode($row->image);

            $_data[] = [
                'no'                => $key+1,
                'id'                => encode_id($row->KegiatanId),
                'judul'             => $row->judul,
                'created_at'        => dateTime($row->created_at),
                'image'             => '<image src="'.asset($image[0]).'" width="80">',
                'action'            => $action,
            ];

        }

        return response()->json($_data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Konten'],
            ['name' => 'Kegiatan','url' => url('konten/kegiatan')],
            ['name' => 'Tambah Kegiatan','active' => true],
        ];

        $data['route'] = $this->route;
        $data['title'] = $this->title;

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());
        try {
            if(@$request->secure_id){
                $keyId = decode_id($request->secure_id);
                $keg = Kegiatan::find($keyId);
                $keg->slug = \Str::slug($request->judul);
                $keg->judul = $request->judul;
                $keg->kategori = $request->kategori;
                $keg->body = $request->body;

                if(@$request->input_upload_files){

                    $filePaths = [];
                    if(is_array(@$request->input_upload_files)){

                        $oldImages = json_decode($keg->image, true) ?? [];
                        foreach (@$request->input_upload_files as $file) {
                            $tempPath = storage_path('app/tmp_uploads/' . $file);

                            if (file_exists($tempPath)) {
                                $path = public_path('uploads/kegiatan/' . date('Y') );
                                if (!File::exists($path)) {
                                    File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                                }

                                $newPath = 'uploads/kegiatan/'.date('Y').'/'.$file;
                                copy($tempPath, public_path($newPath));
                                $newfilePaths[] = $newPath;
                            }
                        }

                        // gabungkan file lama + file baru
                        $filePaths = array_merge($oldImages, $newfilePaths);
                    }else{
                        $tempPath = storage_path('app/tmp_uploads/' . @$request->input_upload_files);

                        if (file_exists($tempPath)) {
                            $path = public_path('uploads/kegiatan/' . date('Y') );
                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kegiatan/'.date('Y').'/'.@$request->input_upload_files;
                            copy($tempPath, public_path($newPath));
                            $filePaths[] = $newPath;
                        }
                    }
                        
                        $path = $filePaths;
                        $keg->image = json_encode($path);
                }
                $keg->save();
            }else{
                $keg = new Kegiatan;
                $keg->slug = \Str::slug($request->judul);
                $keg->judul = $request->judul;
                $keg->kategori = $request->kategori;
                $keg->body = $request->body;

                // if (@$request->hasFile('image')) {
                //     $file = $request->file('image');
                //     $destinationPath = public_path('uploads/kegiatan');
                //     $current = Carbon::now()->format('Y/m/d');
                //     $path = $destinationPath . '/' . $current;
                //     $fileName = $file->getClientOriginalName();
                //     $fileMime = $file->getClientMimeType();
                //     $fileExtension = $file->getClientOriginalExtension();
                //     $fileSize = $file->getSize();
                //     if(($fileExtension != 'jpg') && ($fileExtension != 'jpeg') && ($fileExtension != 'png')){                        
                //         return redirect()->back()->with([
                //             'message' => 'Maaf File Harus Berupa PNG,JPEG,JPG!',
                //             'type'    => "error"
                //         ]);   
                //     }
                //     $newFilename = session('id').'_'.uniqid('file_') . '.' . $fileExtension;

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

                //     $filePathTim = 'kegiatan/' . $current . '/' . $newFilename;
                //     $uploaded = $file->move($path, $newFilename);
                //     $keg->image = $filePathTim;
                // }

                if(@$request->input_upload_files){

                    $filePaths = [];
                    if(is_array(@$request->input_upload_files)){
                        foreach (@$request->input_upload_files as $file) {
                            $tempPath = storage_path('app/tmp_uploads/' . $file);

                            if (file_exists($tempPath)) {
                                $path = public_path('uploads/kegiatan/' . date('Y') );
                                if (!File::exists($path)) {
                                    File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                                }

                                $newPath = 'uploads/kegiatan/'.date('Y').'/'.$file;
                                copy($tempPath, public_path($newPath));
                                $filePaths[] = $newPath;
                            }
                        }
                    }else{
                        $tempPath = storage_path('app/tmp_uploads/' . @$request->input_upload_files);

                        if (file_exists($tempPath)) {
                            $path = public_path('uploads/kegiatan/' . date('Y') );
                            if (!File::exists($path)) {
                                File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
                            }

                            $newPath = 'uploads/kegiatan/'.date('Y').'/'.@$request->input_upload_files;
                            copy($tempPath, public_path($newPath));
                            $filePaths[] = $newPath;
                        }
                    }
                        
                        $path = $filePaths;
                        $keg->image = json_encode($path);
                }
                
                $keg->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)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Konten'],
            ['name' => 'Kegiatan','url' => url('konten/kegiatan')],
            ['name' => 'Edit Kegiatan','active' => true],
        ];

        $data['route'] = $this->route;
        $data['title'] = $this->title;
        $data['item'] = Kegiatan::find(decode_id($id));

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

    /**
     * Update the specified resource in storage.
     */
    public function update($id)
    {
        $data['breadcrumbs'] = [
            ['name' => 'Dashboard','url' => url('dashboard')],
            ['name' => 'Konten'],
            ['name' => 'Kegiatan','url' => url('konten/kegiatan')],
            ['name' => 'Tambah Kegiatan','active' => true],
        ];

        $data['route'] = $this->route;
        $data['title'] = $this->title;
        $data['item'] = Kegiatan::find(decode_id($id));
        $data['keyId'] = $id;

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

    /**
     * Remove the specified resource from storage.
     */
    public function delete($id)
    {
        $keyId = decode_id($id);
        $form = Kegiatan::where('KegiatanId',$keyId)->delete();

        return response()->json(['success' => true,'message' => 'Berhasil update data','type' => 'success']);
    }
    function imageDelete(Request $request,$id){
        $keyId = decode_id($id);
        $keg = Kegiatan::where('KegiatanId',$keyId)->first();

        // Ambil nama file yang mau dihapus
        $fileToDelete = $request->url; // contoh: 'uploads/kegiatan/2025/file2.pdf'

        // Ambil data lama
        $images = json_decode($keg->image, true) ?? [];

        // Cari dan hapus dari array
        $newImages = array_filter($images, function ($img) use ($fileToDelete) {
            return $img !== $fileToDelete;
        });

        // Hapus file fisik juga
        $fullPath = public_path($fileToDelete);
        if (File::exists($fullPath)) {
            File::delete($fullPath);
        }

        // Simpan array baru ke DB
        $keg->image = json_encode(array_values($newImages)); // reset index array
        $keg->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Image deleted successfully',
        ]);    
    }
}
