<?php 
include("../db.php");

header('Content-Type: application/json');

    $class = $_POST['class'];
    $uid = $_POST['uid'];
    
    $status = 0;

    $objectiveArray = array();
    $subjectiveArray = array();
    $ncertArray = array();

    $array = array();
    
    $result_view_mode = $db->getVal("select result_view_mode from tbl_info");

    $objectivepapers = $db->getRows("select * from assignment_paper where class='$class' and paper_type=1");
    if(count($objectivepapers) > 0){

        foreach($objectivepapers as $objective){
            $flag = 0;
            $allquestions = $db->getRows("select * from assignment_questions where paper_id='$objective[id]' ");
            
            $checkattempt = $db->getRow("select * from assignment_attempt_paper where pid='".$objective[id]."' and uid='".$uid."' ");
            if(count($checkattempt)>1){
                $flag = 1;
            }

            $tq = count($allquestions);
            $marks = $objective['per_que_marks']*$tq;
            $time = $objective['duration'];
            $level = $objective['level'];
            $description = $objective['paper_description'];
            
            $subject = $db->getVal("select subject from subject_new where id='$objective[parent_subject]' and type='subject' ");
            $sub_subject = $db->getVal("select subject from subject_new where id='$objective[sub_subject]' and type='sub_subject' ");
            $chapter = $db->getVal("select subject from subject_new where id='$objective[chapter]' and type='chapter' ");
 
            array_push($objectiveArray, ["id"=>"$objective[id]", "totalque"=>"$tq", "per_que_marks"=>"$objective[per_que_marks]", "marks"=>"$marks", "time"=>"$time", "level"=>"$level", "description"=>"$description", "attempted"=>$flag, "subject"=>"$subject", "sub_subject"=>"$sub_subject", "chapter"=>"$chapter", "result_view"=>$result_view_mode]);
        }
    }
    
    $subjectivepapers = $db->getRows("select * from assignment_paper where class='$class' and paper_type=2 ");
    if(count($subjectivepapers) > 0){

        foreach($subjectivepapers as $subjective){
        $subpaperArray = array(); 
            $allquestions = $db->getRows("select * from assignment_questions where paper_id='$subjective[id]' ");

            $tq = count($allquestions);
            $marks = $subjective['per_que_marks']*$tq;
            $time = $subjective['duration'];
            $level = $subjective['level'];
            $description = $subjective['paper_description'];
            
            if(count($allquestions) > 0){
                $status = 1;

            	foreach($allquestions as $question){
            	    $options = json_decode($question[options], true);
            	    $m_options = json_decode($question[m_options], true);
            	    
                    $allimages = $db->getRows("SELECT * from assignment_question_files where question_id='$question[id]' ");
                    $imageArray = array();
                    $optionimage = array();

                    foreach($allimages as $image){
                        if($image[image_type]=="question_image"){
                            array_push($imageArray, ["image"=>"https://$_SERVER[HTTP_HOST]/uploads/questionimages/$image[name]"]);
                        }
                        else {
                            array_push($optionimage, ["image"=>"https://$_SERVER[HTTP_HOST]/uploads/questionimages/$image[name]", "optno"=>"$image[option_no]"]);
                        }
                    }

                  array_push($subpaperArray,["id"=>"$question[id]","question"=>"$question[question]","q_image"=>$imageArray,"options"=>$options, "opt_image"=>$optionimage, "m_options"=>$m_options, "answer"=>"$question[answer]", "hint"=>"$question[hint]", "solution"=>"$question[solution]", "qtype"=>$question[qtype], "quemark"=>$question[quemark] ]);
            	}

            }

            $subject = $db->getVal("select subject from subject_new where id='$subjective[parent_subject]' and type='subject' ");
            $sub_subject = $db->getVal("select subject from subject_new where id='$subjective[sub_subject]' and type='sub_subject' ");
            $chapter = $db->getVal("select subject from subject_new where id='$subjective[chapter]' and type='chapter' ");

            array_push($subjectiveArray, ["totalque"=>"$tq", "per_que_marks"=>"$subjective[per_que_marks]", "marks"=>"$marks", "time"=>"$time", "level"=>"$level", "description"=>"$description", "all_questions"=>$subpaperArray, "subject"=>"$subject", "sub_subject"=>"$sub_subject", "chapter"=>"$chapter" ]);
        }
    }

    $ncertpapers = $db->getRows("select * from assignment_paper where class='$class' and paper_type=3");
    if(count($ncertpapers) > 0){

        foreach($ncertpapers as $ncert){
            $ncertpaperArray = array();
            $allquestions = $db->getRows("select * from assignment_questions where paper_id='$ncert[id]' ");

            $tq = count($allquestions);
            $marks = $ncert['per_que_marks']*$tq;
            $time = $ncert['duration'];
            $level = $ncert['level'];
            $description = $ncert['paper_description'];

            if(count($allquestions) > 0){
                $status = 1;

            	foreach($allquestions as $question){
            	    $options = json_decode($question[options], true);
            	    $m_options = json_decode($question[m_options], true);
            	    
                    $allimages = $db->getRows("SELECT * from assignment_question_files where question_id='$question[id]' ");
                    $imageArray = array();
                    $optionimage = array();

                    foreach($allimages as $image){
                        if($image[image_type]=="question_image"){
                            array_push($imageArray, ["image"=>"http://$_SERVER[HTTP_HOST]/uploads/questionimages/$image[name]"]);
                        }
                        else {
                            array_push($optionimage, ["image"=>"http://$_SERVER[HTTP_HOST]/uploads/questionimages/$image[name]", "optno"=>"$image[option_no]"]);
                        }
                    }

                  array_push($ncertpaperArray,["id"=>"$question[id]","question"=>"$question[question]","q_image"=>$imageArray,"options"=>$options, "opt_image"=>$optionimage, "m_options"=>$m_options, "answer"=>"$question[answer]", "hint"=>"$question[hint]", "solution"=>"$question[solution]", "qtype"=>$question[qtype], "quemark"=>$question[quemark] ]);
            	}

            }

            $subject = $db->getVal("select subject from subject_new where id='$ncert[parent_subject]' and type='subject' ");
            $sub_subject = $db->getVal("select subject from subject_new where id='$ncert[sub_subject]' and type='sub_subject' ");
            $chapter = $db->getVal("select subject from subject_new where id='$ncert[chapter]' and type='chapter' ");

            array_push($ncertArray, ["totalque"=>"$tq", "per_que_marks"=>"$ncert[per_que_marks]", "marks"=>"$marks", "time"=>"$time", "level"=>"$level", "description"=>"$description", "all_questions"=>$ncertpaperArray, "subject"=>"$subject", "sub_subject"=>"$sub_subject", "chapter"=>"$chapter" ]);
        } 
    } 
    
    $monthsList1 = array(
        1   =>  'April',
        2   =>  'May',
        3   =>  'June',
        4   =>  'July ',
        5   =>  'August',
        6   =>  'September',
        7   =>  'October',
        8   =>  'November',
        9   =>  'December',
    	10  =>  'January',
        11  =>  'February',
        12  =>  'March'
    );

    $fStudent = $db->getRow("select * from student where idno='$uid' and  school_id='1' and status=1 and issue_TC=0"); 
    
    $session = $fStudent['session'];
    
    $tblinfo = $db->getRow("select due_month, resultview from tbl_info");    
        $duemonth = $tblinfo['due_month'];
        
		$overAllTotal=0;$overAlltution=0;$overAllTransport=0;$overAllhotel=0;$overAllOther=0;$overAllOther_hostel=0;$overAllFine=0;$overAllextra=array();					
		$overAllNewextra=0;

		$aryFeeType=$db->getRows("select distinct(type) from extrafee_type where school_id='1' and session='$session' and status=1 order by type");
		
		$m=0;
		if($duemonth!=0){
			  if($duemonth<4){
				$m=($duemonth+9);
			  }
			  else{
				$m=$duemonth-3;
			  }
		}
		else{
			$m=12;
		}
		
		
		            	$i=0;$total_comp=0;
            	if(count($fStudent) > 1){
        			for($j=1; $j<=$m; $j++){
						$md[]=$j;
					}
					 $mdf= implode(',',$md);

    				    $i++;
    					$mn=$m;

						$tution=0;$trasnport=0;$hostel=0;$otherExtra=0;$total=0;$fine=0;$total_full=0;
						$j=0;$other=0;$k=0;$total_extra=0;$count=0;
							$m1=$m+1;			
							foreach($monthsList1 as $key=>$val){$count++;

							if($mn===0){}
							else{ $mn--;
						$installTution=$db->getRow("select i".$key.",ip".$key." from installment where idno='".$fStudent["idno"]."'");
						if(is_array($installTution) && count($installTution)>0){
							if($installTution["ip$key"]=="" || $installTution["ip$key"]=="0")
							{
								$tution=$installTution["i$key"];
							}
							else
							{
                				if($m==$key)
                				{
                				$tution=$db->getVal("select (i".$m."-COALESCE(ip".$m.",0)) from installment where  idno='".$fStudent["idno"]."' ");
                				}
                                else
                                   {
                	             $tution=0;	
                                 }
							}
						}else{
							$tution="";
						}

						$overAlltution=$tution;

						$installTution=$db->getRow("select b".$key.",bp".$key." from installment where idno='".$fStudent["idno"]."'");
						
						if(is_array($installTution) && count($installTution)>0){
							if($installTution["bp$key"]=="" || $installTution["bp$key"]==0)
							{
								$trasnport=$installTution["b$key"];
							}
							else
							{
								
					 $tut_last_val=$db->getVal("select bp".$key1." from installment where  idno='".$fStudent["idno"]."'");

				if($m==$key)
				{
				$trasnport=$db->getVal("select (b".$m."-COALESCE(bp".$m.",0)) from installment where  idno='".$fStudent["idno"]."' ");
				}
                else
                   {
	             $trasnport=0;
                     }
							}
						}else{
							$trasnport="";
						}
						$overAllTransport=$trasnport;
						$installTution=$db->getRow("select i".$key.",ip".$key." from hostelinstallment where idno='".$fStudent["idno"]."'");
						if(is_array($installTution) && count($installTution)>0){
							if($installTution["ip$key"]=="" || $installTution["ip$key"]==0)
							{
								$hostel=$installTution["i$key"];
							}
							else
							{
							if($m==$key)
				{
				$hostel=$db->getVal("select (i".$m."-COALESCE(ip".$m.",0)) from hostelinstallment where  idno='".$fStudent["idno"]."' ");
				}
                else
                   {
	             $hostel=0;	
                     }	

							}								
						}else{
							$hostel="";
						}
						$overAllhotel=$hostel;
						$extrasum=array();
						if(is_array($aryFeeType) && count($aryFeeType)>0){
							foreach($aryFeeType as $ftype){  
								$sums=0;
								$Ftypeid=$db->getVal("select id from extrafee_type where type='".$ftype["type"]."' and class='".$fStudent["class"]."'");
        						$installTution=$db->getRow("select fee,pay from extrafee where type='".$Ftypeid."' and pid= 'p".$key."' and idno='".$fStudent["idno"]."'");
								$no=array();
								if(is_array($installTution) && count($installTution)>0){
									if($installTution["pay"]=="" || $installTution["pay"]==0)
									{
										$sums=$installTution["fee"];
									}
									else
									{
										if($m==$key)
                    				{
									$ext_last=$db->getVal("select sum(pay) from extrafee where idno='".$fStudent["idno"]."' and pid ='p".$key1."' ");
                                	if($ext_last==0)
									{	
									$sums=$db->getVal("select sum(fee-pay)  from extrafee where idno='".$fStudent["idno"]."' and pid ='p".$key."'  ");
									}
				}
                else
                   {
	             $sums=0;	
                     }
									}
									
								}else{
									$sums="";
								}
								$extrasum[]=$sums;
								$total_extra+=$sums;
								$tp=$ftype["type"];
								$overAllextra[$tp]+=$sums;
							}
						}

						 $overAllNewextra=0;
						for($ij=0; $ij<count($aryFeeType); $ij++){
						 $overAllNewextra+=$extrasum[$ij];
						}

						  $total=0;
						if($overAlltution=="0"&&$overAllTransport==0&&$overAllhotel==0&&$overAllNewextra==0)
						 {$total==0;}
						elseif($overAlltution==""&&$overAllTransport==""&&$overAllhotel==""&&$overAllNewextra=="")
						{$total="";}
						 else{ $total=$overAlltution+$overAllTransport+$overAllhotel+$overAllNewextra;}

		if($key=="12"){			
		$total23=$db->getVal("select (COALESCE(i12,0)+COALESCE(b12,0)-COALESCE(ip12,0)-COALESCE(bp12,0)) from installment where idno='".$fStudent["idno"]."'");
		
		$total24=$db->getVal("select (COALESCE(i12,0)-COALESCE(ip12,0)) from hostelinstallment where idno='".$fStudent["idno"]."'");
		
		$te=$db->getVal("SELECT sum(fee-pay) FROM extrafee WHERE idno='$uid' and pid='p12' and session='$session'  ");
		
		$total22=$total23+$total24+$te;
		$total_full+=$total22;
			}
			else{ 
			$total_full=$total_full+$total;
    			 }
            }
		}
					$install=$db->getRows("select * from otherfee_structure where class='".$fStudent["class"]."' and  school_id='1' and (otype =  '' or otype = 'old' or otype = 'new' ) and month <= '".$m."' and session='$session'");

						if(is_array($install) && count($install)>0){
							$k=0;$c=0;$other2=0;
							foreach($install as $ins){$k+=2;$c++;
							if($fStudent['stype']=="old" && $ins['otype']=="new"){
								$over="";
							}
						   elseif($fStudent['stype']=="new" && $ins['otype']=="old"){
								$over="";
							}
							else{
							$installTution=$db->getRow("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$ins['name']."'"); 
							$installTution1=$db->getRows("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$ins['name']."' and id !=".$installTution['id']."");	$installTution2=$db->getRow("select * from otherfee_discount where idno=".$fStudent['idno']." and other_id='".$ins['id']."' and class='".$fStudent["class"]."' and  school_id='1' and session='$session' ");
							$t=0;$other1=0;$other_left=0;$dis=0;
							$t=$ins['fee'];
					 if(is_array($installTution2) && count($installTution2)>0){
									 $dis=$installTution2['discount'];
											if($t==$dis)
												$t=0;
											else 
												$t=$t-$dis;
							 }
							if(is_array($installTution) && count($installTution)>0){
								if($installTution['fine']!=""){
								if(is_array($installTution1) && count($installTution1)>0)
									{	foreach ($installTution1 as $instt)
											$other_left+=$instt['fine'];
									}
									 $other=$installTution['fine'];
																		
									if($other_left!=0 && $other!=$ins['fee'] && $installTution['id']!=$installTution1['id'])
									{$other+=$other_left;}
								}
								else
									$other=0;	
							}else{
								$other="";
							}
							$other1=$other;
														
							$overAllOther=$t - $other1;
						    $over=$overAllOther;
							$other2+=$over;
							
						}
							}	
						}
					$total_full+=$other2;

					$install=$db->getRow("select * from otherfee_structure where otype ='".$fStudent['idno']."' and name like 'b%' and  school_id='1' and session='$session' ");

					$discount= $db->getVal("SELECT discount from otherfee_discount  WHERE  idno='$fStudent[idno]' and other_id='$install[id]'   and session='".$session."' ");
					
					$install2=$db->getRow("select id from otherfee_structure where otype ='".$fStudent['idno']."' and name like 'Latefine%' and  school_id='1' and session='".$session."'");
					
					$discount2= $db->getVal("SELECT COALESCE(sum(discount),0) from otherfee_discount  WHERE  idno='$fStudent[idno]' and other_id in(select id from otherfee_structure where otype ='".$fStudent['idno']."' and name like 'Latefine%' and  school_id='1' and session='$session')   and session='$session' ");

							$dues=0;
							if(is_array($install) && count($install)>0){
								$installTution=$db->getRows("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$install['name']."'"); 

								if(is_array($installTution) && count($installTution)>0){
									$total_dues=0;
									foreach($installTution as $ins){
										$total_dues+=$ins['fine'];
									}
									if($install['fee']==$total_dues)
										$dues=0;
									else $dues=$install['fee']-$total_dues-$discount;	

									$installTution_remain=$db->getVal("select sum(fine) from installment_fine where idno=".$fStudent['idno']." and reasion like 'remain%' ");
											$dues=$dues-$installTution_remain;
								}
							  else 		
									$dues=$install['fee']-$discount;
							}
							else
								$dues="";
							$alldues+=$dues;
							
							$total_full+=$dues;

					$install=$db->getRows("select * from hostel_otherfee_structure where class='".$fStudent["class"]."' and  school_id='1' and (otype =  '' or otype = 'old' or otype = 'new') and month <= '".$m."' and session='$session' ");

						if(is_array($install) && count($install)>0){
							$k=0;$b=0;$other2_hostel=0;
							foreach($install as $ins){$k+=2;$b++;
							if($fStudent['htype']=="old" && $ins['otype']=="new"){
								$over_hostel="";
							}
						   elseif($fStudent['htype']=="new" && $ins['otype']=="old"){
								$over_hostel="";
							}
							 elseif($fStudent['htype']==""){
								$over_hostel="";
							}
							else{
							$installTution=$db->getRow("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$ins['name']."'"); 
							$installTution1=$db->getRows("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$ins['name']."' and id !=".$installTution['id']."");	
							$installTution2=$db->getRow("select * from hostelotherfee_discount where idno=".$fStudent['idno']." and other_id='".$ins['id']."' and class='".$fStudent["class"]."' and  school_id='1' and session='$session' ");
							$t=0;$other1=0;$other_left=0;$dis=0;
							$t=$ins['fee'];
							 if(is_array($installTution2) && count($installTution2)>0){
									 $dis=$installTution2['discount'];
											if($t==$dis)
												$t=0;
											else 
												$t=$t-$dis;
							 }
							if(is_array($installTution) && count($installTution)>0){
								if($installTution['fine']!=""){
								if(is_array($installTution1) && count($installTution1)>0)
									{	foreach ($installTution1 as $instt) 
											$other_left+=$instt['fine'];
									}
									 $other=$installTution['fine'];
																		
									if($other_left!=0 && $other!=$ins['fee'] && $installTution['id']!=$installTution1['id'])
									{$other+=$other_left;}
								}
								else
									$other=0;	
							}else{
								$other="";
							}
							$other1=$other;
														
							$overAllOther_hostel=$t - $other1;
						    $over_hostel=$overAllOther_hostel;
							$other2_hostel+=$over_hostel;
							
						}
						}	
						}$total_full+=$other2_hostel; 
						$install=$db->getRows("select * from otherfee_structure where otype ='".$fStudent['idno']."' and name like 'Latefine%' and month <= '".$m."' and school_id='1' and session='$session' ");
							$dues=0;$total_dues=0;$fine_t=0;
							if(is_array($install) && count($install)>0){
								foreach($install as $ins){
									$fine_t+=$ins["fee"];
								$installTution=$db->getRows("select * from installment_fine where idno=".$fStudent['idno']." and reasion = '".$ins['name']."'");  
								      if(is_array($installTution) && count($installTution)>0){
											foreach($installTution as $ins){
												$total_dues+=$ins['fine'];
											}
									   }
									  else
										$dues=$ins['fee'];
								}
										if($fine_t==$total_dues)
												$dues=0;
								else $dues=$fine_t-$total_dues;	
										
						    }
							else
								$dues="";
							$alldues+=$dues;
							
							$total_full+=$dues-$discount2;
						
				 $install2=$db->getRow("SELECT otype,GROUP_CONCAT(id) as id FROM `otherfee_structure` where otype='".$fStudent['idno']."' and name like 'Latefine%'");

				$dis3= $db->getVal("SELECT sum(discount) from otherfee_discount  WHERE  idno='$fStudent[idno]' and other_id in($install2[id])   and session='$session' ");

				$to=$db->getVal("select sum(fee) from otherfee_structure where otype='".$fStudent['idno']."' and name!='Back_Dues' and name NOT like 'Latefine%' and month in ($mdf) and session='$session' ");

				$to1=$db->getVal("SELECT sum(amount) FROM reff_receipt WHERE idno='".$fStudent['idno']."' and session='$session' and type in (SELECT name FROM otherfee_structure WHERE otype='".$fStudent['idno']."' and name!='Back_Dues' and name NOT like 'Latefine%' and month in ($mdf))");

				$dis1=$db->getVal("SELECT sum(discount) FROM otherfee_discount WHERE idno='".$fStudent['idno']."' and session='$session' and other_id in (SELECT id FROM otherfee_structure WHERE otype='".$fStudent['idno']."' and name!='Back_Dues' and name NOT like 'Latefine%' and month in ($mdf))");

					 $t2=$to-$to1-$dis1;

					if($dues=="0")
					{
					 $finetotal=$dues;   
					}
					else
					{
					$finetotal=$dues-$dis3;    
					}
				 $total_comp+=$total_full+$t2;
        }
        
        $resultview = $tblinfo['resultview'];
        
        if($resultview == 1){
            $viewresult = 1;
        } 
        elseif($resultview == 2){
            if($total_comp > 0){
                $viewresult = 0;
            } else {
                $viewresult = 1;
            }
        }
        elseif($resultview == 3){
            if($total_comp > 0){
                if($fStudent['view_result'] == 1){
                    $viewresult = 1;
                } else {
                    $viewresult = 0;    
                }
            } else {
                $viewresult = 1;
            }
        }
        elseif($resultview == 4){
            if($fStudent['view_result'] == 1){
                $viewresult = 1;
            } else {
                $viewresult = 0;    
            }
        }
        else {
                $viewresult = 0;
        }
 
    $array['status'] = $status;

    $array['viewresult'] = $viewresult;
    $array['resultsetting'] = $resultview;

    $array['objective'] = $objectiveArray;
    $array['subjective'] = $subjectiveArray;
    $array['ncert'] = $ncertArray;
 
 echo json_encode($array);
?>