<?php

namespace App\Modules\Academic\Controllers;

use App\Core\BaseApiController;
use App\Modules\Academic\Models\SubjectModel;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Subject CRUD API (ADMIN only).
 */
class SubjectController extends BaseApiController
{
    /**
     * GET /api/academic/subjects
     */
    public function index(): ResponseInterface
    {
        $model = new SubjectModel();
        $rows  = $model->orderBy('name', 'ASC')->findAll();
        $data  = array_map(static function ($s) {
            return [
                'id'   => (int) $s->id,
                'name' => (string) $s->name,
                'code' => $s->code !== null ? (string) $s->code : null,
            ];
        }, $rows);
        return $this->successResponse($data, 'Subjects');
    }

    /**
     * POST /api/academic/subjects
     */
    public function create(): ResponseInterface
    {
        $payload = $this->request->getJSON(true) ?? [];
        $data    = [
            'name' => trim($payload['name'] ?? ''),
            'code' => isset($payload['code']) && $payload['code'] !== '' ? trim($payload['code']) : null,
        ];

        $model = new SubjectModel();
        if (!$model->validate($data)) {
            return $this->errorResponse(
                implode(' ', $model->errors()),
                $model->errors(),
                null,
                ResponseInterface::HTTP_UNPROCESSABLE_ENTITY
            );
        }

        $id = $model->insert($data);
        if ($id === false) {
            return $this->errorResponse('Gagal menyimpan mata pelajaran', null, null, ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
        }

        $row = $model->find($id);
        $out = [
            'id'   => (int) $row->id,
            'name' => (string) $row->name,
            'code' => $row->code !== null ? (string) $row->code : null,
        ];
        return $this->successResponse($out, 'Mata pelajaran berhasil ditambahkan', null, ResponseInterface::HTTP_CREATED);
    }

    /**
     * PUT /api/academic/subjects/{id}
     */
    public function update(int $id): ResponseInterface
    {
        $model = new SubjectModel();
        $row   = $model->find($id);
        if (!$row) {
            return $this->errorResponse('Mata pelajaran tidak ditemukan', null, null, ResponseInterface::HTTP_NOT_FOUND);
        }

        $payload = $this->request->getJSON(true) ?? [];
        $data    = [
            'id'   => $id,
            'name' => trim($payload['name'] ?? $row->name),
            'code' => isset($payload['code']) && $payload['code'] !== '' ? trim($payload['code']) : null,
        ];

        if (!$model->validate($data)) {
            return $this->errorResponse(
                implode(' ', $model->errors()),
                $model->errors(),
                null,
                ResponseInterface::HTTP_UNPROCESSABLE_ENTITY
            );
        }

        unset($data['id']);
        if ($model->update($id, $data) === false) {
            return $this->errorResponse('Gagal mengubah mata pelajaran', null, null, ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
        }

        $updated = $model->find($id);
        $out     = [
            'id'   => (int) $updated->id,
            'name' => (string) $updated->name,
            'code' => $updated->code !== null ? (string) $updated->code : null,
        ];
        return $this->successResponse($out, 'Mata pelajaran berhasil diubah');
    }

    /**
     * DELETE /api/academic/subjects/{id}
     */
    public function delete(int $id): ResponseInterface
    {
        $model = new SubjectModel();
        if (!$model->find($id)) {
            return $this->errorResponse('Mata pelajaran tidak ditemukan', null, null, ResponseInterface::HTTP_NOT_FOUND);
        }
        if ($model->delete($id) === false) {
            return $this->errorResponse('Gagal menghapus mata pelajaran', null, null, ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
        }
        return $this->successResponse(null, 'Mata pelajaran berhasil dihapus');
    }
}
