<?php
/// file: app/Controllers/Admin/CareerController.php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Models\Career;

final class CareerController extends Controller
{
    public function index(Request $request): Response
    {
        $rows = Career::all('sort_order ASC');
        $html = $this->adminView('admin/careers/index', ['careers' => $rows]);
        return Response::html($html);
    }

    public function applications(Request $request): Response
    {
        $pdo = $this->app->pdo();
        $rows = $pdo->query(
            'SELECT ja.*, c.title AS career_title FROM job_applications ja LEFT JOIN careers c ON c.id = ja.career_id ORDER BY ja.id DESC'
        )->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        $html = $this->adminView('admin/careers/applications', ['rows' => $rows]);
        return Response::html($html);
    }

    public function create(Request $request): Response
    {
        $flash = Session::pullFlash();
        $old = Session::get('_old_career');
        Session::remove('_old_career');
        $html = $this->adminView('admin/careers/form', [
            'career' => is_array($old) ? $old : null,
            'errors' => $flash['errors'] ?? [],
        ]);
        return Response::html($html);
    }

    public function store(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/admin/careers'));
        }
        $data = $this->collect($request);
        $errors = $this->validate($data);
        if ($errors !== []) {
            Session::flash('errors', $errors);
            Session::set('_old_career', $data);
            return $this->redirect(url('/admin/careers/create'));
        }
        $this->app->pdo()->prepare(
            'INSERT INTO careers (title, slug, location, type, description, sort_order, status) VALUES (?,?,?,?,?,?,?)'
        )->execute([
            $data['title'], $data['slug'], $data['location'], $data['type'], $data['description'], $data['sort_order'], $data['status'],
        ]);
        return $this->redirect(url('/admin/careers'));
    }

    public function edit(Request $request): Response
    {
        $id = (int) ($request->param('id') ?? 0);
        $career = Career::find($id);
        if ($career === null) {
            return $this->redirect(url('/admin/careers'));
        }
        $flash = Session::pullFlash();
        $old = Session::get('_old_career');
        Session::remove('_old_career');
        if (is_array($old)) {
            $career = array_merge($career, $old);
        }
        $html = $this->adminView('admin/careers/form', ['career' => $career, 'errors' => $flash['errors'] ?? []]);
        return Response::html($html);
    }

    public function update(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/admin/careers'));
        }
        $id = (int) ($request->param('id') ?? 0);
        $data = $this->collect($request);
        $errors = $this->validate($data, $id);
        if ($errors !== []) {
            Session::flash('errors', $errors);
            Session::set('_old_career', array_merge($data, ['id' => $id]));
            return $this->redirect(url('/admin/careers/edit/' . $id));
        }
        $this->app->pdo()->prepare(
            'UPDATE careers SET title=?, slug=?, location=?, type=?, description=?, sort_order=?, status=? WHERE id=?'
        )->execute([
            $data['title'], $data['slug'], $data['location'], $data['type'], $data['description'], $data['sort_order'], $data['status'], $id,
        ]);
        return $this->redirect(url('/admin/careers'));
    }

    public function destroy(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            return $this->redirect(url('/admin/careers'));
        }
        $id = (int) ($request->param('id') ?? 0);
        $this->app->pdo()->prepare('DELETE FROM careers WHERE id = ?')->execute([$id]);
        return $this->redirect(url('/admin/careers'));
    }

    /** @return array<string, mixed> */
    private function collect(Request $request): array
    {
        return [
            'title' => trim((string) $request->input('title', '')),
            'slug' => trim((string) $request->input('slug', '')),
            'location' => trim((string) $request->input('location', '')),
            'type' => trim((string) $request->input('type', 'Full-time')),
            'description' => trim((string) $request->input('description', '')),
            'sort_order' => (int) $request->input('sort_order', '0'),
            'status' => $request->input('status', 'open') === 'closed' ? 'closed' : 'open',
        ];
    }

    /** @return array<string, string> */
    private function validate(array $data, ?int $ignoreId = null): array
    {
        $errors = [];
        if ($data['title'] === '' || $data['slug'] === '') {
            $errors['title'] = 'Required.';
        }
        $pdo = $this->app->pdo();
        $q = 'SELECT id FROM careers WHERE slug = ?';
        $params = [$data['slug']];
        if ($ignoreId) {
            $q .= ' AND id != ?';
            $params[] = $ignoreId;
        }
        $st = $pdo->prepare($q . ' LIMIT 1');
        $st->execute($params);
        if ($st->fetch()) {
            $errors['slug'] = 'In use.';
        }
        return $errors;
    }
}
