<?php
namespace Dreamfox\DeliveryDate\Ajaxs;

use Dreamfox\DeliveryDate\Abstracts\AbstractAjax;
use Dreamfox\DeliveryDate\Facades\SystemFacade;
use Dreamfox\DeliveryDate\Helpers\TimeslotHelper;
use Dreamfox\DeliveryDate\Repositories\OrderRepository;

class FrontendAjax extends AbstractAjax
{
	public function getAjaxEvents()
	{
		return array();
	}

	public function getNoPrivAjaxEvents()
	{
		return array( 'get_timeslots' );
	}

	/**
	 * Return available timeslots for a given delivery date.
	 * Called by the checkout page when the customer picks a date.
	 */
	public function get_timeslots()
	{
		// Verify frontend nonce — no login required, but must be on our page.
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'dreamfox_wdd_frontend' ) ) {
			wp_send_json_error( array( 'message' => 'Invalid request.' ), 403 );
		}

		$settings = SystemFacade::getInstance()->loadTimeslotSettings();

		if ( ! $settings->getEnabled() ) {
			wp_send_json_success( array( 'slots' => array() ) );
		}

		$rawDate = isset( $_POST['date'] ) ? sanitize_text_field( wp_unslash( $_POST['date'] ) ) : '';
		if ( empty( $rawDate ) ) {
			wp_send_json_error( array( 'message' => 'No date provided.' ), 400 );
		}

		$dateYmd  = TimeslotHelper::parseDateToYmd( $rawDate );
		$allSlots = TimeslotHelper::generateSlots(
			$settings->getStartTime(),
			$settings->getEndTime(),
			$settings->getDuration()
		);
		$allSlots  = TimeslotHelper::filterPastSlots( $allSlots, $dateYmd );
		$maxOrders = $settings->getMaxOrders();

		$result = array();
		foreach ( $allSlots as $slot ) {
			$booked    = OrderRepository::countOrdersForTimeslot( $rawDate, $slot );
			$remaining = $maxOrders - $booked;
			if ( $remaining > 0 ) {
				$result[] = array(
					'value'     => $slot,
					'label'     => sprintf(
						/* translators: 1: timeslot range e.g. "09:00-11:00", 2: number of spots remaining */
						__( '%1$s (%2$d remaining)', 'woocommerce-delivery-date' ),
						$slot,
						$remaining
					),
					'remaining' => $remaining,
				);
			}
		}

		wp_send_json_success( array( 'slots' => $result ) );
	}
}
