<?php

try {

    // Your API credentials
    $apiUrl = "https://us.priority-connect.online/odata/Priority/tabpe61d.ini/a102521/DOCUMENTS_D";

    $apiKey = base64_encode('orthofeetapi:vJLY6Q4B9hsphD9l'); // Replace with your actual API key

    date_default_timezone_set('America/New_York');
    // Get the current date and time
    $yesterdayDate = date('Y-m-d', strtotime('-1 day'));
    $todayDate = date('Y-m-d');

    // Define the OData query parameters (adjust the filter if needed)
    $queryParams = [
        '$filter' => "REFERENCE eq 'TA1%' and STATDES eq 'Shipped' and UDATE ge ".$yesterdayDate."T00:00:00Z and UDATE lt ".$todayDate."T00:00:00Z", // "REFERENCE eq 'TA100069' and STATDES eq 'Shipped' and UDATE ge 2024-09-26T00:00:00Z and UDATE lt 2024-09-27T00:00:00Z",
        '$select' => "CUSTNAME,DOCNO,ORDNAME,REFERENCE,AIRWAYBILL,STDES,STCODE"
    ];

    // Create the full URL
    $fullUrl = $apiUrl . '?' . http_build_query($queryParams);

    // Create a cURL session to make the API call
    $ch = curl_init();

    // Set the URL and options for the cURL request
    curl_setopt($ch, CURLOPT_URL, $fullUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . $apiKey, // Authorization header
        'Content-Type: application/json'
    ]);

    // Execute the API request
    $response = curl_exec($ch);

    // Check if any error occurred during the API request
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        exit;
    }

    // Close the cURL session
    curl_close($ch);

    // Decode the JSON response
    $data = json_decode($response, true);

    // Define the CSV file name
    $csvFileName = $witreDirectory = getcwd() . '/taika/Shipments/shipments-'.date('mdY').'.csv';

    // Open the CSV file for writing
    $csvFile = fopen($csvFileName, 'w');

    // Define the headers for the CSV file
    $headers = ['Customer No', 'Doc Number', 'Sales Order', 'Taika Order id','Cust po', 'Tracking', 'Shipment method', 'Shipment code'];

    // Write the headers to the CSV file
    fputcsv($csvFile, $headers);

    // Write each data row to the CSV file
    foreach ($data['value'] as $row) {

        $parts = explode('-', $row['REFERENCE'], 2);

        if (count($parts) < 2) {
            $parts = [$row['REFERENCE'], ''];
        }

        $csvRow = [
            $row['CUSTNAME'],
            $row['DOCNO'],
            $row['ORDNAME'],
            $parts[0], // Tika order ID
            $parts[1], // Customer PO
            $row['AIRWAYBILL'],
            $row['STCODE'],
            $row['STDES']
        ];

        fputcsv($csvFile, $csvRow);
    }

    // Close the CSV file
    fclose($csvFile);
    echo "Taika order is pulled from priority for date - ".$todayDate;

}catch (\Exception $exception){
    echo " - Exception Error -";
    echo "<pre>"; print_r($exception->getMessage());
}