<?php

namespace App\Http\Controllers\Api\PublicApi;

use App\Http\Controllers\Controller;
use App\Models\Contacts;
use App\Models\Listing;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index()
    {
        $contacts = Contacts::query()
            ->with(['listing', 'user'])
            ->get();

        return response()->json([
            'data' => $contacts
        ]);
    }

    
    public function store(Request $request, ?string $slug = null)
    {
    
        $user = $request->user('sanctum');
        $user_id = $user?->id;

        $listing_id = null;
        if ($slug) {
            $listing = Listing::query()
                ->where('slug', $slug)
                ->published()
                ->firstOrFail();

            $listing_id = $listing->id;
        }

        $data = $request->validate([
            'name' => ['required', 'string', 'max:50'],
            'surname' => ['required', 'string', 'max:50'],
            'companyName' =>  ['required', 'string', 'max:50'],
            
            'phone' => ['required', 'string', 'max:30', 'regex:/^[0-9+\s().\-]+$/'],
            'email' => ['required', 'string', 'email', 'max:150'],
            'message' => ['required', 'string', 'max:1000'],
        ]);

       
        $contact = Contacts::create(array_merge($data, [
            'listing_id' => $listing_id,
            'user_id' => $user_id,
        ]));

        return response()->json([
            'data' => ['id' => $contact->id],
        ], 201);
    }
}
