<?php

namespace Booktics\Order;

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

use Booktics\Contracts\Hookable_Service_Contract;
use Booktics\Models\Appointment_Model;

class Order_Hooks implements Hookable_Service_Contract {

    /**
     * Register the hooks for the order model.
     *
     * @return void
     */
    public function register() {
        add_action( 'booktics_order_filters', [
            $this,
            'team_member_order_filters'
        ] );
    }

    /**
     * Filter order conditions based on the current user's role.
     *
     * @param array $conditions The order conditions.
     *
     * @return array The filtered order conditions.
     */
    public function team_member_order_filters( $conditions ) {
        $current_user = wp_get_current_user();
        $roles        = $current_user->roles;

        if ( in_array( 'administrator', $roles, true ) ) {
            return $conditions;
        }

        if ( in_array( 'booktics_team_member', $roles, true ) ) {
            $order_ids        = $this->get_order_ids();
            $conditions['id'] = [ 'in', $order_ids ];
        }

        return $conditions;
    }

    /**
     * Get order ids for a date range
     *
     * @param array $dates
     *
     * @return array
     */
    private function get_order_ids() {
        $order_ids    = ['null'];
        $args         = [];
        $args         = apply_filters( 'booktics_appointment_args', $args );
        $appointments = ( new Appointment_Model() )->all( $args );
        foreach ( $appointments as $appointment ) {
            $order_ids[] = $appointment->order_id;
        }

        return $order_ids;
    }
}