<?php

namespace App\Controllers\View;

use App\Models\ContactUsModel;
use App\Controllers\BaseController;

class PageController extends BaseController
{
    public function privacyPolicy()
    {
        return $this->response->setBody(file_get_contents(ROOTPATH . 'public/html/privacy_policy.html'))
            ->setContentType('text/html');
    }

    public function termsOfService()
    {
        return $this->response->setBody(file_get_contents(ROOTPATH . 'public/html/terms_of_service.html'))
            ->setContentType('text/html');
    }

    public function helpCenter()
    {
        return $this->response->setBody(file_get_contents(ROOTPATH . 'public/html/help_center.html'))
            ->setContentType('text/html');
    }

    public function submitContactForm()
    {
        try {
            $email = strtolower($this->request->getPost('email'));
            $message = $this->request->getPost('message');

            // Save the message to the database
            $contactModel = new ContactUsModel();
            $contactData = [
                'email' => $email,
                'message' => $message,
            ];

            if (!$contactModel->save($contactData)) {
                log_message('error', 'Failed to save contact data: ' . implode(', ', $contactModel->errors()));
                return redirect()->back()->with('error', 'Failed to save message. Please try again.');
            }

            // Prepare the email content
            $recipient = 'alrahma.isgl@gmail.com'; // Change to the communication head's email
            $subject = 'Contact Us Form Submission';
            $emailMessage = "You have received a new message from $email:\n\n$message";

            // Use EmailController to send the email
            $emailController = new \App\Controllers\View\EmailController();
            if (!$emailController->sendEmail($recipient, $subject, $emailMessage)) {
                log_message('error', 'Failed to send email.');
                return redirect()->back()->with('error', 'Failed to send message. Please try again.');
            }

            return redirect()->to('/thank_you')->with('success', 'Message sent successfully.');
        } catch (\Exception $e) {
            log_message('error', 'Exception occurred: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An unexpected error occurred. Please try again.');
        }
    }
}