<?php
/**
 * Renewal Controller for Warranty Cart
 *
 * Backs the Renew action on the My Account warranties tab.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\REST\Controllers;

/*
 * The renewal rules, aliased because this controller is also called
 * Renewals. Ownership, the window and the grace period are decided there, so
 * they hold for every caller rather than only for this route.
 */
use WarrantyCart\Core\Renewals as RenewalRules;
use WarrantyCart\REST\Controller;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Renewals class
 *
 * Customer-facing, unlike `/admin/warranty-records/{id}/renew`, which requires
 * `manage_woocommerce` — so until now the only person who could renew a
 * customer's warranty was the shop owner, by hand.
 */
class Renewals extends Controller {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->rest_base = 'renewals';
	}

	/**
	 * Register routes
	 *
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'start_renewal' ),
					'permission_callback' => array( $this, 'check_customer_permission' ),
					'args'                => array(
						'warranty_id' => array(
							'required'          => true,
							'type'              => 'integer',
							'description'       => __( 'The warranty to renew.', 'warranty-cart' ),
							'sanitize_callback' => 'absint',
						),
					),
				),
			)
		);
	}

	/**
	 * Whether the caller may renew anything at all.
	 *
	 * Being logged in is the entry requirement; *which* warranty this account
	 * may renew is decided by `Renewals`, where it holds for every caller
	 * rather than only for this route.
	 *
	 * @return bool
	 */
	public function check_customer_permission(): bool {
		return is_user_logged_in();
	}

	/**
	 * Put a renewal in the customer's cart and send them to checkout.
	 *
	 * @param WP_REST_Request $request REST request object.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function start_renewal( WP_REST_Request $request ) {
		$result = RenewalRules::add_to_cart(
			(int) $request->get_param( 'warranty_id' ),
			get_current_user_id()
		);

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return $this->success_response(
			array_merge(
				array( 'message' => __( 'Renewal added to your cart.', 'warranty-cart' ) ),
				$result
			)
		);
	}
}
