<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;

class ContactController extends BaseController
{
    public function __construct(private \CodeIgniter\HTTP\IncomingRequest $request)
    {
        helper('form'); // Load the form helper
    }

    public function index()
    {
        return view('/parent/contact');
    }

    public function submit()
    {
        helper('form'); // Ensure the form helper is loaded

        $validation = \Config\Services::validation();

        // Define validation rules
        $validation->setRules([
            'name' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[3]|max_length[100]",
            'email' => 'required|valid_email|max_length[254]',
            'subject' => 'required|min_length[3]|max_length[150]',
            'message' => 'required|min_length[10]|max_length[5000]'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return view('/parent/contact', [
                'validation' => $validation
            ]);
        }

        // Process form data
        $name = esc((string) $this->request->getPost('name'));
        $email = esc(strtolower((string) $this->request->getPost('email')));
        $subject = esc((string) $this->request->getPost('subject'));
        $message = nl2br(esc((string) $this->request->getPost('message')));

        // Initialize the EmailController
        $emailController = new \App\Controllers\View\EmailController();

        // Prepare the message to send
        $formattedMessage = "
            <p><strong>From:</strong> {$name} ({$email})</p>
            <p><strong>Subject:</strong> {$subject}</p>
            <p>{$message}</p>
        ";

        // Send the email using EmailController
        if ($emailController->sendEmail('support@alrahmaisgl.org', $subject, $formattedMessage)) {
            $session = session();
            $session->setFlashdata('success', 'Thank you for contacting us! We will get back to you soon.');
        } else {
            $session = session();
            $session->setFlashdata('error', 'There was an error sending your message. Please try again later.');
        }

        return redirect()->to('/parent/contact');
    }
}
