<?php
/**
 * Base REST Controller
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

/**
 * Base REST controller class
 */
abstract class WAHRB_REST_Controller extends WP_REST_Controller {

    /**
     * Namespace
     *
     * @var string
     */
    protected $namespace = 'wahrb/v1';

    /**
     * Check if current user is a vendor
     *
     * In Dokan mode: checks dokan_view_store_menu capability.
     * In solo mode: checks manage_woocommerce (site owner is the vendor).
     *
     * @return bool
     */
    protected function is_vendor(): bool {
        // Dokan multi-vendor capability
        if (current_user_can('dokan_view_store_menu')) {
            return true;
        }
        // Solo mode / general WooCommerce capability
        if (current_user_can('edit_products') || current_user_can('manage_woocommerce')) {
            return true;
        }
        return false;
    }

    /**
     * Check if current user is admin
     *
     * Uses manage_woocommerce to match admin menu page capabilities.
     * This includes WordPress administrators and WooCommerce shop managers.
     *
     * @return bool
     */
    protected function is_admin(): bool {
        return current_user_can('manage_woocommerce');
    }

    /**
     * Check vendor permission
     *
     * @param WP_REST_Request $request Request object
     * @return bool|WP_Error
     */
    public function check_vendor_permission($request) {
        if (!is_user_logged_in()) {
            return new WP_Error(
                'rest_not_logged_in',
                __('You must be logged in.', 'wahra-rentals-bookings'),
                ['status' => 401]
            );
        }

        if (!$this->is_vendor() && !$this->is_admin()) {
            return new WP_Error(
                'rest_forbidden',
                __('You do not have the required permissions.', 'wahra-rentals-bookings'),
                ['status' => 403]
            );
        }

        return true;
    }

    /**
     * Check admin permission
     *
     * @param WP_REST_Request $request Request object
     * @return bool|WP_Error
     */
    public function check_admin_permission($request) {
        if (!is_user_logged_in()) {
            return new WP_Error(
                'rest_not_logged_in',
                __('You must be logged in.', 'wahra-rentals-bookings'),
                ['status' => 401]
            );
        }

        if (!$this->is_admin()) {
            return new WP_Error(
                'rest_forbidden',
                __('Administrator access required.', 'wahra-rentals-bookings'),
                ['status' => 403]
            );
        }

        return true;
    }

    /**
     * Get current vendor ID
     *
     * @return int
     */
    protected function get_vendor_id(): int {
        return get_current_user_id();
    }

    /**
     * Sanitize date input
     *
     * @param string $date Date string
     * @return string|null
     */
    protected function sanitize_date(string $date): ?string {
        $timestamp = strtotime($date);
        if (!$timestamp) {
            return null;
        }
        return gmdate('Y-m-d', $timestamp);
    }

    /**
     * Sanitize datetime input
     *
     * @param string $datetime Datetime string
     * @return string|null
     */
    protected function sanitize_datetime(string $datetime): ?string {
        $timestamp = strtotime($datetime);
        if (!$timestamp) {
            return null;
        }
        return gmdate('Y-m-d H:i:s', $timestamp);
    }

    /**
     * Format error response
     *
     * @param string $code Error code
     * @param string $message Error message
     * @param int $status HTTP status code
     * @return WP_Error
     */
    protected function error(string $code, string $message, int $status = 400): WP_Error {
        return new WP_Error($code, $message, ['status' => $status]);
    }

    /**
     * Format success response
     *
     * @param mixed $data Response data
     * @param int $status HTTP status code
     * @return WP_REST_Response
     */
    protected function success($data, int $status = 200): WP_REST_Response {
        return new WP_REST_Response($data, $status);
    }

    /**
     * Get pagination params
     *
     * @param WP_REST_Request $request Request object
     * @return array
     */
    protected function get_pagination_params($request): array {
        return [
            'page' => absint($request->get_param('page') ?: 1),
            'per_page' => min(absint($request->get_param('per_page') ?: 20), 100),
        ];
    }

    /**
     * Add pagination headers
     *
     * @param WP_REST_Response $response Response object
     * @param int $total Total items
     * @param int $per_page Items per page
     * @return WP_REST_Response
     */
    protected function add_pagination_headers(WP_REST_Response $response, int $total, int $per_page): WP_REST_Response {
        $total_pages = ceil($total / $per_page);

        $response->header('X-WP-Total', $total);
        $response->header('X-WP-TotalPages', $total_pages);

        return $response;
    }
}
