<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\ResponseInterface;

class TestsController extends ResourceController
{
    protected $modelName = 'App\Models\TestModel';
    protected $testItemModel;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->testItemModel = model('App\Models\TestItemModel');
    }

    /**
     * Count the total number of tests.
     *
     * @return ResponseInterface
     */
    public function count()
    {
        $total = $this->model->countAll();
        return $this->respond(['total' => $total]);
    }

    /**
     * Return an array of resource objects, themselves in array format.
     *
     * @return ResponseInterface
     */
    public function index()
    {
        $tests = $this->model->findAll();

        foreach ($tests as &$test) {
            $test['test_items'] = $this->testItemModel->where('test_id', $test['id'])->findAll();
            if (!$test['test_items']) {
                $test['test_items'] = [];
            }
        }
        return $this->respond($tests);
    }

    /**
     * Return the properties of a resource object.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function show($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        $data = $this->model->find($id);
        if (!$data) {
            return $this->failNotFound('Test not found');
        }

        $data['test_items'] = $this->testItemModel->where('test_id', $id)->findAll();
        if (!$data['test_items']) {
            $data['test_items'] = [];
        }

        return $this->respond($data);
    }

    /**
     * Return a new resource object, with default properties.
     *
     * @return ResponseInterface
     */
    public function new()
    {
        $values = $this->model->getDefaultValues();
        $values['test_items'] = $this->testItemModel->getDefaultValues();
        return $this->respond($values);
    }

    /**
     * Create a new resource object, from "posted" parameters.
     *
     * @return ResponseInterface
     */
    public function create()
    {
        $data = (array) $this->request->getVar();
        if (!$this->model->insert($data)) {
            return $this->failValidationErrors($this->model->errors());
        }

        if(!isset($data['test_items']) || !is_array($data['test_items'])) {
            return $this->failValidationErrors(['test_items' => 'Test items must be an array']);
        }

        $id = $this->model->insertID();
        foreach ($data['test_items'] as $item) {
            $item = (array) $item;
            $item['test_id'] = $id;
            if (!$this->testItemModel->insert($item)) {
                return $this->failValidationErrors($this->testItemModel->errors());
            }
        }
        return $this->respondCreated(['id' => $id], 'Test created successfully');
    }

    /**
     * Return the editable properties of a resource object.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function edit($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        $data = $this->model->find($id);
        if (!$data) {
            return $this->failNotFound('Test not found');
        }

        $data['test_items'] = $this->testItemModel->where('test_id', $id)->findAll();
        if (!$data['test_items']) {
            $data['test_items'] = [];
        }

        return $this->respond($data);
    }

    /**
     * Add or update a model resource, from "posted" properties.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function update($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        
        $data = $this->model->find($id);
        if (!$data) {
            return $this->failNotFound('Test not found');
        }

        $data = (array) $this->request->getVar();
        if (!$this->model->update($id, $data)) {
            return $this->failValidationErrors($this->model->errors());
        }

        $data['test_items'] = (array) ($data['test_items'] ?? []);
        if (!isset($data['test_items']) || !is_array($data['test_items']) || count($data['test_items']) === 0) {
            return $this->failValidationErrors(['test_items' => 'Test items must be an array']);
        }

        $this->testItemModel->where('test_id', $id)->delete();

        foreach ($data['test_items'] as $item) {
            $item = (array) $item;
            $item['test_id'] = $id;
            if (!$this->testItemModel->insert($item)) {
                return $this->failValidationErrors($this->testItemModel->errors());
            }
        }

        return $this->respondUpdated(['id' => $id], 'Test updated successfully');
    }

    /**
     * Delete the designated resource object from the model.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function delete($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        if (!$this->model->find($id)) {
            return $this->failNotFound('Test not found');
        }

        if (!$this->model->delete($id)) {
            return $this->failValidationErrors($this->model->errors());
        }

        return $this->respondDeleted(['id' => $id], 'Test deleted successfully');
    }
}
