<?php

namespace FleekDash\Controllers;

use FleekDash\Services\ResponseService;

abstract class BaseController
{
    /**
     * Default items per page
     */
    protected const PER_PAGE = 10;

    /**
     * Cache duration in seconds (1 hour)
     */
    protected const CACHE_TTL = 3600;

    /**
     * Check if request should be cached
     */
    protected function shouldCacheRequest()
    {
        return defined('WP_CACHE')
            && WP_CACHE
            && isset($_SERVER['REQUEST_METHOD'])
            && $_SERVER['REQUEST_METHOD'] === 'GET';
    }

    /**
     * Get cached response or execute callback
     */
    protected function cacheOrExecute($callback)
    {
        if ($this->shouldCacheRequest()) {
            $cached = ResponseService::getCachedResponse();
            if ($cached !== false) {
                return $cached;
            }
        }

        return $callback();
    }

    /**
     * Get pagination parameters from request
     */
    protected function getPaginationParams($request)
    {
        return [
            'page' => absint($request->get_param('page') ?? 1),
            'per_page' => min(
                absint($request->get_param('per_page') ?? self::PER_PAGE),
                100,
            )
        ];
    }

    /**
     * Format pagination metadata
     */
    protected function getPaginationMeta($total_items, $page, $per_page)
    {
        $total_pages = ceil($total_items / $per_page);

        return [
            'current_page' => $page,
            'per_page' => $per_page,
            'total_items' => $total_items,
            'total_pages' => $total_pages
        ];
    }

    /**
     * Validate required parameters
     */
    protected function validateRequired($params, $required)
    {
        $missing = [];
        foreach ($required as $field) {
            if (!isset($params[$field]) || empty($params[$field])) {
                $missing[] = $field;
            }
        }

        if (!empty($missing)) {
            return ResponseService::error(
                'Missing required fields: ' . implode(', ', $missing),
                $missing,
                400,
            );
        }

        return true;
    }
}
