<?php
    include_once("helper.php");
    include_once("CHeader.php");
    include_once("CSolution.php");
    include_once("CProjectInfo.php");
    include_once("CProjectSolutions.php");

    class UDStandard{
        
        public $header;
        
        // function __construct(){
        //     $headers = array();
        // }

        // function populateFromDBRow( $row ){
            
        //     $this->ref = $row["Ref"];
        //     $this->h1 = $row["H1"];
        //     $this->h1_title = $row["H1_Title"];
        //     $this->h2 = $row["H2"];
        //     $this->h2_title = $row["H2_Title"];
        //     $this->h3 = $row["H3"];
        //     $this->h3_title = $row["H3_Title"];
        //     $this->h4 = $row["H4"];
        //     $this->h4_title = $row["H4_Title"];
        //     $this->standard_no = $row["Standard_No"];
		// 	$this->standard_text = $row["Standard_Text"];
		// 	$this->item_no = $row["Item_No"];
		// 	$this->points = $row["Points"];
		// 	$this->critical = $row["Critical"];
            
        //     // Goals
		// 	$this->goal_awareness = $row["Goal_Awareness"];
		// 	$this->goal_body_fit = $row["Goal_Body_Fit"];
		// 	$this->goal_comfort = $row["Goal_Comfort"];
		// 	$this->goal_cultural_appropriateness = $row["Goal_Cultural_Appropriateness"];
		// 	$this->goal_personalization = $row["Goal_Personalization"];
		// 	$this->goal_social_participation = $row["Goal_Social_Participation"];
		// 	$this->goal_understanding = $row["Goal_Understanding"];
		// 	$this->goal_wellness = $row["Goal_Wellness"];
            
        //     // Phases
        //     $this->phase_close = $row["Phase_Close"];
		// 	$this->phase_construct = $row["Phase_Construct"];
		// 	$this->phase_design = $row["Phase_Design"];
		// 	$this->phase_initiate = $row["Phase_Initiate"];
		// 	$this->phase_operations = $row["Phase_Operations"];
        //     $this->phase_plan = $row["Phase_Plan"];


            
            
        // }
        
    }
	
	// Getting Standards	
	function API($H1_No){
        
		$sql_conn = mysqli_connection();
        if($H1_No != -1){

            //get all for Screen reader version
            if($H1_No === "sr"){
                $H1_No = "";
            }

            $where = "WHERE `Credit` like '".$H1_No."%'";  
            $sql = "SELECT  * FROM  UD_S_Headings ".$where." ORDER BY `H1#`, `H2#`, `H3#`";
            $udStandard = new UDStandard();
            $res = array();

            $result = mysqli_query($sql_conn, $sql);
            while($row = mysqli_fetch_array($result)) {
                $header = new UD_S_Header();
                $header->populateFromDBRow($row);

                if($header->header_level === "H1"){
                    $udStandard = new UDStandard();
                    $udStandard->header = $header;
                    $res[$header->h1] = $udStandard;
                } else if($header->header_level === "H2"){
                    $res[$header->h1]->header->h2_elems[$header->h2] = $header;
                } else if($header->header_level === "H3"){
                    $res[$header->h1]->header->h2_elems[$header->h2]->h3_elems[$header->h3] = $header;
                } 
            }

            $where = "WHERE `Standard#` like '".$H1_No."%'";  
            $sql = "SELECT  * FROM  UD_S_Solutions ".$where." ORDER BY `H1#`, `H2#`, `H3#`, `Item#`, `Standard#`";
            
            $result = mysqli_query($sql_conn, $sql);
            while($row = mysqli_fetch_array($result)) {
                $solution = new UD_S_Solution();
                $solution->populateFromDBRow($row);

                if(substr_count($solution->standard_no,".") === 1){
                    $res[$solution->h1]->header->solutions[$solution->item_no] = $solution;
                } else if(substr_count($solution->standard_no,".") === 2){
                    $res[$solution->h1]->header->h2_elems[$solution->h2]->solutions[$solution->item_no] = $solution;
                } else if(substr_count($solution->standard_no,".") === 3){
                    $res[$solution->h1]->header->h2_elems[$solution->h2]->h3_elems[$solution->h3]->solutions[$solution->item_no] = $solution;
                } 
            }

        } else {
            $where = "";  
            $sql = "SELECT  * FROM  UD_S_Headings ".$where." ORDER BY `H1#`, `H2#`, `H3#`";
            $udStandard = new UDStandard();
            $res = array();

            $result = mysqli_query($sql_conn, $sql);
            while($row = mysqli_fetch_array($result)) {
                $header = new UD_S_Header();
                $header->populateFromDBRow($row);

                if($header->header_level === "H1"){
                    $udStandard = new UDStandard();
                    $udStandard->header = $header;
                    $res[$header->h1] = $udStandard;
                } else if($header->header_level === "H2"){
                    $res[$header->h1]->header->h2_elems[$header->h2] = $header;
                } else if($header->header_level === "H3"){
                    $res[$header->h1]->header->h2_elems[$header->h2]->h3_elems[$header->h3] = $header;
                } 
            }
        }
        
        mysqli_close($sql_conn);
        $r = json_encode($res);
        return $r;
		
	}
    
    function getPhaseColumnNames(){
        $sql_conn = mysqli_connection();
        $sql = 'SELECT `phase_text` FROM UD_S_Phases ORDER BY sl_no';
        $result = mysqli_query($sql_conn,$sql);
        $res = array();
        while($row = mysqli_fetch_array($result)) {
            $res[] = $row["phase_text"];
        }
        
        mysqli_close($sql_conn);
        $r = json_encode($res);
        return $r;
    }
	
    
    function getGoalColumnNames(){
        $sql_conn = mysqli_connection();
        $sql = 'SELECT `goal_text` FROM UD_S_Goals ORDER BY sl_no';
        $result = mysqli_query($sql_conn,$sql);
        $res = array();
        while($row = mysqli_fetch_array($result)) {
            $res[] = $row["goal_text"];
        }
        
        mysqli_close($sql_conn);
        $r = json_encode($res);
        return $r;
    }

    function createDictionaryForProject()
    {
        $H1_No = 1;
        $sql_conn = mysqli_connection();
        // $where = "WHERE `Credit` like '".$H1_No."%'";
        $where = "";  
        $sql = "SELECT  * FROM  UD_S_Headings ".$where." ORDER BY `H1#`, `H2#`, `H3#`";
        $udStandard = new UDStandard();

        // create the object here
        $result = mysqli_query($sql_conn, $sql);
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $header = new UD_S_Header();
            $header->populateFromDBRow($row);
            // echo $row;
            // echo "<br><br>";
            if($header->header_level === "H1"){
                // echo "inside h1";
                $res[$header->h1] = $row;
            } else if($header->header_level === "H2"){
                // echo "inside h2";
                $res[$header->h1][$header->h2] = $row;
            } else if($header->header_level === "H3"){
                // echo "inside h3";
                $res[$header->h1][$header->h2][$header->h3] = $row;
            } 
        }
        // echo $res;
        // echo "Priniting UD_S_Headings data";
        // echo "<script>console.log($res)</script>";
        // echo json_encode($res);
        // $where = "WHERE `Standard#` like '".$H1_No."%'";

        $where = "";  
        $sql = "SELECT  * FROM  UD_S_Solutions ".$where." ORDER BY `H1#`, `H2#`, `H3#`, `Item#`, `Standard#`";
        
        $result = mysqli_query($sql_conn, $sql);
        while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
            $solution = new UD_S_Solution();
            $solution->populateFromDBRow($row);
            // echo $row;
            if(substr_count($solution->standard_no,".") === 1){
                // echo "inside h1 solutions";
                $res[$solution->h1]["solutions"] = $row;
            } else if(substr_count($solution->standard_no,".") === 2){
                 // echo "inside h2 solutions";
                 // $res[$solution->h1][$solution->h2]["solutions"][$solution->item_no] = $row;
                 $res[$solution->h1][$solution->h2][$solution->item_no] = $row;
            } else if(substr_count($solution->standard_no,".") === 3){
                // echo "inside h3 solutions";
                // $res[$solution->h1][$solution->h2][$solution->h3]["solutions"][$solution->item_no] = $row;
                $res[$solution->h1][$solution->h2][$solution->h3][$solution->item_no] = $row;
            } 
        }
        mysqli_close($sql_conn);
        // $r = json_encode($res);
        // echo $r;
        // echo "<script>console.log($r)</script>";
        return $res;
    }

    function displayRecursiveResults($arrayObject) 
    {
        foreach($arrayObject as $key=>$data) 
        {
            if(is_array($data))
            {
                displayRecursiveResults($data);
            } elseif(is_object($data))
            {
                displayRecursiveResults($data);
            } else 
            {
                // echo "".$key." : ".$data."<br />";
            }
        }
    }

    function createDictionaryForSpecificProject($project_id)
    {
        $project_info = getProjectInfo($project_id);
        // echo "<script>console.log($project_info)</script>";
        // echo "project id is ".$project_info[0]["project_id"];
        $project_info = json_decode($project_info,true);
        $project_info_arr = $project_info[0];

        $keys = array_keys($project_info_arr);
        // echo "key is : ".$keys[1];
        // echo "<br><br>";
        // echo "value is : ".$project_info_arr[$keys[1]];

        // echo "<br><br>";
        // echo "<script>console.log($project_info_arr)</script>";

        // displayRecursiveResults($project_info_arr);

        foreach($project_info_arr as $key=>$data) 
        {
            if(strpos($key, "s_") === 0) 
            {
                $project_dict = add_checked_values_to_dict($key, $data, $project_dict);
            }
            else if (strpos($key, "h1_credits_applicable") === 0)
            {
                $project_dict[$key] = $data;
                $project_dict = add_applicable_credits_to_dict($key, $data, $project_dict);
            }
            else if (strpos($key, "h1_credits_earned") === 0)
            {
                $project_dict[$key] = $data;
                $project_dict = add_credits_earned_to_dict($key, $data, $project_dict);
            }
            else if (strpos($key, "header_mask") === 0)
            {
                $project_dict[$key] = $data;
                $project_dict = add_header_mask_to_dict($key, $data, $project_dict);
                $project_dict["enabled_sections"] = add_header_mask_to_dict($key, $data, $temp);
            }
            else
            {
                $project_dict[$key] = $data;
            }
        }

        //here we need generic dictionary
        $general_project_dict = createDictionaryForProject();
        $temp = get_required_solutions_status($general_project_dict,$project_id,$project_dict);
        $project_dict["required_solutions"] = $temp;

         //here we need generic dictionary
        $temp_minimum_credit_check = minimum_credit_check($general_project_dict,$project_id,$project_dict);
        $project_dict["minimum_credit_check"] = $temp_minimum_credit_check;

        $project_dict = updateBonusSolutions($general_project_dict,$project_dict);

        $project_dict["total_enabled_sections"] = get_total_enabled_sections($project_dict["header_mask"]);
        $project_dict["review_status"] = get_review_checkbox_status($project_id, $project_dict);
        
        //$project_dict = json_encode($project_dict);
        //echo "<script>console.log($project_dict)</script>";
        //echo "Project_dict_inside function : ".$project_dict;
        return $project_dict;
    }

    function add_checked_values_to_dict($key, $value, $project_dict)
    {
         // split the key now
        $split_key = explode("_",$key);
        $length_of_key = count($split_key);
        // echo "".$key." : ".$value." ".$length_of_key."<br />";

        if($length_of_key === 4)
        {
            $h1 = $split_key[1];
            $h2 = $split_key[2];
            $h3 = $split_key[3];
            $project_dict[$h1][$h2][$h3]["checked"] = $value;
        }

        if ($length_of_key === 5)
        {
            $h1 = $split_key[1];
            $h2 = $split_key[2];
            $h3 = $split_key[3];
            $h4 = $split_key[4];
            $project_dict[$h1][$h2][$h3][$h4]["checked"] = $value;
        }

        return $project_dict;
    }

    function add_applicable_credits_to_dict($key, $value, $dict)
    {
        // split the applicable credits value now
        $split_credits = explode(",",$value);
        $length_of_credits = count($split_credits);

        // echo "Inside add_applicable_credits_to_dict()";
        // echo $length_of_credits;

        for ($i = 0; $i < $length_of_credits; $i++) 
        {
            // print $split_credits[$i];
            $dict[$i+1]["applicable_credits"] = $split_credits[$i];
        }

        return $dict;
    }
    
    function add_credits_earned_to_dict($key, $value, $dict)
    {
        // split the applicable credits value now
        $split_credits = explode(",",$value);
        $length_of_credits = count($split_credits);

        // echo "Inside add_credits_earned_to_dict()";
        // echo $length_of_credits;

        for ($i = 0; $i < $length_of_credits; $i++) 
        {
            // print $split_credits[$i];
            $dict[$i+1]["earned_credits"] = $split_credits[$i];
        }

        return $dict;
    }

    function add_header_mask_to_dict($key, $value, $dict)
    {
        // split on h1
        // $value = "1,1;1,1,1,1;1,1,1,1,1,1,1,1,1,1,1,1;1:0:0:0,1:0:1:1:0,1,1;1:0:1:0,1,1,1,1,1,1,1;1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1;1,1,1,1,1,1,1,1,1,1,1,1;1,1,1,1,1,1;1,1,1";
        $h1_mask = explode(";",$value);
        $h1_mask_length = count($h1_mask);

        // echo "<br> Inside HEADER MASK function <br>";
        // echo json_encode($value);
        // echo "<br><br>";

        for ($h1 = 0; $h1 < $h1_mask_length ; $h1++)
        {
            $h2_mask = explode(",",$h1_mask[$h1]);
            $h2_mask_length = count($h2_mask);
            
            // echo "<br>";
            // echo json_encode($h2_mask);

            for ($h2 = 0; $h2 < $h2_mask_length ; $h2++)
            {
                $h3_mask = explode(":",$h2_mask[$h2]);
                $h3_mask_length = count($h3_mask);
                // echo "<br>".($h1+1)." ".($h2+1)." ".$h3_mask[0];

                $dict[$h1+1][$h2+1]["enabled"] = $h3_mask[0];

                for ($h3 = 1; $h3 < $h3_mask_length ; $h3++)
                {
                    // echo "<br>".($h1+1)." ".($h2+1)." ".$h3." ".$h3_mask[$h3];
                    $dict[$h1+1][$h2+1][$h3]["enabled"] = $h3_mask[$h3];
                }
            }
        }

        return $dict;
    }

    function get_required_solutions_status ($project_dict,$project_id,$current_project_dict)
    {
        // $current_project_dict = createDictionaryForSpecificProject($project_id);
        ///////////
        //$project_dict = createDictionaryForProject();
        $is_all_required_solutions_checked = true;
        $is_all_enabled_required_solutions_checked = true;

        // echo "current project dict ".$current_project_dict."<br>";
        // echo "Project dict ".$project_dict."<br>";
        // echo "<script>console.log($current_project_dict)</script>";
        // echo "<script>console.log($project_dict)</script>";

        // iterate over the project_dict checking for the pre-requisite
        foreach ( $project_dict as $h1_key => $h1_value) 
        {            
            foreach ( $h1_value as $h2_key => $h2_value) 
            {
                if(is_iterable($h2_value)==false)
                {
                    continue;
                }
                foreach ( $h2_value as $h3_key => $h3_value) 
                {
                    if (is_numeric($h3_key))
                    {
                        // required as per pre-defined UD standards
                        $is_required = $project_dict[$h1_key][$h2_key][$h3_key]["Prerequisite"];
                        $is_required = $is_required == "Required" ? true :false;
                        // if the solution is  is checked by the user
                        $is_satisfied = $current_project_dict[$h1_key][$h2_key][$h3_key]["checked"];
                        $is_satisfied = $is_satisfied != 0 ? true :false;
                        // if the section which contains the required solution is enabled by the user. i.e appplicable to the user's project.
                        $is_enabled = $current_project_dict[$h1_key][$h2_key]["enabled"];
                        if ($is_required)
                        {
                            // echo " ".$h1_key." ".$h2_key." ".$h3_key. " : ".$is_required." - ".$is_satisfied;
                            // echo "<br>";
                            $required_solutions[$h1_key][$h2_key][$h3_key]["is_checked"] = $is_satisfied;
                            if ( !$is_satisfied )
                            {
                                $is_all_required_solutions_checked = false;
                            }
                            if ( $is_enabled && !$is_satisfied )
                            {
                                $is_all_enabled_required_solutions_checked = false;
                                // echo " ".$h1_key." ".$h2_key." ".$h3_key. " : ".$is_required." - ".$is_satisfied;
                                // echo "<br>";
                            }
                        }
                    }

                    if(is_iterable($h3_value)==false)
                    {
                        continue;
                    }
                    foreach ( $h3_value as $h4_key => $h4_value) 
                    {
                        if (is_numeric($h4_key))
                        {
                            $is_required = $project_dict[$h1_key][$h2_key][$h3_key][$h4_key]["Prerequisite"];
                            $is_required = $is_required == "Required" ? true :false;
                            $is_satisfied = $current_project_dict[$h1_key][$h2_key][$h3_key][$h4_key]["checked"];
                            $is_satisfied = $is_satisfied != 0 ? true :false;
                            $is_enabled = $current_project_dict[$h1_key][$h2_key][$h3_key]["enabled"] && $current_project_dict[$h1_key][$h2_key]["enabled"];
                            if ($is_required)
                            {
                                // echo " level_4 : ".$h1_key." ".$h2_key." ".$h3_key." ".$h4_key." : ".$is_required." - ".$is_satisfied;
                                // echo "<br>";
                                $required_solutions[$h1_key][$h2_key][$h3_key][$h4_key]["is_checked"] = $is_satisfied;
                                if ( !$is_satisfied )
                                {
                                    $is_all_required_solutions_checked = false;
                                }
                                if ( $is_enabled && !$is_satisfied )
                                {
                                    $is_all_enabled_required_solutions_checked = false;
                                    // echo " level_4 : ".$h1_key." ".$h2_key." ".$h3_key." ".$h4_key." : ".$is_required." - ".$is_satisfied;
                                    // echo "<br>";
                                }
                            }
                        }
                    }
                }
            }
        }
        $required_solutions["all_required_solutions_checked"] = $is_all_required_solutions_checked;
        $required_solutions["all_enabled_required_solutions_checked"] = $is_all_enabled_required_solutions_checked;
        // $required_solutions = json_encode($required_solutions);
        // echo "<script>console.log($required_solutions)</script>";
        return $required_solutions;     
    }

    // This function returns the true or false for each enabled section.
    // true : if section has sifficient solutions checked for atleast one credit
    // false : otherwise
    // example : 1.1 has 7 solutions and 2 credits
    // user should enable(tick the checkbox) for atleast 3 solutions to get the 1 credit
    // if user has only two solutions checked, we will show user warning on the UI and hence mark false here in this function
    function minimum_credit_check ($project_dict,$project_id,$current_project_dict)
    {
        //$project_dict = createDictionaryForProject();
        $overall_minimum_credit_check = true;
        // iterate over the project_dict checking for the pre-requisite
        foreach ( $current_project_dict as $h1_key => $h1_value) 
        {       
            if(is_iterable($h1_value)==false)
            {
                continue;
            }
            foreach ( $h1_value as $h2_key => $h2_value) 
            {
                if (is_numeric($h2_key))
                {
                    $enabled = $current_project_dict[$h1_key][$h2_key]["enabled"];
                    // echo "key: ".$h1_key." ".$h2_key." enabled: ".$enabled;
                    // echo"<br>";

                    if ($enabled)
                    {
                        $min_point_1 = $project_dict[$h1_key][$h2_key]["Min_Points_1"];
                        $min_point_2 = $project_dict[$h1_key][$h2_key]["Min_Points_2"];
                        $min_point_3 = $project_dict[$h1_key][$h2_key]["Min_Points_3"];
                        // $minimum_solutions is the minimum solutions required to be checked by user to have atleast one credit
                        $minimum_solutions = $min_point_1;
                        $minimum_solutions = $minimum_solutions == 0 ? $min_point_2 : $minimum_solutions;
                        $total_solutions_checked = 0;

                        foreach ( $h2_value as $h3_key => $h3_value) 
                        {
                            if (is_numeric($h3_key))
                            {
                                $total_solutions_checked =  $total_solutions_checked + $current_project_dict[$h1_key][$h2_key][$h3_key]["checked"];
                            }
                            
                            // apply same logic for H3 level headers
                            $enabled_h3 = false;
                            if(isset($current_project_dict[$h1_key][$h2_key][$h3_key]["enabled"]))
                            {
                                $enabled_h3 = $current_project_dict[$h1_key][$h2_key][$h3_key]["enabled"];
                            }
                            // echo "key: ".$h1_key." ".$h2_key." ".$h3_key." ENABLED: ".$enabled_h3;
                            // echo "<br>";
                            if ($enabled_h3 && is_numeric($h3_key))
                            {
                                $min_point_1_next = $project_dict[$h1_key][$h2_key][$h3_key]["Min_Points_1"];
                                $min_point_2_next = $project_dict[$h1_key][$h2_key][$h3_key]["Min_Points_2"];
                                $min_point_3_next = $project_dict[$h1_key][$h2_key][$h3_key]["Min_Points_3"];
                                // $minimum_solutions is the minimum solutions required to be checked by user to have atleast one credit
                                $minimum_solutions_next = $min_point_1_next;
                                $minimum_solutions_next = $minimum_solutions_next == 0 ? $min_point_2_next : $minimum_solutions_next;
                                $total_solutions_checked_next = 0;
                                foreach ( $h3_value as $h4_key => $h4_value) 
                                {
                                    if (is_numeric($h4_key))
                                    {
                                        $total_solutions_checked_next = $total_solutions_checked_next + $current_project_dict[$h1_key][$h2_key][$h3_key][$h4_key]["checked"];
                                    }
                                }
                                
                                $temp_check = $total_solutions_checked_next >= $minimum_solutions_next ? true : false;
                                $minimum_credit_check[$h1_key][$h2_key][$h3_key] =  $temp_check;
                                if (!$temp_check)
                                     $overall_minimum_credit_check = false;
                               
                                /*
                                echo "min_point_1_next ".$min_point_1_next;
                                echo "<br>";
                                echo "min_point_2_next ".$min_point_2_next;
                                echo "<br>";
                                echo "min_point_3_next ".$min_point_3_next;
                                echo "<br>";
                                
                                echo "key: ".$h1_key." ".$h2_key." ".$h3_key." ENABLED: ".$enabled_h3;
                                echo "<br>";
                                echo "Minimum required for atleast one credit is ".$minimum_solutions_next;
                                echo "<br>";
                                echo "Total solutions checked ".$total_solutions_checked_next;
                                echo "<br>";
                                
                                echo "MINIMUM SOLUTION CRITERIA SATISFIED ".$temp_check;
                                echo "<br>";
                                */
                                

                            }
                            
                        }
                        $temp_check = $total_solutions_checked >= $minimum_solutions ? true : false;
                        $minimum_credit_check[$h1_key][$h2_key] = $temp_check;
                        if (!$temp_check)
                            $overall_minimum_credit_check = false;

                        /*
                        echo "Min_Points_1 ".$min_point_1;
                        echo "<br>"; 
                        echo "Min_Points_2 ".$min_point_2;
                        echo "<br>";
                        echo "Min_Points_3 ".$min_point_3;
                        echo "<br>";
                       
                        echo "key: ".$h1_key." ".$h2_key." enabled: ".$enabled;
                        echo "<br>";
                        echo "Minimum required for atleast one credit is ".$minimum_solutions;
                        echo "<br>";
                        echo "Total solutions checked ".$total_solutions_checked;
                        echo "<br>";                        
                        echo "MINIMUM SOLUTION CRITERIA SATISFIED ".$temp_check;
                        echo "<br>";
                        echo "<br>";
                         */
                        
                    }

                }
            }
        }
        $minimum_credit_check["overall_minimum_credit_check"] = $overall_minimum_credit_check;
        // $minimum_credit_check = json_encode($minimum_credit_check);
        // echo "<script>console.log($minimum_credit_check)</script>";
        return $minimum_credit_check;     
    }

    function ToggleProjectChapter ($project_id,$chapter,$header,$enable)
    {
        $project_dict = createDictionaryForProject();
        $r = json_encode($project_dict);
        echo "<script>console.log($r)</script>";

        $current_project_dict = createDictionaryForSpecificProject($project_id);
        $r = json_encode($current_project_dict);
        echo "<script>console.log($r)</script>";

        // display data before updating
        // display_data($current_project_dict);

        $current_project_dict["h1_credits_applicable"] = get_h1_credits_applicable($current_project_dict["h1_credits_applicable"],$chapter,$project_dict,$enable);
        $current_project_dict["applicable_credits"] = get_h1_applicable_credits_total($current_project_dict["h1_credits_applicable"]);       
        $current_project_dict["h1_credits_earned"] = get_h1_credits_earned($current_project_dict["h1_credits_earned"],$chapter,$enable);
        $current_project_dict["earned_credits"] = get_h1_applicable_credits_total($current_project_dict["h1_credits_earned"]);       
        $current_project_dict["bonus_credits"] = get_bonus_credits($current_project_dict,$chapter,$enable);
        $current_project_dict["award_percentage"] = get_award_percentage($current_project_dict);
        $current_project_dict["header_mask"] = get_header_mask($current_project_dict["header_mask"],$chapter,$enable);

        if($enable != true)
        {
            // disable_solutions for chapter so update_solutions_for_chapter() method can 
            // write it to the database
            $current_project_dict = disable_solutions_for_chapter($current_project_dict,$chapter);
            $r = json_encode($current_project_dict);
            echo "<script>console.log($r)</script>";
        }
        
        // display data after updating
        // display_data($current_project_dict);

        update_solutions_for_chapter($current_project_dict,$chapter);
        update_global_dependent_settings($current_project_dict);
        
    }

    function disable_solutions_for_chapter($current_project_dict,$chapter)
    {
        foreach($current_project_dict[$chapter] as $header_key =>$header)
        {
            if(is_numeric($header_key))
            {
                $current_project_dict[$chapter][$header_key] = disable_solutions_for_chapter_header($current_project_dict[$chapter][$header_key]);
            }
        }
        return  $current_project_dict;
    }

    function disable_solutions_for_chapter_header($partial_dict)
    {
        $partial_dict["bonus_solutions"]=0;
        $partial_dict["checked_solutions"]=0;

        foreach($partial_dict as $solution_key=>$solution)
        {
            if(gettype($solution) === "array" && (gettype($solution["checked"]) !== "NULL"))
            {
                $partial_dict[$solution_key]["checked"] = 0;               
            }

            if(gettype($solution["1"]) === "array" && (gettype($solution["1"]["checked"]) !== "NULL"))
            {
                foreach($solution as $e3_key => $e3)
                {
                    if(gettype($e3) === "array" && (gettype($e3["checked"]) !== "NULL")){
                        $partial_dict[$solution_key][$e3_key]["checked"]=0;
                    }
                }
            }
        }
        return $partial_dict;        
    }

    function get_header_mask($old_header_mask,$chapter,$enable)
    {
        // $old_header_mask = $current_project_dict["header_mask"];
        //echo "<br><br> old Header Mask : ".$old_header_mask;
        if($enable == true)
        {
            $new_header_mask = update_header_mask_for_chapter($old_header_mask,$chapter,true);
        }
        else
        {
            $new_header_mask = update_header_mask_for_chapter($old_header_mask,$chapter,false);
        }              
        //echo "<br><br> New Header Mask : ".$new_header_mask;
        return $new_header_mask;
    }

    function get_award_percentage($current_project_dict)
    {
        // award percentage new in PHP
        $bonus_credits_new = (int)$current_project_dict["bonus_credits"]; 
        $earned_credits_new = (int)$current_project_dict["earned_credits"];
        $applicable_credits_new = (int)$current_project_dict["applicable_credits"];

        $bonus = $bonus_credits_new > 50 ? 10 : floor($bonus_credits_new/5);
        $new_percentage = round($earned_credits_new*100/$applicable_credits_new);
        $new_percentage =  $new_percentage + $bonus;
        //echo "<br>New award percentage (calculated in PHP): ".$new_percentage;
        return $new_percentage;
    }

    function get_bonus_credits($current_project_dict,$chapter,$enable)
    {
        if( $enable == true )
        {
            $bonus_solution_count_for_chapter = 0;
        }
        else
        {
            $bonus_solution_count_for_chapter = get_bonus_solutions_for_chapter($current_project_dict,$chapter);
        }

        // bonus percentage
        $bonus_credits = (int)$current_project_dict["bonus_credits"];
        //echo "<br>Current bonus credits : ".$bonus_credits;
        //echo "<br>bonus_solution_count_for_chapter :" .$bonus_solution_count_for_chapter;
        $bonus_credits_new = $bonus_credits - $bonus_solution_count_for_chapter;
        //echo "<br>New bonus credits : ".$bonus_credits_new;
        return $bonus_credits_new;
    }

    function display_data($current_project_dict)
    {
        $applicable_credits = (int)$current_project_dict["applicable_credits"];
        echo "<br>Current Applicable credits : ".$applicable_credits;

        $earned_credits = (int)$current_project_dict["earned_credits"];
        echo "<br>Current Earned credits : ".$earned_credits;
        
        $h1_credits_applicable = $current_project_dict["h1_credits_applicable"];
        echo "<br>h1_credits_applicable : ".$h1_credits_applicable;

        $h1_credits_earned = $current_project_dict["h1_credits_earned"];
        echo "<br>h1_credits_earned : ".$h1_credits_earned;

        $bonus_credits = (int)$current_project_dict["bonus_credits"];
        echo "<br>Current bonus credits : ".$bonus_credits;

        $award_percentage = (int)$current_project_dict["award_percentage"];
        echo "<br>Award percentage : ".$award_percentage;

        $header_mask = $current_project_dict["header_mask"];
        echo "<br>Header Mask : ".$header_mask;
    }

    function get_h1_applicable_credits_total($h1_applicable_credits)
    {
        $arr = explode(",",$h1_applicable_credits);
        foreach($arr as $key=>$val)
        {
            $sum = $sum + $val;
        }
        return $sum;
    }

    function get_h1_credits_applicable($old_h1_credits,$chapter,$project_dict,$enable)
    {
        // $old_h1_credits = $current_project_dict["h1_credits_applicable"];
        //echo "<br><br> old h1 credits string : ".$old_h1_credits;
        if ($enable==true)
        {
            $new_h1_credits = update_h1_credits($old_h1_credits,$chapter,(int)$project_dict[$chapter]["H1_Credits"]);
        }
        else
        {
            $new_h1_credits = update_h1_credits($old_h1_credits,$chapter,0);
        }
        //echo "<br> NEW h1 credits string : ".$new_h1_credits;
        return $new_h1_credits;
    }

    function get_h1_credits_earned($old_h1_credits,$chapter,$enable)
    {
        if($enable==true)
        {
            return $old_h1_credits;  
        }
        else
        {
            $new_h1_credits = update_h1_credits($old_h1_credits,$chapter,0);
            return $new_h1_credits;
        }                
    }

    function update_global_dependent_settings($current_project_dict)
    {
        $project_id = $current_project_dict["project_id"];
        $applicable_credits = (int)$current_project_dict["applicable_credits"];
        $earned_credits = (int)$current_project_dict["earned_credits"];
        $bonus_credits = (int)$current_project_dict["bonus_credits"];
        $award_percentage = (int)$current_project_dict["award_percentage"];
        $h1_credits_applicable = $current_project_dict["h1_credits_applicable"];
        $h1_credits_earned = $current_project_dict["h1_credits_earned"];
        $header_mask = $current_project_dict["header_mask"];

        $update_clause = " `applicable_credits` = {$applicable_credits}, `earned_credits` = {$earned_credits}, `bonus_credits` = {$bonus_credits}, `award_percentage` = {$award_percentage}, `header_mask` = '{$header_mask}', `h1_credits_applicable` = '{$h1_credits_applicable}', `h1_credits_earned` = '{$h1_credits_earned}'";
        // echo "<br><br> UPDATE clause : ".$update_clause;
        $update_query = "UPDATE `UD_P_Projects` SET ".$update_clause." WHERE `project_id` like '".$project_id."' AND `user_id` like '".$_SESSION['user']->_id."'";
        // echo "<br><br> QUERY ======> ".$update_query;
        update_db($update_query);
    }

    function update_solutions_for_chapter($current_project_dict, $chapter)
    {
        $project_id = $current_project_dict["project_id"];
        foreach($current_project_dict[$chapter] as $header_key =>$header)
        {
            update_solutions_for_chapter_header($header,$project_id,$chapter,$header_key);            
        }
    }

    // $data_dict is the dictionary for the chapter->header combination such as 5.1 or
    // even it works for the level 2 headers such as 5.7.1 or 5.7.2
    // it writes to the database all the values for the solutions either 1 or 0 (checked/unchecked) to dictionary
    // we have Chapter->header->solution hirachy e.g 1-1-1
    // chapter->header->sub_header->solution e.g. 5-7-1-2
    function update_solutions_for_chapter_header($data_dict,$project_id,$chapter,$header)
    {
        if(is_numeric($header))
        {
            // echo "<br><br> update clause for ".$chapter ." ".$header;
            $update_clause = get_update_clause($data_dict,$chapter,$header);
            $update_query = "UPDATE `UD_P_Projects` SET ".$update_clause." WHERE `project_id` like '".$project_id."' AND `user_id` like '".$_SESSION['user']->_id."'";
            //echo "<br> QUERY ====> ".$update_query;
            return update_db($update_query);
        }
    }

    function update_db($update_query)
    {
        $sql_conn = mysqli_connection();   
        if (!($u_stmt = $sql_conn->prepare($update_query))){
            $resp["message"] =  "Prepare failed: (" . $sql_conn->errno . ") " . $sql_conn->error;
            $resp["success"] = false;
            // echo "<br><br> Failure inside prepare : ".$sql_conn->error;
            return $resp;
        }
        
        if (!($ret = $u_stmt->execute())) {
            $resp["message"] =  "Execute failed: (" . $u_stmt->errno . ") " . $u_stmt->error;
            $resp["success"] = false;
            //echo "<br><br> Failure inside execute : ".$u_stmt->error;
            return $resp;
        } else {
            $resp["message"] = $update_query ;
            $resp["success"] = true;
            //echo "<br><br> SUCCESS";
        }

        $u_stmt->close();
    }

    function get_bonus_solutions_for_chapter($current_project_dict,$chapter)
    {
        $h1_value = $current_project_dict[$chapter];
        $bonus_solution_count_for_chapter =0;
        foreach ( $h1_value as $h2_key => $h2_value) 
        {
            if(is_numeric($h2_key))
            {
                $val = $current_project_dict[$chapter][$h2_key]["bonus_solutions"];
                // echo "<br>key: ".$chapter." ".$h2_key." Bonus Solutions: ".$val;
                $bonus_solution_count_for_chapter = $bonus_solution_count_for_chapter + $val;
                
                foreach ( $h2_value as $h3_key => $h3_value)
                {
                    if(is_numeric($h3_key))
                    {
                        $val_next = $current_project_dict[$chapter][$h2_key][$h3_key]["bonus_solutions"];
                        $bonus_solution_count_for_chapter = $bonus_solution_count_for_chapter + $val_next;
                        // echo "<br>";
                        //echo "key: ".$chapter." ".$h2_key." ".$h3_key." Bonus Solutions: ".$val_next; 
                    }
                }
            }
        }
        return $bonus_solution_count_for_chapter;
    }

    // this function is used to updat h1 credits for APPLICABLE as well as EARNED
    // example of input params
    // $old = 4,7,15,7,15,30,12,6,4
    // $chapter = 5
    // $value = 99
    // $output = 4,7,15,7,99,30,12,6,4
    function update_h1_credits($old,$chapter,$value)
    {
        $arr = explode(",",$old);
        $arr[$chapter-1]=$value;
        $new_str= implode(",",$arr);
        return $new_str;
    }

    function update_header_mask_for_chapter($old,$chapter,$value)
    {
        $arr_chap = explode(";",$old);
        if($value==true)
        {
            $arr_chap[$chapter-1] = str_replace('0','1',$arr_chap[$chapter-1]);
        }
        else
        {
            $arr_chap[$chapter-1] = str_replace('1','0',$arr_chap[$chapter-1]);
        }
        
        $header_mask = implode(";",$arr_chap);
        return $header_mask;        
    }
    
   
    function updateBonusSolutions($project_dict,$current_project_dict)
    {
        foreach ( $current_project_dict as $h1_key => $h1_value) 
        {   
            if(is_iterable($h1_value)==false)     
            {
                continue;
            }
            foreach ( $h1_value as $h2_key => $h2_value) 
            {
                if (is_numeric($h2_key))
                {
                    $total_solutions_checked = 0;
                    $total_solutions = 0;

                    foreach ( $h2_value as $h3_key => $h3_value) 
                    {
                        if (is_numeric($h3_key))
                        {
                            $total_solutions_checked =  $total_solutions_checked + $current_project_dict[$h1_key][$h2_key][$h3_key]["checked"];
                            $total_solutions = $total_solutions+1;
                        }
                        
                        $enabled_h3 = false;
                        if(isset($current_project_dict[$h1_key][$h2_key][$h3_key]["enabled"]))
                        {
                            $enabled_h3 = $current_project_dict[$h1_key][$h2_key][$h3_key]["enabled"];
                        }                                                
                        if ($enabled_h3 && is_numeric($h3_key))
                        {
                            $total_solutions_checked_next = 0;
                            $total_solutions_next =0;
                            foreach ( $h3_value as $h4_key => $h4_value) 
                            {
                                if (is_numeric($h4_key))
                                {
                                    $total_solutions_checked_next = $total_solutions_checked_next + $current_project_dict[$h1_key][$h2_key][$h3_key][$h4_key]["checked"];
                                    $total_solutions_next = $total_solutions_next+1;
                                }
                            }
                            $current_project_dict[$h1_key][$h2_key][$h3_key]["checked_solutions"] = $total_solutions_checked_next;
                            $current_project_dict[$h1_key][$h2_key][$h3_key]["total_solutions"] = $total_solutions_next;
                            //echo "<br>".$h1_key." ".$h2_key." ".$h3_key;
                            $current_project_dict[$h1_key][$h2_key][$h3_key]["bonus_solutions"] = get_bonus_solutions_credits_second($project_dict[$h1_key][$h2_key][$h3_key],$current_project_dict[$h1_key][$h2_key][$h3_key]);
                        }
                        
                    }
                    $current_project_dict[$h1_key][$h2_key]["checked_solutions"] = $total_solutions_checked;
                    $current_project_dict[$h1_key][$h2_key]["total_solutions"] = $total_solutions;
                    //echo "<br>".$h1_key." ".$h2_key;
                    $current_project_dict[$h1_key][$h2_key]["bonus_solutions"] = get_bonus_solutions_credits_second($project_dict[$h1_key][$h2_key],$current_project_dict[$h1_key][$h2_key]);
                }
            }
        }        
        return $current_project_dict;
    }

    function get_bonus_solutions_credits_second($project_dict,$current_project_dict)
    {
        $threshold = array();
        $instruction = $project_dict["Instruction"];
        //echo "<br> Instruction is : ".$instruction;
        $threshold = get_threshold_from_instruction($instruction);
        //echo "<br> Threshold is : ".count($threshold);
        $checked_solutions =  $current_project_dict["checked_solutions"];
        $bonus_solutions = $checked_solutions;
        foreach ($threshold as $index => $threshold_interval) 
        {
            //echo "<br> threshold interval : ".$threshold_interval;
            //echo "<br> checked solutions : ".$checked_solutions;
            if($checked_solutions >= (int)$threshold_interval )
            {
                $bonus_solutions = $checked_solutions - (int)$threshold_interval;
                //echo "<br> Bonus Solution count".$chapter." ".$header." ".$bonus_solutions;
                return $bonus_solutions;
            }
        }
        //echo "<br> Bonus Solution count - f- ".$chapter." ".$header." ".$bonus_solutions;
        return $bonus_solutions;        
    }

    // instruction is of the form "1:credit implement 3 of 5|1:credit implement 4 of 5" in the database
    function get_threshold_from_instruction($instruction)
    {
        $pos=0;
        $credit_intervals = array();
        if (strlen($instruction)<1)
        {
            return $credit_intervals;
        }
        $count = 0;
        while($pos = strpos($instruction,"of",$pos+1))
        {
            $credit_intervals[$count]=(int)$instruction[$pos-2];
            $count++;
        }
        // sort from high to low 
        rsort($credit_intervals);
        return $credit_intervals;
    }

    function test_get_threshold_from_instruction($instruction)
    {
        $pos=0;
        $credit_intervals = array();
        $count = 0;
        while($pos = strpos($instruction,"of",$pos+1))
        {
            $solution_count = (int)$instruction[$pos-2];
            $credit_count = (int)$instruction[$pos-23];
            $credit_intervals[$solution_count]=$credit_count;
            $count++;
        }
        // sort from high to low 
        rsort($credit_intervals);
        //$r = json_encode($credit_intervals);
        //echo "<script>console.log($r)</script>";
        return $credit_intervals;
    }

    function get_update_clause($data,$h1,$h2,$h3=-1)
    {
        $prefix = "`s_".$h1."_".$h2;
        $val = $data["enabled"] === "1" ? 1:0;
        if (intval($h3,10) > 0)
        {
             $prefix = "`s_".$h1."_".$h2."_".$h3;
        }
        else
        {
            $h3 = "-1";
            $prefix = "`s_".$h1."_".$h2;
        }        
        
        foreach($data as $e2_key => $e2){
            if(gettype($e2) === "array" && (gettype($e2["checked"]) !== "NULL")){
                $update_clause .= $prefix."_".$e2_key."` = ".$e2["checked"].",";                        
            }

            if(gettype($e2["1"]) === "array" && (gettype($e2["1"]["checked"]) !== "NULL")){
                foreach($e2 as $e3_key => $e3){
                    if(gettype($e3) === "array" && (gettype($e3["checked"]) !== "NULL")){
                        $update_clause .= $prefix."_".$e2_key."_".$e3_key."` = ".$e3["checked"].",";
                    }
                }
            }
        }
        
        $update_clause = rtrim($update_clause, ',');
        //echo "<br><br>".$update_clause;
        return $update_clause;
        //$update_clause .= " `applicable_credits` = {$applicable_credits}, `earned_credits` = {$earned_credits}, `bonus_credits` = {$bonus_credits}, `innovative_credits` = {$innovative_credits}, `innovative_credits_submitted_count` = {$innovative_credits_submitted_count}, `award_percentage` = {$award_percentage}, `award_category` = '{$award_category}', `header_mask` = '{$header_mask_test}', `h1_credits_applicable` = '{$h1_credits_applicable}', `h1_credits_earned` = '{$h1_credits_earned}'";
        //$update_query = "UPDATE `UD_P_Projects` SET ".$update_clause." WHERE `project_id` like '".$id."' AND `user_id` like '".$_SESSION['user']->_id."'";
        
    }
    function get_total_enabled_sections($str)
    {
        $total = 0;
        $chapters = explode(";",$str);
        foreach($chapters as $key_headers=>$headers)
        {
            $chapter_sum = 0;
            $pos = strpos($headers, ":");
            $h_arr = explode(",",$headers);
            if($pos === false)
            {
                
                $chapter_sum = array_sum($h_arr);
            }
            else
            {
                foreach($h_arr as $header_key=>$header)
                {
                    $temp_arr = explode(":",$header);
                    
                    if(count($temp_arr)=== 1)
                    {
                        $chapter_sum = $chapter_sum + array_sum($temp_arr);
                    }
                    else
                    {
                        $temp_sum = array_sum($temp_arr)-1;
                        $temp_sum=  max(0,$temp_sum);
                        $chapter_sum =  $chapter_sum + $temp_sum;
                        
                    }            
                }
            }        
            $total = $total +$chapter_sum;
        }
        return $total;
    }
    
    // is_project_reached_threshold();
    //createDictionaryForSpecificProject("pr_0956aa1511");
    //createDictionaryForProject();
    // ToggleProjectChapter("pr_0956aa1511","5","1",true);
    // test_get_threshold_from_instruction("2 credits: implement 5 of 7|1 credits: implement 3 of 7");
    // is_project_reached_threshold("pr_019c934964");
    
?>