<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class GuestContactController extends Controller
{
    public function index()
    {
        return view('guest.contact.index');
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama' => 'required|string|max:255',
            'email' => 'required|email',
            'pesan' => 'required|string|min:10',
            'phone' => 'nullable|string|max:20',
            'company' => 'nullable|string|max:255',
            'subject' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()->first(),
            ], 422);
        }

        try {
            // Generate unique tracking code
            $trackingCode = 'CT' . str_pad(Contact::count() + 1, 6, '0', STR_PAD_LEFT);
            
            $contact = Contact::create([
                'nama' => $request->nama,
                'email' => $request->email,
                'pesan' => $request->pesan,
                'phone' => $request->phone,
                'company' => $request->company,
                'subject' => $request->subject,
                'tracking_code' => $trackingCode,
                'is_read' => false,
            ]);
            
            // Kirim notifikasi untuk kontak baru
            try {
                $notificationService = new NotificationService();
                $notificationService->notifyNewContact($contact, true);
            } catch (\Exception $e) {
                Log::error('Failed to send contact notification: ' . $e->getMessage());
            }
            
            return response()->json([
                'success' => true,
                'message' => 'Pesan berhasil dikirim! Admin akan merespons dalam 1-2 hari kerja.',
                'tracking_code' => $trackingCode,
                'contact_id' => $contact->id,
                'tracking_url' => route('guest.contact.track', $trackingCode),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengirim pesan: ' . $e->getMessage(),
            ], 500);
        }
    }
    
    public function track($trackingCode)
    {
        $contact = Contact::where('tracking_code', $trackingCode)->firstOrFail();
        return view('guest.contact.track', compact('contact'));
    }
}
