<?php
namespace Dreamfox\DeliveryDate\Repositories;

use Dreamfox\DeliveryDate\OrderData;

class OrderRepository
{
  private $_orderId;

  public function __construct($orderId)
  {
    $this->_orderId = $orderId;
  }

  public function getOrderId()
  {
    return $this->_orderId;
  }

	public function load()
	{
		$order = wc_get_order( $this->getOrderId() );
		if ( ! $order ) {
			return new OrderData();
		}

		$date     = $order->get_meta( DREAMFOX_WDD_FIELD_NAME, true );
		$timeslot = $order->get_meta( DREAMFOX_WDD_TIMESLOT_FIELD_NAME, true );

		$data = new OrderData();
		$data->setDeliveryDate( $date );
		$data->setTimeslot( $timeslot ?: '' );
		return $data;
	}

	public function save( OrderData $data )
	{
		$order = wc_get_order( $this->getOrderId() );
		if ( ! $order ) {
			return;
		}

		$order->update_meta_data( DREAMFOX_WDD_FIELD_NAME, $data->getDeliveryDate() );

		if ( null !== $data->getTimeslot() ) {
			$order->update_meta_data( DREAMFOX_WDD_TIMESLOT_FIELD_NAME, $data->getTimeslot() );
		}

		$order->save();
	}

	/**
	 * Count active orders booked for a specific delivery date + timeslot combination.
	 * Uses wc_get_orders() for HPOS compatibility.
	 *
	 * @param  string $deliveryDate Raw date value as stored in order meta.
	 * @param  string $timeslot     Slot label, e.g. "09:00-11:00".
	 * @return int
	 */
	public static function countOrdersForTimeslot( $deliveryDate, $timeslot )
	{
		$statuses   = array( 'pending', 'processing', 'on-hold', 'completed' );
		$meta_query = array(
			'relation' => 'AND',
			array( 'key' => DREAMFOX_WDD_FIELD_NAME,         'value' => $deliveryDate, 'compare' => '=' ),
			array( 'key' => DREAMFOX_WDD_TIMESLOT_FIELD_NAME, 'value' => $timeslot,     'compare' => '=' ),
		);

		$hpos_enabled = class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )
			&& \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();

		if ( $hpos_enabled ) {
			$orders = wc_get_orders( array(
				'limit'      => -1,
				'return'     => 'ids',
				'status'     => $statuses,
				'meta_query' => $meta_query,
			) );

			return count( $orders );
		}

		// Legacy posts datastore: wc_get_orders() silently ignores meta_query
		// there (WC_Order_Data_Store_CPT::query flags it as doing_it_wrong),
		// which would make every active order count toward every timeslot.
		$order_ids = get_posts( array(
			'post_type'   => 'shop_order',
			'post_status' => array_map(
				static function ( $status ) {
					return 'wc-' . $status;
				},
				$statuses
			),
			'fields'      => 'ids',
			'numberposts' => -1,
			'meta_query'  => $meta_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		) );

		return count( $order_ids );
	}
}
