<?php
/// file: app/Controllers/Admin/ServiceAdminController.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\Service;

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

    public function create(Request $request): Response
    {
        $flash = Session::pullFlash();
        $old = Session::get('_old_service');
        Session::remove('_old_service');
        $html = $this->adminView('admin/services/form', [
            'service' => 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/services'));
        }
        $data = $this->collect($request);
        $errors = $this->validate($data);
        if ($errors !== []) {
            Session::flash('errors', $errors);
            Session::set('_old_service', $data);
            return $this->redirect(url('/admin/services/create'));
        }
        $this->app->pdo()->prepare(
            'INSERT INTO services (title, slug, short_description, detail, process, deliverables, ideal_client, sort_order, status) VALUES (?,?,?,?,?,?,?,?,?)'
        )->execute([
            $data['title'], $data['slug'], $data['short_description'], $data['detail'], $data['process'],
            $data['deliverables'], $data['ideal_client'], $data['sort_order'], $data['status'],
        ]);
        return $this->redirect(url('/admin/services'));
    }

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

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

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

    /** @return array<string, mixed> */
    private function collect(Request $request): array
    {
        return [
            'title' => trim((string) $request->input('title', '')),
            'slug' => trim((string) $request->input('slug', '')),
            'short_description' => trim((string) $request->input('short_description', '')),
            'detail' => trim((string) $request->input('detail', '')),
            'process' => trim((string) $request->input('process', '')),
            'deliverables' => trim((string) $request->input('deliverables', '')),
            'ideal_client' => trim((string) $request->input('ideal_client', '')),
            'sort_order' => (int) $request->input('sort_order', '0'),
            'status' => $request->input('status', 'published') === 'draft' ? 'draft' : 'published',
        ];
    }

    /** @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 services 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;
    }
}
