<?php

// Folder where the text files are stored
$directory = getcwd().'/taika/Orders/';
$witreDirectory = getcwd().'/taika/PriorityOrders/';

$files = glob($directory . 'TA*.txt');

$orderNumber = '';
$newData = [];
foreach ($files as $file) {
    // Read the content of the file
    $content = file_get_contents($file);

    $dataArray = explode("\n", $content);

    foreach ($dataArray as $key => $data){
        $itemArray = explode(';',$data);
        if(!isset($itemArray[0]) || empty($itemArray[0])){
            continue;
        }

        $orderExits = readOlderData($itemArray[1]);
        if($key == 0 && isset($itemArray[0])){

            if(isset($itemArray[11]) && !empty($itemArray[11])){
                $orderDate = DateTime::createFromFormat('m/d/y', $itemArray[11]);
                $convertedOrderDate = $orderDate->format('Ymd');
            }else {
                $convertedOrderDate = date('Ymd');
            }

            $poNumber = '';
            if(isset($itemArray[4]) && !empty($itemArray[4])){
                $poNumber = "-".$itemArray[4];
            }
            $head = [
                'H',
                $itemArray[0], //Customer Number
                $itemArray[0], //Customer Number
                "",
                $convertedOrderDate, //Order date
                $itemArray[1] .$poNumber, //Taika Order id
                '',
                '',
                '',
                '',
                $itemArray[6], //Patient Name
                $itemArray[7], //Address
                '',
                $itemArray[8], //State
                $itemArray[9], //City
                $itemArray[10], // Zip
                '',
                '',
                $itemArray[4], // PO number
            ];

            $orderNumber = preg_replace('/[a-zA-Z]/', '', $itemArray[1]);
            $newData[] = implode(';',$head);
            $sku = [
                'D',
                $itemArray[2], // SKU
                "",
                "PR",
                $itemArray[3], // Qty
                $itemArray[5], // Ship to name
                ""
            ];
            $newData[] = implode(';',$sku);
        }else {
            $otherSku = [
                'D',
                $itemArray[2], // SKU
                "",
                "PR",
                $itemArray[3], // Qty
                $itemArray[5], // Ship to name
                ""
            ];
            $newData[] = implode(';',$otherSku);
        }

    }
    if($orderExits == true){
        echo "duplicated order - ". $file;
        rename($file, $directory.'duplicated/'. basename($file));
    }else {
        if(count($newData)){
            rename($file, $directory.'completed/'. basename($file));
        }
    }
}

if(count($newData)){
    $newFileData = implode("\n", $newData);
    $fileName = 'website_tika_merge-'.date('Y-m-d_H-i-s').'.txt';
    $result = file_put_contents($witreDirectory.$fileName, $newFileData);
}
function readOlderData($search_string)
{
    $directory = getcwd().'/taika/Orders/completed';

    // Ensure the directory exists
    if (!is_dir($directory)) {
        return false;
    }

    // Get all .txt files from the directory
    $files = glob($directory . "/*.txt");

    if (!empty($files)) {
        foreach ($files as $file) {
            // Open and read the file
            $file_contents = file_get_contents($file);
            // Search for the string in the file contents
            if (stripos($file_contents, $search_string) !== false) {
                return true;
            }
        }
        return false;
    } else {
        return false;
    }
}