<?php
require_once 'constants.php';
require_once 'logs.php';

// Fetch orders from the API
function fetchOrders() {
    $pageNo = 1;
    $limit = 100;
    $response_dispatch_arr = [];
    $chanelID = 85;

    $sinceDate = (new DateTime())->modify('-7 days')->format('Y-m-d');
    do {
        $curl = curl_init();
        curl_setopt_array( $curl, array(
            CURLOPT_URL => 'https://api.mintsoft.co.uk/api/Order/List?IncludeOrderItems=true&ChannelId=' . $chanelID . '&OrderStatusId=4&SinceDate=' . $sinceDate . '&PageNo=' . $pageNo . '&Limit=' . $limit,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'ms-apikey:' . MS_API_KEY,
                'Content-Length: 0'
            ),
        ) );
        log_message( 'Fetching orders from API: Page ' . $pageNo );

        $response = curl_exec( $curl );
        curl_close( $curl );
        $responseData = json_decode( $response, true );

        if ( count( $responseData ) > 0 ) {
            $response_dispatch_arr = array_merge( $response_dispatch_arr, $responseData );
            $pageNo++;
        } else {
            break;
        }
    }
    while ( count( $responseData ) == $limit );

    return $response_dispatch_arr;
}

function processOrder($order) {
    $orderNumber = $order['OrderNumber'];
    $trackingNumber = $order['TrackingNumber'];
    $trackingUrl = $order['TrackingURL'];
       $externalOrderReference = $order['ExternalOrderReference'];
    $curl = curl_init();

log_message(json_encode(array('status' => 'shipped','sourceOrderId' => $orderNumber,'sourceShipmentId' => $externalOrderReference,'trackingNumber' => $trackingNumber,'trackingUrl' => $trackingUrl)
    ));
    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://www.papier.com/oneflow',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => array('status' => 'shipped','sourceOrderId' => $orderNumber,'sourceShipmentId' => $externalOrderReference,'trackingNumber' => $trackingNumber,'trackingUrl' => $trackingUrl),
    ));

    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        log_message('Error: ' . curl_error($curl));
     } else {
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        log_message($httpCode);
        if ($httpCode === 200) {
            log_message("Order Mintsoft Response " . $orderNumber . ": " . $response . "\n");
            log_message("Order " . $orderNumber .   "Shipment successfully\n");
          
         
        } else {
            log_message("Failed to update Shipment " . $orderNumber .":" . $response ."\n");
            
        }

    }

    curl_close($curl);
}
// Main function to execute the complete process

function main() {
    try {
        // Fetch orders
        $orders = fetchOrders();

        // Process each order
        foreach ( $orders as $order ) {
            try {
                processOrder( $order );
            } catch ( Exception $e ) {
                // Log the error message for a specific order processing failure
                log_message( 'Error fulfilling order ' . $order[ 'OrderNumber' ] . ': ' . $e->getMessage() );
            }
        }
    } catch ( Exception $e ) {
        // Log the error message for general failures in fetching orders or processing
        log_message( 'Error in fulfilling main function: ' . $e->getMessage() );
    }
    
}
// Run the main function
main();