<?php

namespace App\Http\Controllers\User;

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

class BantuanControllers extends Controller
{
    public function index()
    {
        $helpdesks = Helpdesk::where('user_id', Auth::id())->latest()->get();

        return view('user.bantuan.index', compact('helpdesks'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'message' => 'required',
            'attachment' => 'nullable|mimes:jpg,jpeg,png|max:5120'
        ], [
            'attachment.mimes' => 'Format file tidak didukung. Hanya menerima file JPG, JPEG, atau PNG.',
            'attachment.max' => 'Ukuran gambar terlalu besar. Maksimal ukuran file adalah 5 MB.'
        ]);

        $filePath = null;

        try {
            if ($request->hasFile('attachment')) {
                $file = $request->file('attachment');
                
                $fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
                
                $file->move(public_path('uploads/helpdesk'), $fileName);
                
                $filePath = 'uploads/helpdesk/' . $fileName;
            }

            Helpdesk::create([
                'user_id' => Auth::id(),
                'message' => $request->message,
                'attachment' => $filePath,
                'status' => 'pending'
            ]);

            return back()->with('success', 'Pesan berhasil dikirim');

        } catch (\Exception $e) {
            dd("Gagal menyimpan data ke database karena: " . $e->getMessage());
        }
    }
}