<?php

require_once 'constants.php';
require_once 'logs.php';

// Helper function to verify Oneflow signature
function verifyOneflowSignature($headers, $method, $path, $accessSecret, $accessToken) {
    $xOneflowDate = $headers['X-Oneflow-Date'] ?? '';
    $providedAuthorization = $headers['X-Oneflow-Authorization'] ?? '';

    if (!$xOneflowDate || !$providedAuthorization) {
        return false; // Missing required headers
    }

    // Split the provided authorization header into access token and signature
    [$providedAccessToken, $providedSignature] = explode(':', $providedAuthorization, 2);

    if ($providedAccessToken !== $accessToken) {
        return false; // Access token mismatch
    }

    // Build the string to sign
    $stringToSign = "{$method} {$path} {$xOneflowDate}";

    // Generate the expected signature
    $expectedSignature = hash_hmac('sha1', $stringToSign, $accessSecret);

    // Compare the signatures securely
    return hash_equals($expectedSignature, $providedSignature);
}


// Helper function to transform Oneflow payload to Mintsoft-compatible payload
function transformToMintsoftPayload($data) {
    $order = $data['orderData'];
    $shipment = $order['shipments'][0];
    $attachment = $shipment['attachments'][0]['path'] ?? '';

    $orderItems = array_map(function ($item) {
        return [
            "SKU" => $item['code'],
            "Quantity" => $item['quantity'],
            "Details" => $item['description'],
            "UnitPrice" => $item['unitPrice']
        ];
    }, $order['stockItems']);

    // Add the additional SKU if attachment is present
    if (!empty($attachment)) {
        $orderItems[] = [
            "SKU" => 'A50039801',
            "Quantity" => 1
        ];
    }

    return [
        "OrderItems" => $orderItems,
        "OrderNumber" => $order['sourceOrderId'],
        "ExternalOrderReference" => $shipment['sourceShipmentId'],
        "FirstName" => $shipment['shipTo']['name'],
        "Address1" => $shipment['shipTo']['address1'],
        "Address2" => $shipment['shipTo']['address2'],
        "Town" => $shipment['shipTo']['town'],
        "County" => $shipment['shipTo']['state'],
        "PostCode" => $shipment['shipTo']['postcode'],
        "Country" => $shipment['shipTo']['country'],
        "Email" => $shipment['shipTo']['email'],
        'CourierService' => "RMTRK48",
        'CourierServiceId' => 0,
        'Channel' => 'Papier DTC',
        'ChannelId' => 85,
        'Warehouse' => 'GLA3', // Change to GLA3 for Prod
        'WarehouseId' => 6, // Change to 3 for Prod
        'Currency' => 'GBP',
        'CurrencyId' => 0,
        'DeliveryDate' => '',
        'DespatchDate' => '',
        'RequiredDeliveryDate' => '',
        'RequiredDespatchDate' => '',
        'Comments' => '',
        'DeliveryNotes' => '',
        'GiftMessages' => '',
        'VATNumber' => '',
        'EORINumber' => '',
        'PIDNumber' => '',
        'IOSSNumber' => '',
        'ShippingTotalVat' => 0,
        'DiscountTotalVat' => 0,
        'TotalVat' => 0,
        'NumberOfParcels' => 0
    ];
}


// Helper function to send POST request to Mintsoft
function sendToMintsoft($payload) {
    $url = "https://api.mintsoft.co.uk/api/Order"; // Replace with actual endpoint
    $apiKey = MS_API_KEY; // Mintsoft API key from environment variable

    $headers = [
        'Content-Type: application/json',
        'ms-apikey: ' . $apiKey,
        'Content-Length: ' . strlen(json_encode($payload))
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Use PUT method
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);

    return $response;
}

function uploadAttachmentToOrder($orderId, $attachment) {
    $url = "https://api.mintsoft.co.uk/api/Order/${orderId}/Documents?DocumentTypeId=2&PrintWithOrder=true"; 
    $apiKey = MS_API_KEY; // Mintsoft API key from environment variable
    log_message($url);
    // Get the PDF file contents
    $pdfContent = file_get_contents($attachment);

    if ($pdfContent === false) {
        return "Error: Unable to fetch the PDF file.";
    }

    // Encode the content to Base64
    $base64 = base64_encode($pdfContent);

    // Corrected payload
    $payload = [
        "Base64Data" => $base64,
        "FileName" => $orderId . "_giftNote.pdf", // Added file extension
        "Comment" => "Attached gift note",
        "OrderDocumentTypeId" => 2, // Use a valid type ID
        "OrderDocumentPaperSize" => "A4" // Use a proper paper size value if required
    ];
    
     log_message(json_encode($payload));

    $headers = [
        'Content-Type: application/json',
        'ms-apikey: ' . $apiKey,
        'Content-Length: ' . strlen(json_encode($payload))
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // Use PUT method
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);

    return $response;
}

function submissionOrderError($orderNumber) {
  
    $curl = curl_init();

    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' => 'submission-error','sourceOrderId' => $orderNumber,'sourceShipmentId' => $orderNumber),
    ));

    $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 Papier Response " . $orderNumber . ": " . $response . "\n");
            log_message("Order " . $orderNumber .   "submissionError successfully\n");
          
         
        } else {
            log_message("Failed to submissionError" . $orderNumber .":" . $response ."\n");
            
        }

    }

    curl_close($curl);
}

// Main API endpoint logic
// Main API endpoint logic
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $inputData = json_decode(file_get_contents('php://input'), true);
    if (!$inputData) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON payload"]);
        exit;
    }

    $headers = getallheaders();
    $accessSecret = ONEFLOW_ACCESS_SECRET; // Oneflow secret from environment variable
    $accessToken = ONEFLOW_ACCESS_TOKEN;
    $method = $_SERVER['REQUEST_METHOD'];
    $path = '/api/order';

    if (!verifyOneflowSignature($headers, $method, $path, $accessSecret,$accessToken )) {
        http_response_code(401);
        echo json_encode(["error" => "Unauthorized"]);
        exit;
    }

    $mintsoftPayload = transformToMintsoftPayload($inputData);
    $response = sendToMintsoft($mintsoftPayload);
    log_message("API Payload" . json_encode($mintsoftPayload));
    log_message("API Response" . $response);
    echo $response;

   // Ensure the response is sent immediately
if (function_exists('fastcgi_finish_request')) {
    log_message("inside");
    fastcgi_finish_request(); // Best for FastCGI environments
} else {
    ob_flush();
    flush();
}
    
    $response_arr = json_decode($response, true);
    if($response_arr[0]['Success'] == false){
        submissionOrderError($mintsoftPayload['OrderNumber']);
    }else{
        $order = $inputData['orderData'];
        $attachment = $order['shipments'][0]['attachments'][0]['path'];
        $attachmentResponse = uploadAttachmentToOrder($response_arr[0]['OrderId'], $attachment);
    $attachmentResponseArr = json_decode($response, true);
        if($attachmentResponseArr['Success'] == true){
            log_message("Gift Note Attached for "  .$response_arr[0]['OrderId']);
            
        }
        log_message("Document API Response" . $attachmentResponse);
    }
} else {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
}