<?php
/// file: app/Controllers/ContactController.php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\Validator;
use App\Helpers\Seo;

final class ContactController extends Controller
{
    public function index(Request $request): Response
    {
        $flash = Session::pullFlash();
        $html = $this->view('contact/index', [
            'meta' => Seo::page('contact'),
            'page' => 'contact',
            'flash' => $flash,
            'errors' => $flash['errors'] ?? [],
        ], 'layouts/base');
        return Response::html($html);
    }

    public function submit(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            Session::flash('error', 'Invalid session token.');
            return $this->redirect(url('/contact'));
        }
        $data = [
            'full_name' => trim((string) $request->input('full_name', '')),
            'email' => trim((string) $request->input('email', '')),
            'company' => trim((string) $request->input('company', '')),
            'project_type' => trim((string) $request->input('project_type', '')),
            'budget_range' => trim((string) $request->input('budget_range', '')),
            'timeline' => trim((string) $request->input('timeline', '')),
            'message' => trim((string) $request->input('message', '')),
        ];
        $v = new Validator($data);
        $errors = $v->validate([
            'full_name' => 'required|min:2|max:200',
            'email' => 'required|email|max:255',
            'message' => 'required|min:10|max:5000',
        ]);
        if ($errors !== []) {
            Session::set('_old_input', $data);
            Session::flash('errors', $errors);
            Session::flash('error', 'Please correct the highlighted fields.');
            return $this->redirect(url('/contact'));
        }
        $pdo = $this->app->pdo();
        $st = $pdo->prepare(
            'INSERT INTO contact_submissions (full_name, email, company, project_type, budget_range, timeline, message, status) VALUES (?,?,?,?,?,?,?,?)'
        );
        $st->execute([
            $data['full_name'],
            $data['email'],
            $data['company'],
            $data['project_type'],
            $data['budget_range'],
            $data['timeline'],
            $data['message'],
            'new',
        ]);
        Session::remove('_old_input');
        Session::flash('success', 'Message received. We will respond with care.');
        return $this->redirect(url('/contact'));
    }
}
