<?php
/// file: app/Controllers/Api/ContactApiController.php

declare(strict_types=1);

namespace App\Controllers\Api;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;

final class ContactApiController extends Controller
{
    public function store(Request $request): Response
    {
        $body = $request->jsonBody() ?? $request->allInput();
        $token = is_array($body) ? ($body['_csrf'] ?? null) : null;
        if (! Csrf::verify(is_string($token) ? $token : null)) {
            return $this->json(['ok' => false, 'error' => 'Invalid CSRF token'], 419);
        }
        if (! is_array($body)) {
            return $this->json(['ok' => false, 'error' => 'Invalid payload'], 400);
        }
        $data = [
            'full_name' => trim((string) ($body['full_name'] ?? '')),
            'email' => trim((string) ($body['email'] ?? '')),
            'company' => trim((string) ($body['company'] ?? '')),
            'project_type' => trim((string) ($body['project_type'] ?? '')),
            'budget_range' => trim((string) ($body['budget_range'] ?? '')),
            'timeline' => trim((string) ($body['timeline'] ?? '')),
            'message' => trim((string) ($body['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 !== []) {
            return $this->json(['ok' => false, 'errors' => $errors], 422);
        }
        $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',
        ]);
        return $this->json(['ok' => true, 'message' => 'Received']);
    }
}
