<?php
ini_set("display_errors", "on");
error_reporting(E_ALL ^ E_NOTICE);

$fileSystem = $_GET['fileSystem'];
$id = $_GET['id'];
$ind = $_GET['ind'];
$action = $_GET['action'];
$replace = $_GET['replace'];
$curFile = $_GET['curFile'];
$batchList = $_POST['batchList'];

$questList = array('', 'BastokQuests', 'SanDorianQuests', 'WindurstQuests', 'JeunoQuests', 'OtherQuests', 'ZilartQuests', 'AhtUrhganQuests', 'GoddessQuests', 'AbysseaQuests');
$missionList = array('', 'BastokMissions', 'SanDorianMissions', 'WindurstMissions', 'ZilartMissions', 'PromathiaMissions', 'AhtUrhganMissions', 'GoddessMissions', 'campaignOp', 'CrystallineMissions', 'KupoMissions', 'ShantottoMissions');

if ($curFile > 0 && $fileSystem == 'Quests') {
    $fileSystem = $questList[$curFile];
    $id = $_GET['questNum'];
} elseif ($curFile > 0 && $fileSystem == 'Missions') {
    $fileSystem = $missionList[$curFile];
    $id = $_GET['missionNum'];
}

$folderPath = "Image Attributes";

$flagListIn = array('None', 'CanUse', 'CanTradeNPC', 'NoAuction', 'CanEquip', 'NoSale', 'NoDelivery', 'Ex');
$flagListOut = array('', 'Can Use', 'NPC tradable', 'Not auctionable', 'Equippable', 'Not vendorable', 'Not sendable', 'Not sendable, Exclusive');

$characterList = array();

$characterList['Space'] = array('', 7);
$characterList['A'] = array('Capital A.png', 11);
$characterList['B'] = array('Capital B.png', 11);
$characterList['C'] = array('Capital C.png', 10);
$characterList['D'] = array('Capital D.png', 10);
$characterList['E'] = array('Capital E.png', 10);
$characterList['F'] = array('Capital F.png', 9);
$characterList['G'] = array('Capital G.png', 11);
$characterList['H'] = array('Capital H.png', 10);
$characterList['I'] = array('Capital I.png', 6);
$characterList['J'] = array('Capital J.png', 9);
$characterList['K'] = array('Capital K.png', 11);
$characterList['L'] = array('Capital L.png', 10);
$characterList['M'] = array('Capital M.png', 12);
$characterList['N'] = array('Capital N.png', 10);
$characterList['O'] = array('Capital O.png', 11);
$characterList['P'] = array('Capital P.png', 10);
$characterList['Q'] = array('Capital Q.png', 12);
$characterList['R'] = array('Capital R.png', 11);
$characterList['S'] = array('Capital S.png', 10);
$characterList['T'] = array('Capital T.png', 10);
$characterList['U'] = array('Capital U.png', 10);
$characterList['V'] = array('Capital V.png', 11);
$characterList['W'] = array('Capital W.png', 14);
$characterList['X'] = array('Capital X.png', 11);
$characterList['Y'] = array('Capital Y.png', 11);
$characterList['Z'] = array('Capital Z.png', 11);
$characterList['Grave accent'] = array('Grave accent.png', 9);
$characterList['1'] = array('Number 1.png', 9);
$characterList['2'] = array('Number 2.png', 9);
$characterList['3'] = array('Number 3.png', 9);
$characterList['4'] = array('Number 4.png', 9);
$characterList['5'] = array('Number 5.png', 9);
$characterList['6'] = array('Number 6.png', 9);
$characterList['7'] = array('Number 7.png', 9);
$characterList['8'] = array('Number 8.png', 9);
$characterList['9'] = array('Number 9.png', 9);
$characterList['0'] = array('Number 0.png', 9);
$characterList['Hyphen'] = array('Hyphen.png', 8);
$characterList['Equal sign'] = array('Equal sign.png', 9);
$characterList['Right square bracket'] = array('Right square bracket.png', 8);
$characterList['Left square bracket'] = array('Left square bracket.png', 8);
$characterList['Backslash'] = array('Backslash.png', 7);
$characterList['Semicolon'] = array('Semicolon.png', 5);
$characterList['Apostrophe'] = array('Apostrophe.png', 5);
$characterList['Comma'] = array('Comma.png', 5);
$characterList['Period'] = array('Period.png', 5);
$characterList['Slash'] = array('Slash.png', 7);
$characterList['a'] = array('Lowercase a.png', 9);
$characterList['b'] = array('Lowercase b.png', 9);
$characterList['c'] = array('Lowercase c.png', 9);
$characterList['d'] = array('Lowercase d.png', 9);
$characterList['e'] = array('Lowercase e.png', 9);
$characterList['f'] = array('Lowercase f.png', 7);
$characterList['g'] = array('Lowercase g.png', 9);
$characterList['h'] = array('Lowercase h.png', 9);
$characterList['i'] = array('Lowercase i.png', 5);
$characterList['j'] = array('Lowercase j.png', 6);
$characterList['k'] = array('Lowercase k.png', 9);
$characterList['l'] = array('Lowercase l.png', 5);
$characterList['m'] = array('Lowercase m.png', 12);
$characterList['n'] = array('Lowercase n.png', 9);
$characterList['o'] = array('Lowercase o.png', 10);
$characterList['p'] = array('Lowercase p.png', 9);
$characterList['q'] = array('Lowercase q.png', 9);
$characterList['r'] = array('Lowercase r.png', 6);
$characterList['s'] = array('Lowercase s.png', 8);
$characterList['t'] = array('Lowercase t.png', 7);
$characterList['u'] = array('Lowercase u.png', 9);
$characterList['v'] = array('Lowercase v.png', 9);
$characterList['w'] = array('Lowercase w.png', 11);
$characterList['x'] = array('Lowercase x.png', 9);
$characterList['y'] = array('Lowercase y.png', 9);
$characterList['z'] = array('Lowercase z.png', 8);
$characterList['Tilde'] = array('Tilde.png', 12);
$characterList['Exclamation point'] = array('Exclamation point.png', 7);
$characterList['At sign'] = array('At sign.png', 11);
$characterList['Number sign'] = array('Number sign.png', 10);
$characterList['Dollar sign'] = array('Dollar sign.png', 8);
$characterList['Percent sign'] = array('Percent sign.png', 13);
$characterList['Caret'] = array('Caret.png', 9);
$characterList['Ampersand'] = array('Ampersand.png', 11);
$characterList['Asterisk'] = array('Asterisk.png', 9);
$characterList['Left parentheses'] = array('Left parentheses.png', 8);
$characterList['Right parentheses'] = array('Right parentheses.png', 8);
$characterList['Underscore'] = array('Underscore.png', 9);
$characterList['Plus sign'] = array('Plus sign.png', 9);
$characterList['Right curly bracket'] = array('Right curly bracket.png', 7);
$characterList['Left curly bracket'] = array('Left curly bracket.png', 7);
$characterList['Vertical pipe'] = array('Vertical pipe.png', 6);
$characterList['Colon'] = array('Colon.png', 5);
$characterList['Quotation mark'] = array('Quotation mark.png', 7);
$characterList['Less than'] = array('Less than.png', 9);
$characterList['Greater than'] = array('Greater than.png', 9);
$characterList['Question mark'] = array('Question mark.png', 9);
$characterList['Fire'] = array('Fire-Icon.png', 16);
$characterList['Ice'] = array('Ice-Icon.png', 16);
$characterList['Wind'] = array('Wind-Icon.png', 16);
$characterList['Earth'] = array('Earth-Icon.png', 16);
$characterList['Thunder'] = array('Thunder-Icon.png', 16);
$characterList['Water'] = array('Water-Icon.png', 16);
$characterList['Light'] = array('Light-Icon.png', 16);
$characterList['Dark'] = array('Dark-Icon.png', 16);
$characterList['Male Symbol'] = array('Male Symbol.png', 15);
$characterList['Female Symbol'] = array('Female Symbol.png', 15);
$characterList['Dot'] = array('Dot.png', 8);
$characterList['Large H'] = array('Large H.png', 15);
$characterList['Large G'] = array('Large G.png', 15);
$characterList['Large E'] = array('Large E.png', 15);
$characterList['Large T'] = array('Large T.png', 15);
$characterList['Large M'] = array('Large M.png', 15);

$femaleSign = '&#9792;';
$maleSign = '&#9794;';

$elementIn = array("?Element: Fire?", "?Element: Ice?", "?Element: Wind?", "?Element: Earth?", "?Element: Thunder?", "?Element: Water?", "?Element: Light?", "?Element: Dark?", "?Element: Air?");
$elementShort = array("Fire", "Ice", "Air", "Earth", "Thunder", "Water", "Light", "Dark", "Wind");
$elementOut = array("©", "¢", "£", "¤", "¥", "§", "®", "²", "£");

$specialIn = array('¼', '½', '°', '¯', '±', 'µ', '¹', '¾');
$specialOut = array('Male Symbol', 'Female Symbol', 'Dot', 'Large H', 'Large T', 'Large M', 'Large G', 'Large E');

$charList = array(' ', '`', '-', '=', '[', ']', ' \ ', ';', "'", ',', '.', '/', '_', '+', '{', '}', '|', ':', '"', '<', '>', '?', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', "©", "¢", "£", "¤", "¥", "§", "®", "²", '¼', '½', '°', '¯', '±', 'µ', '¹', '¾');
// "³" unused;
$nameList = array('Space', 'Grave accent', 'Hyphen', 'Equal sign', 'Left square bracket', 'Right square bracket', 'Backslash', 'Semicolon', 'Apostrophe', 'Comma', 'Period', 'Slash', 'Underscore', 'Plus sign', 'Left curly bracket', 'Right curly bracket', 'Vertical pipe', 'Colon', 'Quotation mark', 'Less than', 'Greater than', 'Question mark', 'Tilde', 'Exclamation point', 'At sign', 'Number sign', 'Dollar sign', 'Percent sign', 'Caret', 'Ampersand', 'Asterisk', 'Left parentheses', 'Right parentheses', 'Fire', 'Ice', 'Wind', 'Earth', 'Thunder', 'Water', 'Light', 'Dark', 'Male Symbol', 'Female Symbol', 'Dot', 'Large H', 'Large T', 'Large M', 'Large G', 'Large E');

$raceListIn = array('HumeMale', 'HumeFemale', 'ElvaanMale', 'ElvaanFemale', 'TarutaruMale', 'TarutaruFemale', 'Mithra', 'Galka', 'Hume', 'Elvaan', 'Tarutaru');
$raceListOut = array('¯¼', '¯½', '¾¼', '¾½', '±¼', '±½', 'µ', '¹', '¯', '¾', '±');

$skillListIn = array('GreatAxe', 'GreatKatana', 'GreatSword', 'HandToHand', 'PoleArm', 'StringInstrument', 'Thrown', 'WindInstrument');
$skillListOut = array('Great Axe', 'Great Katana', 'Great Sword', 'Hand-to-Hand', 'Polearm', 'String Instrument', 'Throwing', 'Wind Instrument');
$renameIn = array(':', '#', '"');
$renameOut = array('', '', '');



function checkWidth($text, $connector) {
    $maxWidth = 326;
    global $characterList;
    global $elementIn;
    global $elementOut;
    global $charList;
    global $nameList;

    $textSplode = explode('[br]', $text);
    foreach ($textSplode as $key => $curDesc) {
        $descSplode = str_split($curDesc);
        $lineSpace = 0;
        $curWord = 0;
        $lines = array();
        $curLine = 0;
        $word = '';
        $wordWidth = 0;
        $lines[$curLine] = array();
        foreach($descSplode as $subKey => $curSplode) {
            $reg = $curSplode;
            if (ord($curSplode) == 92) {
                $curSplode = 'Backslash';
            } else {
                $curSplode = str_replace($charList, $nameList, $curSplode);
            }
            $lineSpace += $characterList[$curSplode][1];
            $wordWidth += $characterList[$curSplode][1];
            if ($reg == $connector) {
                if ($lineSpace > $maxWidth) {
                    $lineSpace = $wordWidth;
                    $curLine++;
                    $lines[$curLine] = array();
                    $curWord = 0;
                    array_push($lines[$curLine], $word);
                    $word = '' ;
                    $wordWidth = 0;
                } else {
                    array_push($lines[$curLine], $word);
                    $word = '';
                    $wordWidth = 0;
                    $curWord++;
               }
            } else {
                $word .= $reg;
            }
        }
        if ($lineSpace > $maxWidth) {
            $lineSpace = $wordWidth;
            $curLine++;
            $lines[$curLine] = array();
        }
        array_push($lines[$curLine], $word);
        foreach ($lines as $k => $curLine) {
            $lines[$k] = implode($connector, $curLine);
        }
        $con = ($connector == '/') ? '/[br]' : '[br]';
        $textSplode[$key] = implode($con, $lines);
    }
    $con = ($connector == '/') ? '/[br]' : '[br]';
    $text = implode($con, $textSplode);
    return $text;
}

function makeImage($imName, $imDesc, $type, $bat) {
    global $characterList;
    global $charList;
    global $nameList;
    global $specialIn;
    global $specialOut;
    global $renameIn;
    global $renameOut;

    $titleOffset = array(50, 20);
    $firstLineOffset = ($type == 'keyItem') ? array(40, 66) : array(40, 50);
    $imName = str_replace('**', '', $imName);
    $imDesc = str_replace($elementIn, $elementOut, $imDesc);

    if (strpos($imDesc, "Ballista") !== false) {
        $imDesc = str_replace('?', '°', $imDesc);
    }
    $descList = explode('[br]', $imDesc);


    $proto = imagecreatefromjpeg("Image Attributes/Box Attributes/Key Item Prototype.jpg");
    //imagealphablending($proto, true);

    $counter = 0;
    
    if (strlen($imName) > 0) {
        $extSplode = str_split($imName);
        $lineSpace = 0;
        foreach($extSplode as $curExt) {
            if (ord($curExt) == 92) {
                $curExt = 'Backslash';
            } else {
                $curExt = str_replace($charList, $nameList, $curExt);
            }
            $curPrint = $characterList[$curExt];
            if ($curExt != 'Space') {
                $thisLet = imagecreatefrompng("Image Attributes/Letters-White/".$curPrint[0]);
                @imagecopy($proto, $thisLet, ($titleOffset[0]+$lineSpace), $titleOffset[1], 0, 0, $curPrint[1], 16);
            }
            $lineSpace += $curPrint[1];
        }
    }
    
    foreach ($descList as $key => $curDesc) {
        $descSplode = str_split($curDesc);
        $lineSpace = 0;
        foreach($descSplode as $subKey => $curSplode) {
            if (ord($curSplode) == 92) {
                $curSplode = 'Backslash';
            } else {
                $curSplode = str_replace($charList, $nameList, $curSplode);
            }
            $curPrint = $characterList[$curSplode];
            if ($curPrint[0] != '') {
                $thisLet = imagecreatefrompng("Image Attributes/Letters-White/".$curPrint[0]);
                @imagecopy($proto, $thisLet, ($firstLineOffset[0]+$lineSpace), ($firstLineOffset[1]+($counter*16)), 0, 0, $curPrint[1], 16);
            }
            $lineSpace += $curPrint[1];
        }
        $counter++;
    }
    if ($bat == false) {
        header('Content-type: image/jpeg');
        imagejpeg($proto);
        imagedestroy($proto);
    } else {
        $imdest = "ImageDump2/".str_replace($renameIn, $renameOut, $imName).".jpg";
        imagejpeg($proto, $imdest);
        print "http://www.septimusprime.com/bgwiki/$imdest\r\n<br /><br /><img src=\"$imdest\">\r\n<br /><br /><br /><br />";
    }
}

function printImage($imName, $imDesc, $type) {
    global $characterList;
    global $charList;
    global $nameList;
    global $specialIn;
    global $specialOut;
    
    $TitleOffset = array(50, 20);
    $firstLineOffset = ($type == 'keyItem') ? array(40, 66) : array(40, 50);

    $imDesc = str_replace($elementIn, $elementOut, $imDesc);

    $descList = explode('[br]', $imDesc);

    print "<img src=\"Image Attributes/Box Attributes/Key Item Prototype.jpg\"><br />";

    print "<br />";
    if (strlen($imName) > 0) {
        $extSplode = str_split($imName);
        foreach($extSplode as $curExt) {
            if (ord($curExt) == 92) {
                $curExt = 'Backslash';
            } else {
                $curExt = str_replace($charList, $nameList, $curExt);
            }
            $curPrint = $characterList[$curExt];
            if ($curPrint[0] != '') {
                print "<img src=\"Image Attributes/Letters-White/".$curPrint[0]."\">";
            } else {
                print "&nbsp;";
            }
        $lineSpace += $curPrint[1];
        }
    }

    foreach ($descList as $key => $curDesc) {
        $descSplode = str_split($curDesc);
        $lineSpace = 0;
        print "<br />";
        foreach($descSplode as $subKey => $curSplode) {
            if (ord($curSplode) == 92) {
                $curSplode = 'Backslash';
            } else {
                $curSplode = str_replace($charList, $nameList, $curSplode);
            }
            $curPrint = $characterList[$curSplode];
            if ($curPrint[0] != '') {
                print "<img src=\"Image Attributes/Letters-White/".$curPrint[0]."\">";
            } else {
                print "&nbsp;";
            }
            $lineSpace += $curPrint[1];
        }
    }


}

function makeKeyItem($r) {
    $currow = explode('|', $r);

    $desc = explode('[br]', $currow[7], 2);
    if (count($desc) == 2) {
        $currow[7] = implode('|', $desc);
        $row = implode('|', $currow);
        $currow = explode('|', $row);
    }
    $retArray = array();
    $retArray[0] = ucfirst($currow[6]);
    $retArray[1] = checkWidth($currow[8], ' ');
    return $retArray;
}

if (strlen($fileSystem) == 0) {
    print "Master list<br /><a href=\"Quest-O-Matic.php?print=true\">Quests</a><br /><a href=\"Mission-O-Matic.php?print=true\">Missionss</a><br /><a href=\"Key-O-Matic.php?print=true\">Key Items</a><br /><a href=\"Image-O-Matic2.php?action=batch&fileSystem=keyItem\">Key Item Batch</a>";
} elseif ($action == 'batch' && strlen($ind) == 0 && strlen($batchList) == 0) {
    print "This form is for batch processing images from the
    <a href=\"http://wiki.bluegartr.com/bg/Category:Need_Key_Item_Image\" target=\"_blank\">
    BG Wiki Key Item Image category page.</a>  Copy
    and paste a page of links into the following text field to automagically
    generate item images for that page.  Please do not generate more than one page
    (200 images) at a time.<br />
    Addtional information has been included at the bottom of the file, designed
    for Septimus's use for handling batch uploads.<br /><br />
    <form id=\"form1\" name=\"form1\" method=\"post\" action=\"Image-O-Matic2.php?action=batch&fileSystem=keyItem\">
  <label>Item List<br />
  <textarea name=\"batchList\" id=\"batchList\" cols=\"45\" rows=\"5\"></textarea>
  </label>
  <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>";
} elseif ($action == 'batch') {
    $fileName = $fileSystem.'Parse.txt';
    $array = @file($fileName);
    $itemList = array();
    $indList = array();
    if (strlen($ind) > 0) {
        $indList = explode(',', $ind);
        $num = 1;
    } else {
        $indList = explode("\r", $batchList);
        $num = 6;
    }
    foreach($indList as $k => $curInd) {
        $id = -1;
        if ($num == 6) {
            $curInd = str_replace('*', '', $curInd);
            $curInd = str_replace('#', '', $curInd);
            if (stripos($curInd, '(key item)') !== false) {
                $splode = explode('(', $curInd);
                $curInd = $splode[0];
            }
            $curInd = trim($curInd);
        }
        if (strlen($curInd) > 1) {
            foreach ($array as $key => $row) {
                $row = explode('|', $row);
                $comp = ($num == 6) ? ucfirst($row[$num]) : $row[$num];
                if ($comp == $curInd) {
                    $id = $key;
                    break;
                }
            }
        }
        if ($id != -1) {
            if ($fileSystem == 'keyItem') {
                $result = makeKeyItem($array[$id]);
            } else {
                $currow = explode('|', $array[$id]);
                $result = array($currow[3], $currow[4]);
            }

            if ($action == 'print') {
                printImage($result[0], $result[1], $fileSystem);
            } else {
                $res = str_replace($renameIn, $renameOut, $result[0]).".jpg";
                $res = str_replace('**', '', $res);
                array_push($itemList, $res);
                makeImage($result[0], $result[1], $fileSystem, 'batch');
            }
        }
    }
    print "<br /><br /><br />iMacros loop: ".count($itemList)." iterations.<br />\r\n";
    foreach ($itemList as $curVal) {
        print "\"$curVal\"<br />\r\n";
    }
} else {
    if (strlen($fileSystem) > 0) {
        $fileName = $fileSystem.'Parse.txt';
        $array = @file($fileName);

        if (strlen($ind) > 0) {
            foreach ($array as $key => $row) {
                $row = explode('|', $row);
                if ($row[1] == $ind) {
                    $id = $key;
                }
            }
        }
        if ($fileSystem == 'keyItem') {
            $result = makeKeyItem($array[$id]);
        } else {
            $currow = explode('|', $array[$id]);
            $result = array($currow[3], $currow[4]);
            if ($action=='print') {
                print $fileSystem." | ".$fileName."<br />".$currow[3]."<br />".$currow[4]."<br />".$array[$id]."<br />";
            }
        }
        
        if ($action == 'print') {
            printImage($result[0], $result[1], $fileSystem);
        } else {
            makeImage($result[0], $result[1], $fileSystem, '');
        }
    }
}

?>
