<?php

namespace App\Http\Controllers;

use App\Models\InvoiceSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class GetController extends Controller
{
    public function getSignaturePosition(Request $request)
    {
        $data = InvoiceSetting::with('relation1')->where('name', $request->name)->first();

        if (!$data) {
            return response(['message' => 'Setting not found'], 404);
        }

        // Konversi signature_img pada relation1 menjadi base64 jika ada
        if ($data->relation1) {
            // Jika relation1 adalah array atau Collection
            if (is_array($data->relation1) || $data->relation1 instanceof Collection) {
                foreach ($data->relation1 as $item) {
                    if (isset($item->signature_img) && !empty($item->signature_img)) {
                        try {
                            $path = $item->signature_img;
                            if (Storage::exists($path)) {
                                $base64 = base64_encode(Storage::get($path));
                                $item->signature_img = 'data:image/png;base64,' . $base64;
                            }
                        } catch (\Exception $e) {
                            // Jika gagal, signature_img tetap seperti semula
                        }
                    }
                }
            } else {
                // Jika relation1 adalah objek tunggal
                $item = $data->relation1;
                if (isset($item->signature_img) && !empty($item->signature_img)) {
                    try {
                        $path = $item->signature_img;
                        if (Storage::exists($path)) {
                            $base64 = base64_encode(Storage::get($path));
                            $item->signature_img = 'data:image/png;base64,' . $base64;
                        }
                    } catch (\Exception $e) {
                        // Jika gagal, signature_img tetap seperti semula
                    }
                }
                $data->relation1 = $item;
            }
        }

        $response = [
            'success' => true,
            'data' => $data,
        ];

        return response($response, 200);
    }
}
