<?php

namespace RadiusTheme\RadiusBooking\ExportImport\Exporters;

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

use RadiusTheme\RadiusBooking\ExportImport\Contracts\ExporterInterface;
use RadiusTheme\RadiusBooking\Models\Appointment;
use RadiusTheme\RadiusBooking\Models\CustomerBooking;
use RadiusTheme\RadiusBooking\Models\Payment;
use RadiusTheme\RadiusBooking\Models\AppointmentIntegration;

/**
 * Class AppointmentExporter
 *
 * Exports appointments with bookings, payments, and integrations.
 *
 * @package RadiusTheme\RadiusBooking\ExportImport\Exporters
 */
class AppointmentExporter implements ExporterInterface {

	/**
	 * {@inheritDoc}
	 */
	public function getModuleName(): string {
		return 'appointment';
	}

	/**
	 * {@inheritDoc}
	 */
	public function count(): int {
		return Appointment::query()->count();
	}

	/**
	 * {@inheritDoc}
	 */
	public function export( int $offset = 0, int $limit = 500 ): array {
		$rows    = Appointment::query()->offset( $offset )->limit( $limit )->get();
		$records = array();

		foreach ( $rows as $row ) {
			$appointment = Appointment::hydrate( $row );
			$data        = $appointment->toArray();
			$appt_id     = (int) $data['id'];

			// Customer bookings.
			$booking_rows    = CustomerBooking::where( 'appointment_id', $appt_id )->get();
			$data['bookings'] = array();

			foreach ( $booking_rows as $b_row ) {
				$booking   = CustomerBooking::hydrate( $b_row );
				$b_data    = $booking->toArray();
				$booking_id = (int) $b_data['id'];

				// Payment for this booking.
				$payment_row = Payment::where( 'booking_id', $booking_id )->first();
				if ( $payment_row ) {
					$payment          = Payment::hydrate( $payment_row );
					$p_data           = $payment->toArray();
					unset( $p_data['id'] );
					$b_data['payment'] = $p_data;
				}

				unset( $b_data['id'] );
				$data['bookings'][] = $b_data;
			}

			// Integrations.
			$integration_rows     = AppointmentIntegration::where( 'appointment_id', $appt_id )->get();
			$data['integrations'] = array();

			foreach ( $integration_rows as $i_row ) {
				$integration = AppointmentIntegration::hydrate( $i_row );
				$i_data      = $integration->toArray();
				unset( $i_data['id'] );
				$data['integrations'][] = $i_data;
			}

			$records[] = $data;
		}

		return $records;
	}

	/**
	 * {@inheritDoc}
	 */
	public function getDependencies(): array {
		return array( 'staff', 'service', 'customer', 'location' );
	}
}
