<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ContactMessage;
use App\Models\SiteSetting;
use App\Models\ContactInfo;
use App\Models\Banner;

class ContactController extends Controller
{
    public function index()
    {
        $data = [
            'siteSettings' => $this->getSiteSettings(),
            'contactInfo' => ContactInfo::active()->ordered()->get(),
            'banners' => [
                'contact' => Banner::getForPosition('contact-page'),
            ],
        ];

        return view('frontend.contact', $data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string|max:5000'
        ]);

        $message = $request->message;
        if ($request->subject) {
            $message = "Subject: " . $request->subject . "\n\n" . $message;
        }

        ContactMessage::create([
            'name' => $request->name,
            'email' => $request->email,
            'message' => $message,
            'ip_address' => $request->ip()
        ]);

        return redirect()->back()->with('success', 'Thank you for your message! We will get back to you soon.');
    }

    private function getSiteSettings()
    {
        $settings = SiteSetting::all();
        $data = [];
        
        foreach ($settings as $setting) {
            $data[$setting->key] = $setting->value;
        }
        
        return $data;
    }
}
