<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CaseRecording;
use App\Models\LegalCase;
use Illuminate\Support\Facades\Auth;

class RecordingController extends Controller
{
    public function store(Request $request, LegalCase $case)
    {
        $request->validate([
            'audio_blob' => 'required|file', // Validates the blob upload
        ]);

        if ($request->hasFile('audio_blob')) {
            $file = $request->file('audio_blob');

            // Generate a unique filename
            $filename = 'rec_' . time() . '_' . $case->id . '.webm';

            // Save to 'public/recordings' folder
            $path = $file->storeAs('recordings', $filename, 'public');

            // Save to DB
            CaseRecording::create([
                'legal_case_id' => $case->id,
                'user_id' => Auth::id(),
                'title' => 'Voice Note - ' . now()->format('M d, H:i'),
                'file_path' => $path,
            ]);

            return response()->json(['success' => true]);
        }

        return response()->json(['error' => 'No audio file received'], 400);
    }

    public function destroy(CaseRecording $recording)
    {
        // Delete file from storage
        \Storage::disk('public')->delete($recording->file_path);
        $recording->delete();

        return back()->with('success', 'Recording deleted.');
    }
}
