<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Module_Orders extends SBPAI_Module_Base {
    public function generate() {
        if ( ! class_exists( 'WooCommerce' ) ) return false;

        $order = wc_create_order();
        if ( is_wp_error( $order ) ) return false;

        $this->track_dummy( $order->get_id(), 'order' );

        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin dummy-user lookup.
        $users = get_users( array( 'meta_key' => '_sbpai_user', 'meta_value' => '1', 'number' => 50 ) );
        
        $address = array(
            'first_name' => $this->faker->firstName,
            'last_name'  => $this->faker->lastName,
            'company'    => $this->faker->company,
            'email'      => $this->faker->safeEmail,
            'phone'      => $this->faker->phoneNumber,
            'address_1'  => $this->faker->streetAddress,
            'city'       => $this->faker->city,
            'state'      => $this->faker->stateAbbr,
            'postcode'   => $this->faker->postcode,
            'country'    => $this->faker->countryCode
        );

        if ( ! empty( $users ) && wp_rand( 1, 2 ) === 1 ) {
            $user = $users[array_rand( $users )];
            $order->set_customer_id( $user->ID );
            $address['first_name'] = $user->first_name ?: $address['first_name'];
            $address['last_name'] = $user->last_name ?: $address['last_name'];
            $address['email'] = $user->user_email;
        }

        $order->set_address( $address, 'billing' );
        $order->set_address( $address, 'shipping' );

        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Admin dummy-product lookup.
        $products = wc_get_products( array( 'limit' => 20, 'meta_key' => '_sbpai_post', 'meta_value' => '1' ) );
        if ( ! empty( $products ) ) {
            $num_items = wp_rand( 1, 4 );
            shuffle( $products );
            $selected = array_slice( $products, 0, $num_items );
            
            foreach ( $selected as $product ) {
                $order->add_product( $product, wp_rand( 1, 3 ) );
            }
        }

        $item = new WC_Order_Item_Shipping();
        $item->set_method_title( 'Flat Rate' );
        $item->set_method_id( 'flat_rate' );
        $item->set_total( wp_rand( 5, 20 ) );
        $order->add_item( $item );

        $order->set_payment_method( 'bacs' );
        $order->set_payment_method_title( 'Direct Bank Transfer' );

        $order->calculate_totals();
        
        $statuses = array( 'completed', 'processing', 'on-hold', 'cancelled' );
        $order->update_status( $statuses[array_rand( $statuses )], 'Generated by SBPAI.' );
        
        $order->save();

        return $order->get_id();
    }
}
