<?php
# ---------------------------------------------------------------------
# truc is a tool for requirement and use case tracking
# Copyright (C) 2006 ASDIS - http://sf.net/projects/truc
#
# (rth) Initial truc version based on rth
#       Copyright (C) 2005 George Holbrook - rth@lists.sourceforge.net
#
# This program is distributed under the terms and conditions of the GPL
# See the README and LICENSE files for details
#----------------------------------------------------------------------

if( isset($_POST['mass_req_update']) ) {

	require_once("requirement_group_action_page.php");
	exit;
}

include"./api/include_api.php";
auth_authenticate_user();
define('NO_FOLDER_VIEW',true);
$page                   = basename(__FILE__);
$action_page            = 'requirement_action.php';
$num                    = 0;
$bg_color               = '';
$project_properties     = session_get_project_properties();
$project_name           = $project_properties['project_name'];
$project_id				= $project_properties['project_id'];
if (isset($_GET['filter_req'])) $_POST['filter_req']=$_GET['filter_req'];
$display_options 	= session_set_display_options("requirements", $_POST);
$order_by			= $display_options['order_by'];
$order_dir			= $display_options['order_dir'];
$page_number 		= $display_options['page_number'];

$filter_doc_type		= $display_options['filter']['doc_type'];
$filter_status			= $display_options['filter']['status'];;
$filter_area_covered	= $display_options['filter']['area_covered'];;
$filter_functionality	= $display_options['filter']['functionality'];;
$filter_assign_release	= $display_options['filter']['assign_release'];;
$filter_per_page		= $display_options['filter']['per_page'];;
$filter_show_versions	= $display_options['filter']['show_versions'];;
$filter_search			= $display_options['filter']['requirement_search'];
$filter_priority		= $display_options['filter']['priority'];
$filter_req_id		= $display_options['filter']['filter_req'];
$filter_usecase_id		= $display_options['filter']['filter_usecase'];

html_window_title();
html_print_body();
html_page_title($project_name ." - ". lang_get('req_page'));
html_page_header( $db, $project_name );
html_print_menu();
requirement_menu_print($page);

error_report_check( $_GET );

print"<br>\n";

print"<form action='$page' method=post>\n";

print"<div align=center>\n";

html_print_requirements_filter(	$project_id,
								$filter_doc_type,
								$filter_status,
								$filter_area_covered,
								$filter_functionality,
								$filter_assign_release,
								$filter_per_page,
								$filter_show_versions,
								$filter_search,
								$filter_priority,
                                                                $filter_req_id,
                                                                $filter_usecase_id);

print"<br>\n";

print"</div>\n";

$g_timer->mark_time( "Get requirements" );

$rows_requirement = requirement_get( $project_id, null, $order_by, $order_dir,
									$filter_doc_type, $filter_status, $filter_area_covered, $filter_functionality, $filter_assign_release, $filter_show_versions, null /* $filter_per_page */, $filter_search, $filter_priority, $csv_name="requirements");

//print_r($rows_requirement);
// Put all parents in the $req_tree
$req_tree=array();
$pos=0;
foreach ($rows_requirement as $row) {
  if ($row[REQ_PARENT]==0) {
    $row['is_valid']=true;
    $req_tree[$row[REQ_ID]]=$row;
    $req_tree[$row[REQ_ID]]['childs']=array();
    unset($rows_requirement[$pos]);
  }
  $pos++;
}
$debug=false;
  function requirement_includeway($req) {
    global $project_id;
    global $debug;
    $way=array();
    $cur_req=$req;

    while ($cur_req[REQ_PARENT]!=0) {
      // As long as the requirement is an child
      $way[]=$cur_req;
      // Get the parent as current one
      $cur_req=requirement_get_detail($project_id,$cur_req[REQ_PARENT]);
      $cur_req=$cur_req[0];
    }
      $way[]=$cur_req;
      if ($way[0][REQ_ID]==4) $debug=true;
    return $way;
  }
  function recalc_node($req_tree,$curway) {
    global $debug;
//    if ($debug)  echo "function recalc_node(";print_r($req_tree);echo",";print_r($curway);echo"){<hr>";
    if (count($curway)==1) {
      if (!isset($req_tree[$curway[0][REQ_ID]])) $req_tree[$curway[0][REQ_ID]]=$curway[0];
      $req_tree[$curway[0][REQ_ID]]['is_valid']=true;
//      print_r($req_tree);
//      echo "<hr>";
      return  $req_tree;
    } else {
      $parent=$curway[count($curway)-1];
//      if (!isset($req_tree[$pos]['childs'])) $req_tree[$pos]['childs']=array();
      array_pop($curway);
//      echo "<b>".$parent[REQ_ID]."</b>";print_r($curway);

      if (!isset($req_tree[$parent[REQ_ID]])) { // If the parent isn't linked in tree yet
        $req_tree[$parent[REQ_ID]]=$parent;
        $req_tree[$parent[REQ_ID]]['childs']=array();
        }
      if (!isset($req_tree[$parent[REQ_ID]]['childs'])) $req_tree[$parent[REQ_ID]]['childs']=array();

      $req_tree[$parent[REQ_ID]]['childs']=recalc_node($req_tree[$parent[REQ_ID]]['childs'],$curway);
/*
      if (!isset($req_tree[$pos]['childs'][$curway[count($curway)-1][REQ_ID]]))
      $req_tree[$pos]['childs'][$curway[count($curway)-1][REQ_ID]]=$curway[count($curway)-1][REQ_ID];
      $req_tree[$pos]['childs']=recalc_node($req_tree[$pos]['childs'],$curway);
      */
      return $req_tree;
    }
  }

foreach ($rows_requirement as $row) {
  $curway=requirement_includeway($row);
//  echo "<hr>";echo "<hr>";  print_r($curway);echo "<hr>";echo "<hr>";
  if (count($curway)==0) {
//    echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";echo "<hr>";
    // Toplevel requirement
  } else {
    // Subrequirement
    // $curway=Leaf -> Node2 -> Node1 -> Root
    $req_tree=recalc_node($req_tree,$curway);
  }
}

$g_timer->mark_time( "Finished get requirements" );

function requirementtree_calculatepercent($req_tree_entry) {
  $percent=array();
  $states=requirement_get_statuses();
  foreach($states as $state) {
    $percent[$state]=0;
    $percent['UC '.$state]=0;
  }
  if ($req_tree_entry[REQ_VERS_STATUS]=="") $req_tree_entry[REQ_VERS_STATUS]="New";
  $percent[$req_tree_entry[REQ_VERS_STATUS]]++;

  if ($req_tree_entry[REQ_VERS_STATUS]=="Rejected") return $percent;

  if (isset($req_tree_entry['is_valid'])){
    $req_test_relationships = requirement_get_test_relationships($req_tree_entry[REQ_ID]);
    if( !empty($req_test_relationships) ) {
      foreach($req_test_relationships as $row_req_test_rels) {
        if ($row_req_test_rels[TEST_STATUS]!='Rejected')  {
			if (!isset($percent['UC '.$row_req_test_rels[TEST_STATUS]])) $percent['UC '.$row_req_test_rels[TEST_STATUS]]=0;
			$percent['UC '.$row_req_test_rels[TEST_STATUS]]++;
	       }
      }
    }
  }

  if (isset($req_tree_entry['childs'])) {
    foreach ($req_tree_entry['childs'] as $child) {
      $sub_percent=requirementtree_calculatepercent($child);
      foreach($states as $state) {
        if ($state!='Rejected') $percent[$state]=$percent[$state]+$sub_percent[$state];
      }
    }
  }
  return $percent;
}
function requirementtree_print($req_tree,$depth,$filter) {
  global $project_id;
$row_style				= '';
//        print_r($req_tree);
        $count=count($req_tree);
        $pos=0;
  	foreach($req_tree as $row_requirement) {
                if ($filter==0 || $row_requirement[REQ_ID]==$filter) {
                $pos++;

		$percent=requirementtree_calculatepercent($row_requirement);
		$req_id					= util_pad_id( $row_requirement[REQ_ID] );
		$req_name				= $row_requirement[REQ_FILENAME];
		$req_version_id			= $row_requirement[REQ_VERS_UNIQUE_ID];
		$req_version			= $row_requirement[REQ_VERS_VERSION];
		$req_version_filename	= $row_requirement[REQ_VERS_FILENAME];
		$req_version_detail		= $row_requirement[REQ_VERS_DETAIL];
		$req_doc_type			= $row_requirement[REQ_DOC_TYPE_NAME];
		$req_version_status		= $row_requirement[REQ_VERS_STATUS];
		$req_area_covered		= $row_requirement[REQ_AREA_COVERAGE];
		$req_locked_by			= $row_requirement[REQ_LOCKED_BY];
		$req_locked_date		= $row_requirement[REQ_LOCKED_DATE];

		$row_style = html_tbl_alternate_bgcolor($row_style);

		$rows_functions = requirement_get_functionality($project_id, $row_requirement[REQ_ID]);

		# Rows

                if ($count==1 && !isset($row_requirement['childs'])) print"<tr class='tree_single_row"; elseif ($pos==1)  print"<tr class='tree_first_row"; elseif  ($pos==$count) print "<tr class='tree_last_row"; else print"<tr class='tree_row";

                if (!isset($row_requirement['is_valid'])) echo "_invalid";

                echo "'>\n";
//		if ($depth!=0) echo "<td COLSPAN=".($depth)." style='background-color:#AAA' width=".($depth*10)."></td>";
		print"<td class='tbl-l'><input type='checkbox' style=' padding:0px;margin:0px;' name='row_req_arr[{$req_id}][{$req_version_id}]'></td>";
		print"<td class='tbl-l' style=' padding:0px;'><a href='requirement_detail_page.php?req_id=$req_id&amp;req_version_id=$req_version_id'>$req_id</a></div></td>\n";
//		print"<td class='tbl-l' >$req_version_detail</td>\n";
// <div style='border-left:".($depth*7)."px #DFDFDF solid;height:23px;padding:0px;margin:0px;padding-top:3px;padding-left:5px'>
		print"<td class='tbl-l' style='white-space:nowrap;'>";
       		for ($i=0;$i<$depth;$i++) {
                  echo ".&nbsp;&nbsp;&nbsp;";
                }

                print"<a href='requirement_page.php?filter_req=$req_id' >$req_name</a></td>\n";
                if ($req_doc_type!="")
                    print"<td  style='border-left:1px solid #999999;text-align:center' ><span title='$req_doc_type'><img src='images/icons/RTypes/$req_doc_type.png' alt='$req_doc_type'></span></td>\n";
		  else
                    print"<td  style='border-left:1px solid #999999;text-align:center' ></td>\n";
		print"<td class='tbl-l' style='border-left:1px solid #999999;' nowrap >$req_version</td>\n";
//		print"<td class='tbl-l' style='border-left:1px solid #999999;' >$req_doc_type</td>\n";
		print"<td class='tbl-l' style='border-left:1px solid #999999;' ><span title='$req_version_status'><img src='images/icons/RStatus/$req_version_status.png' alt='$req_version_status'></span>
               $req_version_status</td>\n";
		print"<td class='tbl-l' style='border-left:1px solid #999999;' >$req_area_covered</td>\n";
		print"<td class='tbl-l' style='border-left:1px solid #999999;' >";
		foreach($rows_functions as $key => $value) {

			print"$value; ";
		}
		print"</td>\n";
		print"<td  class='tbl-l' style='border-left:1px solid #999999;' >$req_locked_by</td>\n";
		print"<td  class='tbl-l' style='border-left:1px solid #999999;' >$req_locked_date</td>\n";
                $states=requirement_get_statuses();
		$total_elements=0;
                foreach ($states as $state) {
                  if ($state!='Rejected') $total_elements+=$percent[$state]+$percent['UC '.$state];
                }
                foreach ($states as $state) if ($state!='Rejected') {
                   echo "<td class='tbl-c' style='border-left:1px solid #999999;'>";
                   if ($percent[$state]==0 && $percent['UC '.$state]==0) {} else {
//                      if ($percent[$state]!=0)
                        printf("<a class=\"percent_reqs\" href=\"requirement_detail_page.php?req_id=$req_id&amp;req_version_id=$req_version_id&amp;tab=1\">%.0f",(floor($percent[$state]*100)/$total_elements));
                      if (/*$percent[$state]!=0 && */ $percent['UC '.$state]!=0) echo "</a>+"; else echo "%</a>";
                      if ($percent['UC '.$state]!=0) printf("<a class=\"percent_uc\" href=\"requirement_detail_page.php?req_id=$req_id&amp;req_version_id=$req_version_id&amp;tab=2\">%.0f%s</a>",(floor($percent['UC '.$state]*100)/$total_elements),"%");
                   }
                   echo "</td>\n";
                } else {
                   if ($percent[$state]>0) echo "<td  class='tbl-c' style='border-left:1px solid #999999;'>Yes</td>\n"; else echo "<td  class='tbl-c' style='border-left:1px solid #999999;'></td>";
                }

		print"</tr>\n";
		              }
//                if ($req_version_status!='Rejected')
		if (isset($row_requirement['childs'])) {
                    if ($filter==0 || $row_requirement[REQ_ID]==$filter) requirementtree_print($row_requirement['childs'],$depth+1,0);
                      else requirementtree_print($row_requirement['childs'],$depth,$filter);
                }  else {
                }
	}
}
################################################################################
# Testset table

if($req_tree) {


        if ($filter_req_id!=0) {
          $parent_req=requirement_get_detail($project_id,$filter_req_id);
	  $parent_way=array();
          if (count($parent_req)>0) $parent_way=requirement_includeway($parent_req[0]);
              $parent_way=array_reverse($parent_way);
              $first=true;
              foreach ($parent_way as $item) {
                if (!$first) {
                  echo " &#8226; ";
                }
                $first=false;
                echo "<a href='requirement_page.php?filter_req=".$item[REQ_ID]."'>".$item[REQ_FILENAME]."</a>";
              }
//              echo ""; print_r($parent_way); echo "";
             echo "<br/>";
             echo "<br/>";
          }

	print"<div align=center>\n";



	print"<table class=width100 >\n";



	# Table headers
	print"<tr class=tbl_header>\n";
	html_tbl_print_header( '');
	html_tbl_print_header( lang_get('req_id'), REQ_ID, $order_by, $order_dir);
	html_tbl_print_header( lang_get('req_name'), REQ_VERS_DETAIL, $order_by, $order_dir );
	html_tbl_print_header( 'Type', REQ_DOC_TYPE_NAME, $order_by, $order_dir,null,null,true); // lang_get('req_type')
	html_tbl_print_header( lang_get('version'),	REQ_VERS_VERSION, $order_by, $order_dir );
	html_tbl_print_header( lang_get('status'), REQ_VERS_STATUS, $order_by, $order_dir );
	html_tbl_print_header( lang_get('req_area'), REQ_AREA_COVERAGE, $order_by, $order_dir );
	html_tbl_print_header( lang_get('functionality') );
	html_tbl_print_header( lang_get('req_locked_by'), REQ_LOCKED_BY, $order_by, $order_dir );
	html_tbl_print_header( lang_get('req_locked_date'),	REQ_LOCKED_DATE, $order_by, $order_dir );
        $states=requirement_get_statuses();
        $first=true;
        foreach ($states as $state) {
                if ($first) html_tbl_print_header($state.' (Req+UC)',null,null,null,null,null,true); else
        	html_tbl_print_header(substr($state,0,5).".",null,null,null,null,null,true);
        	$first=false;
        }


	print"</tr>\n";
        requirementtree_print($req_tree,0,$filter_req_id);



	print"</table>\n";

	print"</div>\n";

	//print lang_get("update").": &nbsp;\n";
	if( session_use_javascript() ) {
		print"<input id=select_all type=checkbox name=thispage onClick='checkAll( this )'>\n";
		print"<label for=select_all>".lang_get("select_all")."</label>";
		print"&nbsp;\n";
	}
	print"<select name=action>\n";
		print"<option value=status>".lang_get("status")."</option>\n";
		print"<option value=assigned_release>".lang_get("req_assign_release")."</option>\n";
	print"</select>\n";

	print"<input type=submit name=mass_req_update value='".lang_get("update")."'>";

} else {


	html_no_records_found_message( lang_get("no_requirements") );
}

print"</form>\n";

html_print_footer();
?>