<?php
/// file: app/Controllers/CareersController.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;
use App\Models\Career;

final class CareersController extends Controller
{
    public function index(Request $request): Response
    {
        $flash = Session::pullFlash();
        $roles = Career::openRoles();
        $html = $this->view('careers/index', [
            'meta' => Seo::page('careers'),
            'page' => 'careers',
            'roles' => $roles,
            '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('/careers'));
        }
        $data = [
            'career_id' => $request->input('career_id', ''),
            'full_name' => trim((string) $request->input('full_name', '')),
            'email' => trim((string) $request->input('email', '')),
            'portfolio_url' => trim((string) $request->input('portfolio_url', '')),
            '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:4000',
        ]);
        if ($errors !== []) {
            Session::set('_old_input', $data);
            Session::flash('errors', $errors);
            Session::flash('error', 'Please review the form.');
            return $this->redirect(url('/careers'));
        }
        $cid = $data['career_id'] !== '' && ctype_digit((string) $data['career_id']) ? (int) $data['career_id'] : null;
        $pdo = $this->app->pdo();
        $st = $pdo->prepare(
            'INSERT INTO job_applications (career_id, full_name, email, portfolio_url, message, status) VALUES (?,?,?,?,?,?)'
        );
        $st->execute([$cid, $data['full_name'], $data['email'], $data['portfolio_url'], $data['message'], 'new']);
        Session::remove('_old_input');
        Session::flash('success', 'Application received. If there is a fit, you will hear from us.');
        return $this->redirect(url('/careers'));
    }
}
