<?php
    function getActiveTypeAsSelectOptions($db, $userRow, $selectName, $selected, $onChange, $style, $addAllOption, $fieldsDisabled){
        try {
            // Initialize the return
            $result = '';

            // Determine if we have an onchange event
            $onChangeHTML = '';
            if ($onChange!=null){
                // Set the onChange of the select to be what was passed in
                $onChangeHTML = $onChange;
            }

            // Determine if the ALL option is added
            if ($addAllOption) {
                // Add ALL to the beginning array
                $result = '<option value="-1">ALL TYPES</option>';
            }
            
            // Create the array of category values by querying the database
            $sql = "SELECT DISTINCT Category FROM material ORDER BY Category DESC;";
            
            // Query the database
            $rows = $db->queryDB($sql, $userRow, "materiallist_presentation occurance 1");
            
            // Loop through the returned results
            while ($row=mysqli_fetch_array($rows)){
                // Set it as not selected at first
                $selectedHTML='';
                
                // Trim it down
                $loopCategory=trim($row["Category"]);

                // Determine what the user's level is that we are editing
                if ($loopCategory==$selected){
                    // Set this as the selected one
                    $selectedHTML = "selected";
                } 
                
                // Add this option
                $result = $result . '<option value="' . $loopCategory . '" ' . $selectedHTML . '>' . $row["Category"] . '</option>';
            }

            // Start and finish the select statement
            $result='<select id="' . $selectName . '" name="' . $selectName . '" style="' . $style . '" onchange="' . $onChangeHTML . '" ' . $fieldsDisabled . '>' . $result . '</select>';

        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function retrieveMaterialsAsList($db, $userRow, $category, $sortNumber){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableMaterialRowCellHTML = '';

        // Clear the category HTML
        $categoryHTML = '';
            
        // Determine if the category is a number greater than 0
        if ($category!=-1){
            // Set the category HTML as though category is correct
            $categoryHTML = 'WHERE m.Category="' . $category . '" ';
        }
        
        // Determine if there is actually a sort passed in
        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as Category then name
                    $sort = "m.Category DESC, m.Name, m.Description ";

                    break;
                case 5:
                    // Sort as Name then Category
                    $sort = "m.Name, m.Category DESC, m.Description ";

                    break;
                case 10:
                    // Sort as Name then Category
                    $sort = "m.Description, m.Name, m.Category DESC ";

                    break;
                default:
                    // Sort as Category then name
                    $sort = "m.Category DESC, m.Name, m.Description ";

                    break;
            }
        }

        // Determine if they are at a level to manage tasks
        switch ($userRow["UserLevel"]){
            case 'MID-MANAGEMENT':
            case 'MANAGEMENT':
            case 'EXECUTIVE':
            case 'SU':
                $updateableTitleRowCellHTML = '
                            <div class="cell updateCell">
                                <p><b>Edit</b></p>
                            </div>
                        ';

                break;
        }
        
        // Get the category drop down list
        $categorySelectHTML=getActiveTypeAsSelectOptions($db, $userRow, 'category', $category, 'javascript:CreateAndGotoSearchOptions();', '', true, false);

        // Initialize the return
        $result = 
            'Material Type: ' 
            .
            $categorySelectHTML 
            . 
            '<br><br>
            <input type="hidden" id="sortNumber" name="sortNumber" value="' . $sortNumber . '"/>
            <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell catCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Category</b></p>
                    </div>
                    <div class="cell nameCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell descCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Description</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </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 m.*, msm.AmountOnMaterialStock 
                  FROM material m 
                  LEFT OUTER JOIN 
                       (SELECT COUNT(*) AS AmountOnMaterialStock, MaterialID 
                        FROM materialstock GROUP BY MaterialID) msm ON m.MaterialID = msm.MaterialID ' .
                  $categoryHTML .
                  'ORDER BY ' . $sort . ';';

            // Query the database for the tasks 
            $rows = $db->queryDB($sql, $userRow, "materiallist_presentation occurance 2");

            // 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)){
                    // Assign the delete button attributes as though deletion is an option
                    $deleteButtonTextColor = 'LIMEGREEN';
                    $deleteButtonTitle = 'Remove this material.';
                    $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this material?\')) ' .
                                           '{window.location=\'redirectors/delete_material.php?deleteMaterialID=' . $row["MaterialID"] . '\';}"';

                    // Determine if this company is assigned to any tasks
                    if ($row["AmountOnMaterialStock"]!=null){
                        // Assign the delete buttons attributes such that deletion will not happen
                        $deleteButtonTextColor = 'RED';
                        $deleteButtonTitle = 'Check what stock or tools this vendor may be assigned to.';
                        $deleteButtonOnClick = 'onclick="javascript:alert(\'This material is assigned to '. $row["AmountOnMaterialStock"] . 
                                               ' material stock\n\nRemove material from stock before attempting to delete again.\');"';
                    }

                    // Give the the delete option
                    $updateableMaterialRowCellHTML = '
                        <div class="cell updateCell">
                            <span>
                                <table>
                                    <tr>
                                        <td>
                                            <input type="button" style="font-size:11px; color:' . $deleteButtonTextColor . ';" value="X" title="' . 
                                            $deleteButtonTitle . '" ' . $deleteButtonOnClick . '/>
                                        </td>
                                        <td>
                                            <input type="button" style="font-size:11px;" value="..." title="Edit this material." ' . 
                                            'onclick="javascript:window.location=\'updateMaterialType.php?updateMaterialID=' . $row["MaterialID"] . '\';"/>
                                        </td>
                                    </tr>
                                </table>
                            </span>
                        </div>
                        ';

                    // Increment the row
                    $amount++;

                    // 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 . '">';
                    }

                    // 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 catCell">
                                    <span>
                                        <p>' . $row["Category"] . '</p>
                                    </span>
                                </div>
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div> 
                                <div class="cell descCell">
                                    <span>
                                        <p>' . $row["Description"] . '</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;
    }
?>       
