<?php

namespace App\Controllers;

use Config\Services;

class ContactController extends BaseController
{
    public function index()
    {
        return view('pages/contact', [
            'pageTitle' => 'Contact Us | Sheltaplux Global',
            'metaDescription' => 'Contact Sheltaplux for project consultation, tenders and partnerships.',
            'bodyClass' => '',
            'headerPartial' => 'plux_header',
            'footerPartial' => 'plux_footer',
            'activePage' => 'contact',
        ]);
    }

    public function send()
    {
        if (! $this->request->isAJAX()) {
            return $this->response->setStatusCode(400)->setJSON([
                'success' => false,
                'message' => 'Invalid request type.',
            ]);
        }

        $rules = [
            'full_name' => 'required|min_length[2]|max_length[120]',
            'phone' => 'required|min_length[7]|max_length[40]',
            'email' => 'required|valid_email|max_length[190]',
            'project_type' => 'required|max_length[120]',
            'project_location' => 'permit_empty|max_length[160]',
            'budget' => 'permit_empty|max_length[120]',
            'message' => 'required|min_length[10]|max_length[3000]',
        ];

        if (! $this->validate($rules)) {
            return $this->response->setStatusCode(422)->setJSON([
                'success' => false,
                'message' => 'Please correct the form fields and try again.',
                'errors' => $this->validator->getErrors(),
            ]);
        }

        $emailConfig = config('Email');
        $recipient = trim($emailConfig->recipients) !== '' ? $emailConfig->recipients : $emailConfig->fromEmail;

        if (trim($emailConfig->fromEmail) === '' || trim($recipient) === '') {
            return $this->response->setStatusCode(500)->setJSON([
                'success' => false,
                'message' => 'Mailer is not configured. Set email.fromEmail and email.recipients in .env.',
            ]);
        }

        $payload = $this->request->getPost();
        $subject = 'New Contact Request - Sheltaplux Website';
        $body = view('emails/contact_message', [
            'fullName' => esc((string) $payload['full_name']),
            'phone' => esc((string) $payload['phone']),
            'email' => esc((string) $payload['email']),
            'projectType' => esc((string) $payload['project_type']),
            'projectLocation' => esc((string) ($payload['project_location'] ?? '')),
            'budget' => esc((string) ($payload['budget'] ?? '')),
            'message' => nl2br(esc((string) $payload['message'])),
        ]);

        $mail = Services::email();
        $mail->setFrom($emailConfig->fromEmail, $emailConfig->fromName ?: 'Sheltaplux Website');
        $mail->setTo($recipient);
        $mail->setReplyTo((string) $payload['email'], (string) $payload['full_name']);
        $mail->setSubject($subject);
        $mail->setMessage($body);

        if (! $mail->send()) {
            log_message('error', 'Contact mail send failed: {0}', [$mail->printDebugger(['headers'])]);

            return $this->response->setStatusCode(500)->setJSON([
                'success' => false,
                'message' => 'Message could not be sent right now. Please try again shortly.',
            ]);
        }

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Thank you. Your message has been sent successfully.',
        ]);
    }
}
