<?php

namespace App\Controllers\Api;

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

class BaseApiController extends ResourceController
{
    protected $format = 'json';
    protected $db;

    // DB lazy loading
    protected function getDB()
    {
        if (!$this->db) {
            $this->db = \Config\Database::connect();
        }
        return $this->db;
    }

    /**
     * Success response
     */
    protected function respondSuccess($data = null, $message = 'Success', $code = ResponseInterface::HTTP_OK)
    {
        return $this->respond([
            'success' => true,
            'message' => $message,
            'data' => $data
        ], $code);
    }

    /**
     * Error response
     */
    protected function respondError($message = 'Error occurred', $code = ResponseInterface::HTTP_BAD_REQUEST, $errors = null)
    {
        return $this->respond([
            'success' => false,
            'message' => $message,
            'errors' => $errors
        ], $code);
    }

    /**
     * Validate token
     */
    protected function validateToken()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (empty($authHeader)) {
            return false;
        }

        $token = str_replace('Bearer ', '', $authHeader);

        if (empty($token)) {
            return false;
        }

        // Check token in database
        $builder = $this->getDB()->table('admin_tokens');
        $tokenData = $builder->where('token', $token)
                             ->where('expires_at >', date('Y-m-d H:i:s'))
                             ->get()
                             ->getRow();

        if (!$tokenData) {
            return false;
        }

        return $tokenData;
    }

    /**
     * Require authentication
     */
    protected function requireAuth()
    {
        $tokenData = $this->validateToken();

        if (!$tokenData) {
            return $this->respondError('Unauthorized', ResponseInterface::HTTP_UNAUTHORIZED);
        }

        return $tokenData;
    }

    /**
     * Get pagination params
     */
    protected function getPaginationParams()
    {
        $page = $this->request->getGet('page') ?? 1;
        $perPage = $this->request->getGet('per_page') ?? 10;
        $offset = ($page - 1) * $perPage;

        return [
            'page' => (int)$page,
            'per_page' => (int)$perPage,
            'offset' => (int)$offset
        ];
    }

    /**
     * Build paginated response
     */
    protected function paginatedResponse($builder, $params)
    {
        $total = $builder->countAllResults(false);
        $items = $builder->limit($params['per_page'], $params['offset'])->get()->getResult();

        return [
            'items' => $items,
            'total' => $total,
            'page' => $params['page'],
            'per_page' => $params['per_page'],
            'total_pages' => ceil($total / $params['per_page'])
        ];
    }
}
