<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Helpdesk;
use Illuminate\Http\Request;

class ManagementBantuanControllers extends Controller
{
    public function index()
    {
        $helpdesks = Helpdesk::with('user')->latest()->get();
        return view('admin.management-bantuan.index', compact('helpdesks'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'reply' => 'required',
            'reply_attachment' => 'nullable|image|max:5120'
        ]);

        $helpdesk = Helpdesk::findOrFail($id);

        $data = [
            'reply' => $request->reply,
            'status' => 'answered'
        ];

        if ($request->hasFile('reply_attachment')) {
            if ($helpdesk->reply_attachment && file_exists(public_path($helpdesk->reply_attachment))) {
                @unlink(public_path($helpdesk->reply_attachment));
            }
            
            $file = $request->file('reply_attachment');
            $fileName = time() . '_reply_' . uniqid() . '.' . $file->getClientOriginalExtension();
            
            $file->move(public_path('uploads/helpdesk/replies'), $fileName);
            
            $data['reply_attachment'] = 'uploads/helpdesk/replies/' . $fileName;
        }

        $helpdesk->update($data);

        return redirect()->back()->with('success', 'Balasan berhasil dikirim.');
    }

    public function destroy($id)
    {
        $helpdesk = Helpdesk::findOrFail($id);
        
        if ($helpdesk->attachment && file_exists(public_path($helpdesk->attachment))) {
            @unlink(public_path($helpdesk->attachment));
        }

        if ($helpdesk->reply_attachment && file_exists(public_path($helpdesk->reply_attachment))) {
            @unlink(public_path($helpdesk->reply_attachment));
        }

        $helpdesk->delete();
        return redirect()->back()->with('success', 'Pesan bantuan berhasil dihapus.');
    }
}