<?php

namespace App\Http\Controllers\User;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProfileController extends Controller
{
    public function Profile(Request $request){
        $user = User::where('id', $request->user()->id)->with('roles')->first();
        
        $user->profile_image_data = null;
        $user->profile_signature_data = null;

        if ($user->profile_image && Storage::exists($user->profile_image)) {
            $imageContent = Storage::get($user->profile_image);
            $user->profile_image_data = 'data:image/' . pathinfo($user->profile_image, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageContent);
        }

        if ($user->profile_signature && Storage::exists($user->profile_signature)) {
            $signatureContent = Storage::get($user->profile_signature);
            $user->profile_signature_data = 'data:image/' . pathinfo($user->profile_signature, PATHINFO_EXTENSION) . ';base64,' . base64_encode($signatureContent);
        }

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

        return response($response, 200);
    }

    public function setProfileImage(Request $request)
    {
        if($request->hasfile('image')){
            $user = User::where('id',$request->user()->id)->first();
            $randomDigits = Str::random(5);
            $filename = 'profile_' . $user->id . '_' . $randomDigits . '.png';
            $path = Storage::putFileAs('profiles', $request->file('image'), $filename);
            
            $user->profile_image = $path;
            $user->save();

            $response = [
                'success'=>true,
                'message'=> "done",
            ];

            return response($response,200);
        }else{
            $response = [
                'success' => false,
                'message' => "Silahkan upload foto profil"
            ];
            return response($response,400);
        }
    }

    public function setSignatureImage(Request $request)
    {
        if($request->hasfile('image')){
            $user = User::where('id',$request->user()->id)->first();
            $randomDigits = Str::random(5);
            $filename = 'signature_' . $user->id . '_' . $randomDigits . '.png';
            $path = Storage::putFileAs('signatures', $request->file('image'), $filename);
            
            $user->profile_signature = $path;
            $user->save();

            $response = [
                'success'=>true,
                'message'=> "done",
            ];

            return response($response,200);
        }else{
            $response = [
                'success' => false,
                'message' => "Silahkan upload tanda tangan"
            ];
            return response($response,400);
        }
    }
}