<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

class BaseApiController extends BaseController
{
    protected function respondJson($payload, int $statusCode = 200): ResponseInterface
    {
        $this->response->setHeader('Access-Control-Allow-Origin', '*');
        $this->response->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
        $this->response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        $this->response->setHeader('Access-Control-Max-Age', '86400');

        return $this->response->setStatusCode($statusCode)->setJSON($payload);
    }

    protected function ok($data = null, array $meta = [], int $statusCode = 200): ResponseInterface
    {
        return $this->respondJson([
            'success' => true,
            'data' => $data,
            'meta' => (object) $meta,
        ], $statusCode);
    }

    protected function fail(string $message, int $statusCode = 400, array $errors = []): ResponseInterface
    {
        return $this->respondJson([
            'success' => false,
            'message' => $message,
            'errors' => (object) $errors,
        ], $statusCode);
    }
}

