<?php

/**
 * Example: Advanced Search Operations with OAuth 2.0 JWT
 * 
 * This example demonstrates advanced search capabilities using the SearchBuilder
 * with OAuth 2.0 JWT authentication
 */

use PortalPeople\netsuite\components\SearchBuilder;

// Example 1: Search customers with various criteria
function searchCustomersExample()
{
    echo "=== Searching for customers ===\n";
    
    $search = new SearchBuilder();
    
    // Build search criteria
    $search->whereContains('companyName', 'Tech')
           ->whereIsNot('entityStatus', '7') // Not inactive
           ->whereOnOrAfter('dateCreated', '2023-01-01')
           ->select(['internalId', 'entityId', 'companyName', 'email', 'phone'])
           ->orderBy('companyName', 'ASC')
           ->limit(10);
    
    try {
        $criteria = $search->build();
        $options = $search->getOptions();
        
        $results = Yii::$app->netsuite->searchRecords('customer', $criteria, $options);
        
        echo "Found " . count($results) . " customers:\n";
        foreach ($results as $customer) {
            echo "- {$customer['companyName']} ({$customer['entityId']}) - {$customer['email']}\n";
        }
        
    } catch (Exception $e) {
        echo "Error searching customers: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

// Example 2: Search items by price range
function searchItemsByPriceExample()
{
    echo "=== Searching items by price range ===\n";
    
    $search = new SearchBuilder();
    
    // Find items between $50 and $200
    $search->whereGreaterThan('basePrice', '50')
           ->whereLessThan('basePrice', '200')
           ->whereIsNot('isInactive', 'T') // Not inactive
           ->select(['internalId', 'itemId', 'displayName', 'basePrice'])
           ->orderBy('basePrice', 'DESC')
           ->limit(20);
    
    try {
        $criteria = $search->build();
        $options = $search->getOptions();
        
        $results = Yii::$app->netsuite->searchRecords('inventoryitem', $criteria, $options);
        
        echo "Found " . count($results) . " items:\n";
        foreach ($results as $item) {
            echo "- {$item['displayName']} ({$item['itemId']}) - \${$item['basePrice']}\n";
        }
        
    } catch (Exception $e) {
        echo "Error searching items: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

// Example 3: Search sales orders by date range
function searchSalesOrdersExample()
{
    echo "=== Searching sales orders from last 30 days ===\n";
    
    $search = new SearchBuilder();
    
    // Find orders from last 30 days
    $thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
    
    $search->whereOnOrAfter('tranDate', $thirtyDaysAgo)
           ->whereIsNot('status', 'Cancelled')
           ->select(['internalId', 'tranId', 'entity', 'tranDate', 'total'])
           ->orderBy('tranDate', 'DESC')
           ->limit(50);
    
    try {
        $criteria = $search->build();
        $options = $search->getOptions();
        
        $results = Yii::$app->netsuite->searchRecords('salesorder', $criteria, $options);
        
        echo "Found " . count($results) . " sales orders:\n";
        foreach ($results as $order) {
            $entityName = is_array($order['entity']) ? $order['entity']['name'] : $order['entity'];
            echo "- {$order['tranId']} - {$entityName} - {$order['tranDate']} - \${$order['total']}\n";
        }
        
    } catch (Exception $e) {
        echo "Error searching sales orders: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

// Example 4: SuiteQL query example
function suiteQLExample()
{
    echo "=== SuiteQL Query Example ===\n";
    
    // Build SuiteQL query using SearchBuilder
    $search = new SearchBuilder();
    $search->select(['id', 'entityid', 'companyname', 'email'])
           ->whereContains('companyname', 'Inc')
           ->orderBy('companyname', 'ASC')
           ->limit(15);
    
    $suiteQLQuery = $search->buildSuiteQL('customer');
    
    echo "Generated SuiteQL Query:\n{$suiteQLQuery}\n\n";
    
    try {
        $results = Yii::$app->netsuite->executeQuery($suiteQLQuery);
        
        echo "Query Results:\n";
        foreach ($results['items'] as $row) {
            echo "- {$row['companyname']} ({$row['entityid']}) - {$row['email']}\n";
        }
        
    } catch (Exception $e) {
        echo "Error executing SuiteQL: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

// Example 5: Custom SuiteQL query
function customSuiteQLExample()
{
    echo "=== Custom SuiteQL Query ===\n";
    
    $customQuery = "
        SELECT 
            c.id,
            c.entityid,
            c.companyname,
            COUNT(so.id) as order_count,
            SUM(so.total) as total_sales
        FROM 
            customer c
        LEFT JOIN 
            salesorder so ON c.id = so.entity
        WHERE 
            c.datecreated >= '2023-01-01'
        GROUP BY 
            c.id, c.entityid, c.companyname
        HAVING 
            COUNT(so.id) > 0
        ORDER BY 
            total_sales DESC
        LIMIT 10
    ";
    
    echo "Custom Query:\n{$customQuery}\n";
    
    try {
        $results = Yii::$app->netsuite->executeQuery($customQuery);
        
        echo "Top customers by sales:\n";
        foreach ($results['items'] as $row) {
            echo "- {$row['companyname']} ({$row['entityid']}) - {$row['order_count']} orders, \${$row['total_sales']} total\n";
        }
        
    } catch (Exception $e) {
        echo "Error executing custom SuiteQL: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

// Example 6: Paginated search
function paginatedSearchExample()
{
    echo "=== Paginated Search Example ===\n";
    
    $pageSize = 5;
    $currentPage = 0;
    $totalProcessed = 0;
    
    do {
        $search = new SearchBuilder();
        $search->whereIsNotEmpty('companyName')
               ->select(['internalId', 'entityId', 'companyName'])
               ->orderBy('dateCreated', 'DESC')
               ->limit($pageSize)
               ->offset($currentPage * $pageSize);
        
        try {
            $criteria = $search->build();
            $options = $search->getOptions();
            
            $results = Yii::$app->netsuite->searchRecords('customer', $criteria, $options);
            
            echo "Page " . ($currentPage + 1) . " - Found " . count($results) . " customers:\n";
            
            foreach ($results as $customer) {
                echo "  - {$customer['companyName']} ({$customer['entityId']})\n";
                $totalProcessed++;
            }
            
            $currentPage++;
            
            // Stop after processing 15 records or when no more results
            if (count($results) < $pageSize || $totalProcessed >= 15) {
                break;
            }
            
            echo "\n";
            
        } catch (Exception $e) {
            echo "Error in paginated search: " . $e->getMessage() . "\n";
            break;
        }
        
    } while (true);
    
    echo "\nTotal customers processed: {$totalProcessed}\n\n";
}

// Run examples
echo "=== NetSuite Advanced Search Examples (OAuth 2.0 JWT) ===\n\n";

// Test connection first
if (Yii::$app->netsuite->testConnection()) {
    echo "✓ NetSuite connection successful!\n\n";
    
    // Run search examples
    searchCustomersExample();
    searchItemsByPriceExample();
    searchSalesOrdersExample();
    suiteQLExample();
    customSuiteQLExample();
    paginatedSearchExample();
    
} else {
    echo "✗ NetSuite connection failed! Please check your configuration.\n";
}