<?php

namespace App\Http\Controllers;

use App\Models\VoiceRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class VoiceRecordController extends Controller
{
    public function index()
    {
        $records = VoiceRecord::where('user_id', Auth::id())->latest()->get();
        return view('voice-records.index', compact('records'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'audio_file' => 'required|file|mimes:mp3,wav|max:10240' // max 10MB
        ]);

        $path = $request->file('audio_file')->store('voice-records', 'public');

        VoiceRecord::create([
            'user_id' => Auth::id(),
            'title' => $request->title,
            'file_path' => $path
        ]);

        return redirect()->route('voice-records.index')->with('success', 'Voice record uploaded successfully.');
    }

    public function destroy(VoiceRecord $voiceRecord)
    {
        if ($voiceRecord->user_id !== Auth::id()) abort(403);
        
        Storage::disk('public')->delete($voiceRecord->file_path);
        $voiceRecord->delete();
        
        return redirect()->route('voice-records.index')->with('success', 'Voice record deleted.');
    }
}
