<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Exceptions\GlobalException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class DoctorSignatureController extends Controller
{
    /**
     * Muestra la vista para cargar/gestionar la firma digital del doctor
     *
     * @return \Illuminate\View\View
     */
    public function show()
    {
        $user = Auth::user();
        
        return view('doctor.signature', [
            'user' => $user,
            'hasSignature' => $user->hasDigitalSignature()
        ]);
    }
    
    /**
     * Guarda la firma digital del doctor
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Eliminar firma anterior si existe
            if ($user->hasDigitalSignature() && Storage::disk('public')->exists('signatures/' . $user->signature_path)) {
                Storage::disk('public')->delete('signatures/' . $user->signature_path);
            }
            
            // Generar nombre único para el archivo
            $filename = Str::uuid() . '.png';
            
            // Verificar si es una firma dibujada o una imagen subida
            if ($request->has('signature_data')) {
                // Firma dibujada (datos base64)
                $signatureData = $request->input('signature_data');
                // Eliminar la parte "data:image/png;base64," del string
                $encodedImg = substr($signatureData, strpos($signatureData, ',') + 1);
                $decodedImg = base64_decode($encodedImg);
                
                // Guardar la imagen en el storage
                Storage::disk('public')->put('signatures/' . $filename, $decodedImg);
            } else {
                // Validar la imagen subida
                $request->validate([
                    'signature' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
                ]);
                
                // Firma subida como archivo
                $signatureImage = $request->file('signature');
                $signatureImage->storeAs('signatures', $filename, 'public');
            }
            
            // Actualizar usuario
            $user->signature_path = $filename;
            $user->has_signature = true;
            $user->save();
            
            return redirect()->route('doctor.signature')->with('success', __('doctor.signature.success'));
            
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * Elimina la firma digital del doctor
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy()
    {
        try {
            $user = Auth::user();
            
            if ($user->hasDigitalSignature() && Storage::disk('public')->exists('signatures/' . $user->signature_path)) {
                Storage::disk('public')->delete('signatures/' . $user->signature_path);
            }
            
            $user->signature_path = null;
            $user->has_signature = false;
            $user->save();
            
            return redirect()->route('doctor.signature')->with('success', __('doctor.signature.deleted'));
            
        } catch (\Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
} 