<?php
declare(strict_types=1);

namespace App\Controller;

class ServicesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Authentication.Authentication');
        $this->Services = $this->fetchTable('Services');
        $this->viewBuilder()->setLayout('ajax'); // 简单 JSON 输出
    }

    public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        parent::beforeFilter($event);
        if ($this->components()->has('Authentication')) {
            $result = $this->Authentication->getResult();
            if (!$result || !$result->isValid()) {
                return $this->redirect([
                    'controller' => 'Login',
                    'action' => 'index',
                    '?' => ['redirect' => $this->request->getRequestTarget()],
                ]);
            }
        }
    }

    /** GET /services/search.json?q= */
    public function search()
    {
        $this->request->allowMethod(['get']);
        $q = trim((string)$this->request->getQuery('q', ''));
        $tb = $this->Services->find()
            ->where(['active' => 1])
            ->orderAsc('name');

        if ($q !== '') {
            $tb->where([
                'OR' => [
                    'name LIKE' => "%{$q}%",
                    'code LIKE' => "%{$q}%"
                ]
            ]);
        }

        $rows = $tb->limit(50)->all();
        $out = [];
        foreach ($rows as $s) {
            $out[] = [
                'id' => (int)$s->id,
                'name' => (string)$s->name,
                'code' => (string)($s->code ?? ''),
                'duration_minutes' => (int)$s->duration_minutes,
                'description' => (string)($s->description ?? ''),
            ];
        }
        return $this->response->withType('json')->withStringBody(json_encode($out));
    }

    /** POST /services/add.json  {name,code,duration_minutes,description} */
    public function add()
    {
        $this->request->allowMethod(['post']);
        $data = (array)$this->request->getData();
        $s = $this->Services->newEmptyEntity();
        $s->name = (string)($data['name'] ?? '');
        $s->code = (string)($data['code'] ?? '');
        $s->duration_minutes = (int)($data['duration_minutes'] ?? 0);
        $s->description = (string)($data['description'] ?? '');

        if ($s->name === '' || $s->duration_minutes <= 0) {
            return $this->response->withStatus(422)->withType('json')
                ->withStringBody(json_encode(['error' => 'Validation failed']));
        }

        if (!$this->Services->save($s)) {
            return $this->response->withStatus(422)->withType('json')
                ->withStringBody(json_encode(['error' => 'Save failed', 'errors' => $s->getErrors()]));
        }

        return $this->response->withType('json')
            ->withStringBody(json_encode([
                'ok' => true,
                'service' => [
                    'id' => (int)$s->id,
                    'name' => (string)$s->name,
                    'duration_minutes' => (int)$s->duration_minutes,
                ],
            ]));
    }
}
