<?php

namespace App\Http\Controllers\API\Inquiries;

use App\Http\Controllers\Controller;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class InquiryController extends Controller
{
    /**
     * Store a new tour inquiry
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string|max:20',
            'message' => 'required|string|max:2000',
            'tour_id' => 'nullable|integer',
            'tour_name' => 'nullable|string',
            'tour_code' => 'nullable|string',
            'page_url' => 'nullable|string',
            // Simple anti-spam: Honeypot field (should be empty)
            'website' => 'present|size:0',
            // Simple anti-spam: Math check or static key
            'spam_check' => 'required|string',
        ]);

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

        // Verify spam check (e.g., "4" for "2+2")
        if ($request->spam_check !== '4' && $request->spam_check !== 'human') {
             return response()->json([
                'message' => 'Anti-spam validation failed'
            ], 422);
        }

        $message = Message::create([
            'sender_name' => $request->name,
            'sender_email' => $request->email,
            'sender_phone' => $request->phone,
            'subject' => 'Tur Bilgi Talebi: ' . ($request->tour_name ?? 'Genel'),
            'message' => $request->message,
            'type' => 'inquiry',
            'status' => 'new',
            'metadata' => [
                'tour_id' => $request->tour_id,
                'tour_name' => $request->tour_name,
                'tour_code' => $request->tour_code,
                'page_url' => $request->page_url,
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ]
        ]);

        return response()->json([
            'message' => 'Talebiniz başarıyla alındı. En kısa sürede size dönüş yapacağız.',
            'id' => $message->id,
        ], 201);
    }
}
