<?php

namespace App\Http\Controllers\Admin;

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

class TicketController extends Controller
{
    public function index()
    {
        $tickets = MaintenanceTicket::with('maintainable')->latest()->get();
        return view('admin.tickets.index', compact('tickets'));
    }

    public function show(MaintenanceTicket $ticket)
    {
        return view('admin.tickets.show', compact('ticket'));
    }

    public function update(Request $request, MaintenanceTicket $ticket)
    {
        $validated = $request->validate([
            'status' => 'required|string',
            'admin_notes' => 'nullable|string',
        ]);

        $ticket->update($validated);

        // Kirim notifikasi ke pelapor
        if ($ticket->reporter_email) {
            try {
                \Illuminate\Support\Facades\Mail::to($ticket->reporter_email)->send(new \App\Mail\TicketStatusUpdateNotification($ticket));
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Gagal mengirim email update progres ke ' . $ticket->reporter_email . ': ' . $e->getMessage());
            }
        }

        return redirect()->route('tickets.index')->with('status', 'Status tiket berhasil diperbarui dan notifikasi telah dikirim ke pelapor.');
    }

    public function destroy(MaintenanceTicket $ticket)
    {
        $ticket->delete();
        return redirect()->route('tickets.index')->with('status', 'Tiket berhasil dihapus.');
    }
}
