<?php
ini_set("display_errors", "on");
error_reporting(E_ALL ^ E_NOTICE);
require('commonFunctions.php');

$textListing = $_POST['textListing'];
$listType = $_POST['listType'];

$cutList = array('Square of', 'Jug of', 'Vial of', 'Piece of', 'Jar of', 'Pot of', 'Vase of', 'Sprig of', 'Bag of', 'Clump of', 'Set of', 'Ingot of', 'Handful of', 'Spool of', 'Ponze of', 'Bowl of', 'Bundle of', 'Flask of', 'Flasque of', 'Lump of', 'Chunk of', 'Slice of', 'Serving of', 'Bunch of', 'Plate of', 'Bottle of', 'Sprig of', 'Dish of', 'Can of', 'Pair of', 'Loaf of', 'Cone of', 'Pitcher of', 'Pair of', 'Dose of');
$cutListPl = array('Squares of', 'Jugs of', 'Vials of', 'Pieces of', 'Jars of', 'Pots of', 'Vases of', 'Sprigs of', 'Bags of', 'Clumps of', 'Sets of', 'Ingots of', 'Handfuls of', 'Spools of', 'Ponzes of', 'Bowls of', 'Bundles of', 'Flasks of', 'Flasques of', 'Lumps of', 'Chunks of', 'Slices of', 'Servings of', 'Bunches of', 'Plates of', 'Bottles of', 'Sprigs of', 'Dishes of', 'Cans of', 'Pairs of', 'Loaves of', 'Cones of', 'Pitchers of', 'Pairs of', 'Doses of');
$repList = array('Square', 'Jug', 'Vial', 'Piece', 'Jar', 'Pot', 'Vase', 'Sprig', 'Bag', 'Clump', 'Set', 'Ingot', 'Handful', 'Spool', 'Ponze', 'Bowl', 'Bundle', 'Flask', 'Flasque', 'Lump', 'Chunk', 'Slice', 'Serving', 'Bunch', 'Plate', 'Bottle', 'Sprig', 'Dish', 'Can', 'Pair', 'Loaf', 'Cone', 'Pitcher', 'Pair', 'Dose');
$repListPl = array('Squares', 'Jugs', 'Vials', 'Pieces', 'Jars', 'Pots', 'Vases', 'Sprigs', 'Bags', 'Clumps', 'Sets', 'Ingots', 'Handfuls', 'Spools', 'Ponzes', 'Bowls', 'Bundles', 'Flasks', 'Flasques', 'Lumps', 'Chunks', 'Slices', 'Servings', 'Bunches', 'Plates', 'Bottles', 'Sprigs', 'Dishes', 'Cans', 'Pairs', 'Loaves', 'Cones', 'Pitchers', 'Pairs', 'Doses');
$skillList = array('Woodworking', 'Goldsmithing', 'Bonecraft', 'Cooking', 'Smithing', 'Fishing', 'Alchemy', 'Leathercraft', 'Clothcraft', '-');
$skillRanks = array('Amateur', 'Recruit', 'Initiate', 'Novice', 'Apprentice', 'Journeyman', 'Craftsman', 'Artisan', 'Adept', 'Veteran');


if ($textListing) {
    $array = @file('ultimateParse.txt');

    $searchName = array();
    foreach($array as $key => $currow) {
        $thisdata = explode('|', $currow);
        $thisdata[4] = ucitem($thisdata[4]);
        $thisdata[5] = ucitem($thisdata[5]);
        $doPhrase = false;
        $augPhrase = '';
        $augPhrases = '';
        $cutPhrase = str_replace($cutList, "", $thisdata[4]);
        $cutPhrase = trim($cutPhrase);
        $cutPhrases = str_replace($cutListPl, "", $thisdata[5]);
        $cutPhrases = trim($cutPhrases);
        $checkPhrase = ($cutPhrase != $thisdata[4]) ? "True" : "False";
        if ($cutPhrase != $thisdata[4] || $cutPhrase != $thisdata[3]) {
            foreach ($cutList as $i => $t) {
                if (strpos($thisdata[4], $t) !== false) {
                    if (strpos($thisdata[4], $t) !== false && strpos($thisdata[3], $repList[$i]) === false) {
                        $augPhrase = $cutPhrase." ".$repList[$i];
                        $doPhrase = true;
                    }
                    if ($cutPhrase." ".$repList[$i] != $thisdata[3] && $augPhrase == '') {
                        $augPhrase = $cutPhrase." ".$repList[$i];
                        $doPhrase = true;
                    }
                    if (strpos($thisdata[5], $cutListPl[$i]) !== false && strpos($thisdata[3], $repListPl[$i]) === false) {
                        $augPhrases = $cutPhrases." ".$repListPl[$i];
                        $doPhrase = true;
                    }
                }
            }
        }
        //print "<b>".$thisdata[3]." / ".$thisdata[4]."</b>: $cutPhrase  |  $cutPhrases  || $checkPhrase - $doPhrase ||  $augPhrase | $augPhrases\r\n<br />";
        if ($searchName[$thisdata[3]] == null) {
            $sname = ($thisdata[3] == $thisdata[2]) ? "[[".$thisdata[2]."]]" : "[[".$thisdata[2]."|".$thisdata[3]."]]";
            $searchName[$thisdata[3]] = $sname;
            if ($thisdata[3] != $thisdata[4]) {
                $searchName[$thisdata[4]] = "[[".$thisdata[2]."|".$thisdata[4]."]]";
            }
            if ($thisdata[3] != $cutPhrase) {
                $searchName[$cutPhrase] = "[[".$thisdata[2]."|".$cutPhrase."]]";
            }
            if ($doPhrase == true) {
                $searchName[$augPhrase] = "[[".$thisdata[2]."|$augPhrase]]";
                $searchName[$augPhrases] = "[[".$thisdata[2]."|$augPhrases]]";
            }
            if ($thisdata[3] != $thisdata[5]) {
                $searchName[$thisdata[5]] = "[[".$thisdata[2]."|".$thisdata[5]."]]";
            }
            if ($thisdata[3] != $cutPhrases) {
                $searchName[$cutPhrases] = "[[".$thisdata[2]."|".$cutPhrases."]]";
            }
        }

    }
    $searchName['Lightweight Steel'] = "[[Lt. Steel Sheet|Lightweight Steel]]";
    if ($listType == "none") {

        $keys = array_map('strlen', array_keys($searchName));
        array_multisort($keys, SORT_DESC, $searchName);
        
        $keyList = array();
        $revertList = array();
        $count = 0;
        
        foreach ($searchName as $key => $currow) {
            $keyList[$key] = "nx".$count."nx";
            $revertList["nx".$count."nx"] = $currow;
            $count++;
        }
        
        $textListing = str_replace(array("\r\n", "\r", "\n"), '[br]', $textListing);
        foreach ($keyList as $key => $currow) {
            $textListing = str_replace($key, $currow, $textListing);
        }
        foreach ($revertList as $key => $currow) {
            $textListing = str_replace($key, $currow, $textListing);
        }
        $textListing = str_replace('[br]', "\r\n<br />", $textListing);
        print $textListing;
    } elseif ($listType == 'synergy') {
        $textListing = str_replace(array("\r\n", "\r", "\n"), '[br]', $textListing);
        $textListing = str_replace("\t", '|', $textListing);
        $text = explode('[br]', $textListing);
        $lim = count($text);
        $count = 0;
        $output = array();
        $output[0] = array();
        $curOp = 0;
        $skill = '';
        while ($count < $lim) {
            $curCount = $count;
            $count++;
            if (strpos($text[$curCount], '<') !== false && strpos($text[$curCount], '>') !== false) {
                $rank = str_replace(array("<", ">", "Rank:"), '', $text[$curCount]);
                $text[$curCount] = trim($rank);
                $curOp = $rank;
                $output[$curOp] = array();
                $count++;
                $curCount++;
                /*foreach ($skillRanks as $r => $curRank) {
                    if (strpos($text[$curCount], '<'.$curRank) !== false) {
                        $curOp = $curRank;
                        $output[$curOp] = array();
                        $count++;
                        $curCount++;
                    }
                } */
            }
            $next = false;
            while ($next == false) {
                $tester = trim($text[$curCount]);
                if (strlen($tester) == 0) {
                    $count++;
                    $curCount++;
               } else {
                   $next = true;
               }
            }
            $currow = explode('|', $text[$curCount]);
            if (trim($currow[1]) == 'Required Skill(s)' || trim($currow[1]) == 'Required Skill' || trim($currow[1]) == 'Required Craft' || trim($currow[1]) == 'Required Crafting Skill') {
                $count++;
                $curCount++;
                $currow = explode('|', $text[$curCount]);
            }
            $curHold = array();
            foreach($currow as $k => $rowpiece) {
                $currow[$k] = trim($rowpiece);
            }
            $curHold[0] = (isset($searchName[$currow[0]])) ? $searchName[$currow[0]] : "[[".$currow[0]."]]";
            $curHold[1] = array("[[".$currow[1]."]]");
            $matList = explode(',', $currow[2]);
            foreach($matList as $k => $curmat) {
                $splodeText = (strpos($curmat, ' x ' !== false)) ? ' x ' : ' x';
                $matsplode = explode($splodeText, $curmat);
                $matsplode[0] = trim($matsplode[0]);
                $matsplode[0] = (isset($searchName[$matsplode[0]])) ? $searchName[$matsplode[0]] : "[[".$matsplode[0]."]]";
                if (count($matsplode) > 1) {
                    $matsplode[1] = trim($matsplode[1]);
                    $matList[$k] = implode(' x ', $matsplode);
                } else {
                    $matList[$k] = $matsplode[0];
                }
            }
            $curHold[2] = implode(', ', $matList);
            $next = false;
            while ($next == false) {
                $nextcheck = str_replace($skillList, 'check', trim($text[$count]));
                if ($nextcheck == 'check') {
                    array_push($curHold[1], "[[".trim($text[$count])."]]");
                    $count++;
               } else {
                   $next = true;
               }
            }
            $curHold[1] = implode("&lt;br /&gt;", $curHold[1]);
            if (strlen($curHold[0]) > 0) {
                $currow = implode('||', $curHold);
                $currow = str_replace('[[-]]', '-', $currow);
                array_push($output[$curOp], $currow);
            }
        }
        foreach ($output as $key => $currow) {
            $skill = ($key != 0) ? '' : "&lt;div align=\"center\"&gt;'''&lt;Rank: $key&gt;'''&lt;/div&gt;\r\n<br />";
            if (count($currow) > 0) {
                print "$skill{| border=1
<br />|-
<br />|
<br />{| width=600 border=0
<br />|- BGCOLOR=\"#ADBDCC\"
<br />! width=\"20%\" | Item
<br />! width=\"20%\" | Required Crafting Skill
<br />! width=\"60%\" | Ingredients";
                foreach ($currow as $key => $curout) {
                    $curout = explode('||', $curout);
                    $start = ($key%2 == 0) ? "BGCOLOR=\"#EAF0FF\" align=\"center\"" : "align=\"center\"";
                     print "\r\n<br />|- $start
<br />| BGCOLOR=\"#CEE0F2\" | ".$curout[0]."
<br />| ".$curout[1]."
<br />| ".$curout[2];
                }
                print "\r\n<br />|-
<br />|}
<br />|}
<br />
<br />";
            }
        }
    } else {
        if ($listType == "comma") {
            $exp = explode(',', $textListing);
        } else  {
            $exp = explode('/', $textListing);
        }
        $output = array();
        foreach ($exp as $key => $currow) {
            $currow = trim($currow);
            if (isset($searchName[$currow])) {
                array_push($output, $searchName[$currow]);
            } else {
                array_push($output, $currow);
            }
        }
        if ($listType == "comma") {
            $text = implode(', ', $output);
        } else  {
            $text = implode(' / ', $output);
        }
        print "<b>Output</b><br />\r\n$text";
    }

} else {
    print "This form if for automagically making wiki-links out of large amounts
    of text.  If at all possible, please avoid using the non-deliminated option,
    as it soaks up tons of processing power.<br />
  <form id=\"form1\" name=\"form1\" method=\"post\" action=\"Text-O-Matic.php\">
  <label>Text Listing<br />
  <textarea name=\"textListing\" id=\"textListing\" cols=\"45\" rows=\"5\"></textarea>
  </label>
  <p>
    <label>
    <input type=\"radio\" name=\"listType\" id=\"listType\" value=\"comma\" checked=\"checked\" />
    Comma deliminated</label>
    <label>
    <input type=\"radio\" name=\"listType\" id=\"listType\" value=\"slash\" />
    Slash deliminated</label>
    <label>
    <input type=\"radio\" name=\"listType\" id=\"listType\" value=\"synergy\" />
    S-E issued Synergy Table</label><label>
    <input type=\"radio\" name=\"listType\" id=\"listType\" value=\"none\" />
    No delmination (This is going to suck!)</label>
  </p>
  <p>
    <label>
    <input type=\"submit\" name=\"Submit\" id=\"Submit\" value=\"Submit\" />
    </label>
    <label>
    <input type=\"reset\" name=\"Reset\" id=\"Reset\" value=\"Reset\" />
    </label>
  </p>
</form>";

}
?>
