<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Contact Controller
 *
 * Handles the contact form display and submission.
 */
class ContactController extends Controller
{
    /**
     * Display the contact form.
     *
     * @return void
     */
    public function index(): void
    {
        $settingModel = $this->model('Setting');
        $settings = $settingModel->getAll();

        $this->view('contact/index', [
            'title'      => 'Contact Us - Gmind Institute',
            'settings'   => $settings,
            'currentNav' => 'contact',
        ]);
    }

    /**
     * Process the contact form submission.
     *
     * Validates CSRF token, sanitizes inputs, and inserts
     * a contact message record.
     *
     * @return void
     */
    public function store(): void
    {
        $this->validateCsrf();

        $name    = sanitize($_POST['name'] ?? '');
        $email   = sanitize($_POST['email'] ?? '');
        $phone   = sanitize($_POST['phone'] ?? '');
        $subject = sanitize($_POST['subject'] ?? '');
        $message = sanitize($_POST['message'] ?? '');

        // Basic validation
        if (empty($name) || empty($email) || empty($message)) {
            flash('error', 'Please fill in all required fields (Name, Email, and Message).');
            redirect('/contact');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect('/contact');
        }

        try {
            $contactModel = $this->model('Contact');
            $contactModel->create([
                'name'    => $name,
                'email'   => $email,
                'phone'   => $phone,
                'subject' => $subject,
                'message' => $message,
                'is_read' => 0,
            ]);

            flash('success', 'Your message has been sent successfully! We will get back to you soon.');
            redirect('/contact');
        } catch (\Throwable $e) {
            error_log('Contact form error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect('/contact');
        }
    }
}
