<?php
/**
 * Booking Payment Subscriber
 *
 * @package NemtlyBooking
 */

namespace NemtlyBooking\Subscribers;

use NemtlyBooking\Repositories\Booking_Repository;

/**
 * Class Booking_Payment_Subscriber
 */
class Booking_Payment_Subscriber {
    /**
     * Booking Repository
     *
     * @var Booking_Repository
     */
    private $booking_repository;

    /**
     * Constructor
     *
     * @param Booking_Repository $booking_repository Booking Repository.
     */
    public function __construct( Booking_Repository $booking_repository ) {
        $this->booking_repository = $booking_repository;
    }

    /**
     * Register hooks
     */
    public function register() {
        // Listen for specific booking payment success
        add_action( 'nemtly_booking_payment_succeeded_booking', [ $this, 'handle_payment_Success' ], 10, 2 );
    }

    /**
     * Handle payment success for bookings
     *
     * @param \NemtlyBooking\Models\Payment $payment Payment object.
     * @param int                           $booking_id Booking ID.
     */
    public function handle_payment_success( $payment, $booking_id ) {
        $booking = $this->booking_repository->find( $booking_id );

        if ( ! $booking ) {
            return;
        }

        // Only update if not already confirmed (idempotency check)
        if ( ! $booking->is_confirmed() ) {
            $booking->set_booking_status( 'confirmed' );
            $this->booking_repository->update( $booking );

            // Trigger confirmation email / legacy actions
            do_action( 'nemtly_booking_event_booking_confirmed', $booking->to_array() );
        }
    }
}
