<?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 )
	{
		$orders = wc_get_orders( array(
			'limit'      => -1,
			'return'     => 'ids',
			'status'     => 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' => '=' ),
			),
		) );

		return count( $orders );
	}
}
