<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SampleFormController extends Controller
{
    /**
     * Display the examples landing page.
     */
    public function landing()
    {
        return view('examples.landing');
    }

    /**
     * Display the sample form.
     */
    public function create()
    {
        return view('samples.form');
    }

    /**
     * Store the form data.
     */
    public function store(Request $request)
    {
        // Server-side validation
        $validated = $request->validate([
            'first_name' => 'required|string|max:191|regex:/^[a-zA-Z\s]+$/',
            'last_name' => 'required|string|max:191|regex:/^[a-zA-Z\s]+$/',
            'email' => 'required|email|max:191',
            'phone' => 'nullable|string|max:20',
            'date_of_birth' => 'nullable|date|before:today',
            'country' => 'nullable|string|max:191',
            'bio' => 'nullable|string|max:1000',
            'documents.*' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048'
        ], [
            'first_name.required' => 'First name is required',
            'first_name.regex' => 'First name can only contain letters and spaces',
            'last_name.required' => 'Last name is required',
            'email.required' => 'Email address is required',
            'email.email' => 'Please enter a valid email address',
            'date_of_birth.before' => 'Date of birth must be in the past',
        ]);

        // XSS Prevention - Laravel automatically escapes output in Blade
        // Additional sanitization for specific fields if needed
        $validated['first_name'] = strip_tags($validated['first_name']);
        $validated['last_name'] = strip_tags($validated['last_name']);
        $validated['bio'] = strip_tags($validated['bio'] ?? '');

        // Handle file uploads
        if ($request->hasFile('documents')) {
            $documents = [];
            foreach ($request->file('documents') as $file) {
                $documents[] = $file->store('documents', 'public');
            }
            $validated['documents'] = $documents;
        }

        // In a real application, you would save to database here
        // For this sample, we'll just redirect with success message
        
        return redirect()
            ->route('samples.form')
            ->with('success', 'Form submitted successfully! Name: ' . $validated['first_name'] . ' ' . $validated['last_name']);
    }
}
