<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class DictationController extends Controller
{
    public function transcribe(Request $request)
    {
        $request->validate([
            'audio' => 'required|file|mimes:webm,mp3,wav,m4a|max:25000', // 25MB Max
        ]);

        $apiKey = env('OPENAI_API_KEY');
        $file = $request->file('audio');

        // 1. SIMULATION MODE (If no API Key)
        if (!$apiKey) {
            // Fake a delay to feel real
            sleep(2);
            return response()->json([
                'text' => "[SIMULATION MODE] The client stated that the contract was signed on January 15th, but the goods were never delivered. We intend to file for breach of contract."
            ]);
        }

        // 2. REAL WHISPER API CALL
        try {
            $response = Http::withToken($apiKey)
                ->attach('file', file_get_contents($file), $file->getClientOriginalName())
                ->post('https://api.openai.com/v1/audio/transcriptions', [
                    'model' => 'whisper-1',
                    'language' => 'en', // Optional: Force English or detect auto
                ]);

            if ($response->failed()) {
                return response()->json(['error' => 'AI Transcription failed.'], 500);
            }

            return response()->json([
                'text' => $response->json()['text']
            ]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
