<?php

namespace Booktics\Dummy_Data;

use Booktics\Models\Service_Model;
use Ens\Flow\Flow;
use Exception;
use stdClass;

class Dummy_Data_Manager {
    private $generator;

    /**
     * Constructor for dummy data manager
     *
     * @return  void
     */
    public function __construct() {
        $this->generator = new Generator();
    }

    /**
     * Generate dummy data for onboarding
     */
    public function generate_onboarding_data( $service_count = 3 ) {
        $flow_result = $this->create_automation_flows();
        $result      = $this->create_services( $service_count );
        if ( empty( $result['service_ids'] ) ) {
            return false;
        }

        return array(
            'flows'    => $flow_result['flow_ids'],
            'services' => $result['service_ids'],
            'errors'   => array_merge( $result['errors'], $flow_result['errors'] ),
        );
    }

    /**
     * Create fake services
     *
     * @param int $count Number of services to create
     *
     * @return array Created service IDs
     */
    public function create_services( int $count = 3 ): array {
        $result           = array(
            'service_ids' => array(),
            'errors'      => array(),
        );
        $current_services = Service_Model::paginate();
        if ( $current_services['total'] > 0 ) {
            return $result;
        }

        $service_model = new \Booktics\Models\Service_Model();
        $service_ids   = array();
        $service_types = array(
            'Consultation' => 30,
            'Check-up'     => 60,
            'Therapy'      => 45,
            'Examination'  => 90,
            'Follow-up'    => 20,
            'Massage'      => 60,
            'Treatment'    => 45,
            'Evaluation'   => 30,
        );

        for ( $i = 0; $i < $count; $i++ ) {
            $service_name = $this->generator->random_element( array_keys( $service_types ) );
            $duration     = $service_types[ $service_name ];
            $description  = $this->generator->sentence( 7 );
            $service_data = array(
                'title'         => $service_name,
                'description'   => $description,
                'content'       => $description,
                'duration_time' => $duration,
                'duration_unit' => 'minutes',
                'charge_amount' => $this->generator->number_between( 50, 300 ),
                'status'        => 'active',
            );

            try {
                $service_id = $service_model->create( $service_data );
                if ( $service_id ) {
                    $result['service_ids'][] = $service_id;
                }
            } catch ( Exception $e ) {
                $result['errors'][] = 'Failed to create service: ' . $e->getMessage();
            }
        }

        return $result;
    }

    /**
     * Create automation flows
     *
     * @return array Created flow IDs
     */
    public function create_automation_flows() {
        $result = array(
            'flow_ids' => array(),
            'errors'   => array(),
        );

        $automation_flows = array(
            array(
                'name'        => 'Order Created',
                'trigger'     => 'order_created',
                'status'      => 'publish',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: order_created',
                                'subtitle'     => 'Order Created',
                                'triggerValue' => 'order_created',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: You just placed and order!',
                                'receiverType' => 'user_email',
                                'from_address' => '',
                                'subject'      => 'You just placed and order!',
                                'body'         => '<p>Hi {{customer_name}}, </p><p>We are glad to let you know that your order placed successful.</p><p>Your order no: {{order_no}}</p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
            array(
                'name'        => 'Team Member Invitation',
                'trigger'     => 'team_member_created',
                'status'      => 'publish',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: team_member_created',
                                'subtitle'     => 'Team Member Created',
                                'triggerValue' => 'team_member_created',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: You are invited to join the team.',
                                'receiverType' => 'team_member_email',
                                'from_address' => '',
                                'subject'      => 'You are invited to join the team',
                                'body'         => '<p>Hi {{team_member_name}}, </p><p>We are glad to let you know that you are invited to join our team.</p><p>Please reset your password from the below link.</p><p><a href="{{password_reset_url}}" rel="noopener noreferrer" target="_blank">{{password_reset_url}}</a></p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
            array(
                'name'        => 'Appointment Scheduled',
                'trigger'     => 'appointment_scheduled',
                'status'      => 'draft',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: appointment_scheduled',
                                'subtitle'     => 'Appointment Scheduled',
                                'triggerValue' => 'appointment_scheduled',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: You have a new appointment.',
                                'receiverType' => 'user_email',
                                'from_address' => '',
                                'subject'      => 'You have a new appointment',
                                'body'         => '<p>Dear {{customer_name}}, </p><p>We are glad to let you know that you have a new appointment schedule for {{appointment_service}} with {{appointment_team_member}} on {{appointment_date}} at {{start_time}}.</p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
            array(
                'name'        => 'Appointment Rescheduled',
                'trigger'     => 'appointment_rescheduled',
                'status'      => 'draft',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: appointment_rescheduled',
                                'subtitle'     => 'Appointment Rescheduled',
                                'triggerValue' => 'appointment_rescheduled',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: Your appointment has been rescheduled.',
                                'receiverType' => 'user_email',
                                'from_address' => '',
                                'subject'      => 'Your appointment has been rescheduled',
                                'body'         => '<p>Dear {{customer_name}}, </p><p>We want to inform you that your appointment has been rescheduled for {{appointment_service}} with {{appointment_team_member}} on {{appointment_date}} at {{start_time}}.</p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
            array(
                'name'        => 'Appointment Cancelled',
                'trigger'     => 'appointment_cancelled',
                'status'      => 'draft',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: appointment_cancelled',
                                'subtitle'     => 'Appointment Cancelled',
                                'triggerValue' => 'appointment_cancelled',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: Your appointment has been cancelled.',
                                'receiverType' => 'user_email',
                                'from_address' => '',
                                'subject'      => 'Your appointment has been cancelled',
                                'body'         => '<p>Dear {{customer_name}}, </p><p>We want to inform you that your appointment has been cancelled for {{appointment_service}} with {{appointment_team_member}} on {{date}} at {{start_time}}.</p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
            array(
                'name'        => 'Customer Invitation',
                'trigger'     => 'customer_created',
                'status'      => 'publish',
                'flow_config' => array(
                    'nodes' => array(
                        array(
                            'id'       => 'node_1',
                            'type'     => 'trigger',
                            'name'     => 'trigger',
                            'data'     => array(
                                'label'        => 'trigger: customer_created',
                                'subtitle'     => 'Customer Created',
                                'triggerValue' => 'customer_created',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 50,
                            ),
                        ),
                        array(
                            'id'       => 'node_2',
                            'type'     => 'end',
                            'name'     => 'end',
                            'data'     => array(
                                'label'    => 'end_flow',
                                'subtitle' => 'End execution path',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 410,
                            ),
                        ),
                        array(
                            'id'       => 'node_3',
                            'type'     => 'action',
                            'name'     => 'email',
                            'data'     => array(
                                'actionType'   => 'send_email',
                                'label'        => 'send_email',
                                'subtitle'     => 'Subject: Your customer profile created.',
                                'receiverType' => 'customer_email',
                                'from_address' => '',
                                'subject'      => 'Your customer profile created.',
                                'body'         => '<p>Dear {{customer_full_name}}, </p><p>We are glad to let you know that you are invited as customer to our platform.</p><p>Please reset your password from the below link.</p><p><a href="{{password_reset_url}}" rel="noopener noreferrer" target="_blank">{{password_reset_url}}</a></p>',
                            ),
                            'position' => array(
                                'x' => 200,
                                'y' => 230,
                            ),
                        ),
                    ),
                    'edges' => array(
                        array(
                            'id'        => 'edge_node_1-node_3',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_1',
                            'target'    => 'node_3',
                            'data'      => new stdClass(),
                        ),
                        array(
                            'id'        => 'edge_node_3-node_2',
                            'type'      => 'smoothstep',
                            'markerEnd' => array(
                                'type' => 'arrowclosed',
                            ),
                            'source'    => 'node_3',
                            'target'    => 'node_2',
                            'data'      => new stdClass(),
                        ),
                    ),
                ),
            ),
        );
        try {
            $prefix_for_cpt = 'bt';
            $post_type      = $prefix_for_cpt . '-flow';
            foreach ( $automation_flows as $key => $automation_flow ) {
                $existing_flow = get_posts(
                    array(
						'post_type'  => $post_type,
                        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Meta query is necessary for filtering appointments by meta fields
						'meta_query' => array(
							array(
								'key'     => '_bt_notification_flow_trigger',
								'value'   => $automation_flow['trigger'],
								'compare' => '=',
							),
						),
                        'post_status' => 'any',
                        'numberposts' => 1,
                    )
                );
                if ( ! empty( $existing_flow ) ) {
                    continue;
                }

                $flow = new Flow( 'bt', 0 );
                $flow->set_props( $automation_flow );
                $flow_id = $flow->save();
                if ( $flow_id ) {
                    $result['flow_ids'][] = $flow_id;
                }
            }
        } catch ( Exception $e ) {
            $result['errors'][] = 'Failed to create service: ' . $e->getMessage();
        }

        return $result;
    }
}
