<?php

namespace WeDevs\AppBridge\Integrations\WooCommerce\REST;

use WC_Bookings_REST_Products_Slots_Controller;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class BookingSlotsController extends WC_Bookings_REST_Products_Slots_Controller {
    /**
     * Endpoint namespace
     *
     * @var string
     */
    protected $namespace = 'app-bridge/v1';

    /**
     * Route name
     *
     * @var string
     */
    protected $rest_base = 'pocket-store';

    public function __construct() {
        $this->register_routes();
    }

    /**
     * Register the route for bookings slots.
     */
    public function register_routes() {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base . '/bookings/product/slots',
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array( $this, 'get_items' ),
                    'permission_callback' => '__return_true',
                ),
            )
        );
    }

    /**
     * Get available bookings slots.
     *
     * @param WP_REST_Request $request Full details about the request.
     * @return mixed
     */
    public function get_items( $request ) {
        $items = parent::get_items( $request );

        $slots = [];

        foreach ( $items['records'] as $key => $item ) {
            $item['date_format'] = gmdate( 'A', strtotime( $item['date'] ) );
            $slots[] = $item;
        }

        return $slots;
    }
}
