<?php    
    include '../database.php';

    function retrieveStockedMaterialsAsListForBlanks($db, $userRow, $type="", $materialID=-1, $inControlName=""){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableMaterialRowCellHTML = '';

        // Set the category HTML as though category is correct
        $whereHTML = 'WHERE 1=1 ';
            
        // Sort as Category then name
        $sort = "Category DESC, ms.Type DESC, m.Name, ms.Amount ";
        
        // Determine if the selected company is NOT the first one
        if ($type != null && 
            $type != -1){
            // Add a category in the where
            $whereHTML = $whereHTML . 'AND ms.Type="' . $type . '" ';
        }
            
        // Determine if the selected company is NOT the first one
        if ($materialID != null && 
            $materialID != -1){
            // Add a type in the where
            $whereHTML = $whereHTML . 'AND m.MaterialID=' . $materialID . ' ';
        }
        
        // Determine if they are at a level to manage material stock
        switch ($userRow["UserLevel"]){
            case 'MID-MANAGEMENT':
            case 'MANAGEMENT':
            case 'EXECUTIVE':
            case 'SU':
                $updateableTitleRowCellHTML = '
                            <div class="cell ssUpdateCell">
                                <p><b>Edit</b></p>
                            </div>
                        ';

                break;
        }
        
        // Initialize the return
        $result = 
            '<li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell ssNameCell" onclick="location.href=\'stockedMaterials.php?sort=1\';" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell ssCatCell" onclick="location.href=\'stockedMaterials.php?sort=5\';" style="cursor: pointer;">
                        <p><b>Category</b></p>
                    </div>
                    <div class="cell ssTypeCell" onclick="location.href=\'stockedMaterials.php?sort=10\';" style="cursor: pointer;">
                        <p><b>Type</b></p>
                    </div>
                    <div class="cell ssAmountCell" onclick="location.href=\'stockedMaterials.php?sort=15\';" style="cursor: pointer;">
                        <p><b>Amount</b></p>
                    </div>
                    <div class="cell ssLLCell" onclick="location.href=\'stockedMaterials.php?sort=20\';" style="cursor: pointer;">
                        <p><b>Low Level</b></p>
                    </div>
                    <div class="cell ssUpdateCell">
                        <p><b>Select</b></p>
                    </div>
                </div>
            </li>';

        try {
            // Setup the query to be where they only get users in their company
            // and tasks that are NOT in stocked status
            $sql = 'SELECT ms.*, m.Category, m.MaterialRowColor, m.Name AS MaterialName  
                    FROM materialstock ms, 
                         material m ' .
                    $whereHTML . '
                    AND m.MaterialID = ms.MaterialID
                    ORDER BY ' . $sort . ';';
            
            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "material_stock_bymaterialandtype occurance 1");

            // Determine if there are any rows before attempting to loop through them
            if ($rows != null && 
                mysqli_num_rows($rows)>0){

                //Set the current type to nothing
                $loopToolCategory='';

                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Check the variables for null and fix
                    $controlName=($inControlName==null?'\'none\'':$inControlName);
                    $materialStockID=($row["MaterialStockID"]==null?"none":$row["MaterialStockID"]);
                    $dimension1=($row["Dimension1"]==null?0:$row["Dimension1"]);
                    $dimension2=($row["Dimension2"]==null?0:$row["Dimension2"]);
                    $dimension3=($row["Dimension3"]==null?0:$row["Dimension3"]);
                    $wallThickness=($row["WallThickness"]==null?0:$row["WallThickness"]);
                    
                    // Determine if this one is an extrusion, tube or round
                    $disableDimension1=true;
                    if ($row["Type"]=="Round" || 
                        $row["Type"]=="Extrusion" || 
                        $row["Type"]=="Tube"){
                        // Swap the dimensions.  This is to not creat confusion as how the programmers currently
                        // think about doing things.  They believe Dimension 1 to be 'x' which equates to the 
                        // cut dimension in their mind.  TODO: Do we ever match these up?
                        $dimension1=($row["Dimension3"]==null?0:$row["Dimension3"]);
                        $dimension2=($row["Dimension1"]==null?0:$row["Dimension1"]);
                        $dimension3=($row["Dimension2"]==null?0:$row["Dimension2"]);
                        
                        // Set a flag to allow cut length
                        $disableDimension1=false;
                    }
                    
                    // Create the material row cell
                    $updateableMaterialRowCellHTML = 
                            '        <div class="cell ssUpdateCell">
                                        <span>
                                            <table>
                                                <tr>
                                                    <td>
                                                        <button type=button onclick="javascript:stockSelected(' . $controlName . ', ' . $materialStockID . ', ' . $dimension1 . ', ' . $dimension2 . ', ' . $dimension3 . ', ' . $wallThickness . ', ' . $disableDimension1 . ');" title="Choose a this stock as the stock for the blank." >Select</button>
                                                    </td>
                                                </tr>
                                            </table>
                                        </span>
                                    </div>';

                    // Increment the row
                    $amount++;

                    // Determine what color this row should be
                    $typeColor="#FFFFFF";
                    switch($row["Type"]){
                        case 'Tube':
                            $typeColor='#f47d42';
                            break;
                        case 'Round':
                            $typeColor='#ae82d8';
                            break;
                        case 'Plate':
                            $typeColor='#e585df';
                            break;
                        case 'Other':
                            $typeColor='#f7e7d7';
                            break;
                        case 'Extrusion':
                            $typeColor='#789a9e';
                            break;
                        case 'Cast':
                            $typeColor='#e8d08f';
                            break;
                        default:
                            $typeColor='#FFFFFF';
                            break;
                    }
                        
                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // Determine if this is NOT the first type
                        if ($loopToolCategory!=''){
                            // Finish the last type div
                            $result = $result . '</DIV>';
                        }

                        // Set the type we are keeping track of as the new type
                        $loopToolCategory=$row["Category"];

                        // set the ID to have underscores where spaces are
                        $id = str_replace(" ", "_", trim($loopToolCategory, "'"));

                        // Set the name of the new type as the ID
                        $result = $result . '<DIV id="' . $id . '">';
                    }
                    
                    // Determine if the amount is lower than the low level
                    $alertBackground = '';
                    $alertBackgroundColor = '';
                    if ($row["Amount"]<=$row["LowReorderLevel"]){
                        // Add a border to the amount in question
                        $alertBackground = ' alertBackground';
                        $alertBackgroundColor='style="background-color: #FFFFFF"';
                    }

                    // Add this option to the select
                    $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: '. $row["MaterialRowColor"] . '; border-style: solid; border-color: BLACK;">
                                <div class="cell ssNameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div>
                                <div class="cell ssCatCell">
                                    <span>
                                        <p>' . $row["Category"] . '</p>
                                    </span>
                                </div>
                                <div class="cell ssTypeCell" style="background-color: '. $typeColor . ';">
                                    <span>
                                        <p>' . $row["Type"] . '</p>
                                    </span>
                                </div>
                                <div class="cell ssAmountCell ' . $alertBackground . '" ' . $alertBackgroundColor . '>
                                    <span>
                                        <p>' . $row["Amount"] . ' ' . $row["Units"] . '</p>
                                    </span>
                                </div>
                                <div class="cell ssLLCell">
                                    <span>
                                        <p>' . $row["LowReorderLevel"] . '</p>
                                    </span>
                                </div>' . 
                                $updateableMaterialRowCellHTML . '
                            </div>
                        </li>';

                    // Determine if the loop type is different than the last one
                    if ($loopToolCategory!=$row["Category"]){
                        // End the DIV Set the name of the type as the ID
                        $result = $result . '<DIV id="' . $loopToolCategory . '"';
                    }
                }
                
                // Determine if the loop did the loopty loop
                if ($loopToolCategory!=''){
                    // Finish the last type div
                    $result = $result . '</DIV>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    $db = new Database();
    $db->setupTmsDB();

    // check the passed in session ID
    if (isset($_GET['sessionID']) ){
        // get the passed in session ID
        $sessionID = $_GET['sessionID'];
    }

    // Set the return as fail at first
    $return="Fail";
    
    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser($sessionID);
    if (mysqli_num_rows($currentUser)==1){
        // Set defaults for the passed in variables
        $type="";
        $material=-1;
        $controlName="";

        // now determine if it was posted via get.  That will override it.
        if (isset($_GET['type']) ){
            // Hold on to the type passed in
            $type = $_GET['type'];
        }

        // Determine if the material is passed in
        if (isset($_GET['material'])){
            // Set the material type to the one passed in
            $material = $_GET['material'];
        }

        // Determine if the control name is passed in
        if (isset($_GET['controlname'])){
            // Set the control name to the one passed in
            $controlName = $_GET['controlname'];
        }

        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
        
        $return = retrieveStockedMaterialsAsListForBlanks($db, $userRow, $type, $material, $controlName);
    }
    
    echo $return;
?>   
