<?php
include("../../db.php");
//header("Access-Control-Allow-Origin: * ");


//error_reporting(E_ALL);
//ini_set('display_errors', 1);

header('Content-Type: application/json');
$class = $_REQUEST['class'];
$section = $_REQUEST['section'];
$term_app = $_REQUEST['term'];
$session = $_REQUEST['session'];

//$teacher_id = $_REQUEST['teacher_id'];

// $session = mysql_real_escape_string($session);

$tableinfo = $db->getRow("select * from tbl_info where id='1'");
$result_pattern = $tableinfo["result_pattern"];

$json = array("status" => 0, "msg" => "Unable to get data");
// $term_mark_array = "{}";
$subject_table_name = "";
$exam_mark_table_name = "";
$teacher_subject_table = "";
if ($result_pattern == '1') {
    $subject_table_name = "subject";
    $exam_mark_table_name = "exammarks";
    $teacher_subject_table = "teacher_subject";
} elseif ($result_pattern == '2') {
    $subject_table_name = "subject_mp";
    $exam_mark_table_name = "exammarks_mp";
    $teacher_subject_table = "teacher_subject_mp";
}

$conwhere = "";
$section_where = " and section='' ";

if (isset($_REQUEST['section']) && trim($_REQUEST['section']) != "") {

    $conwhere .= " and section='" . $_REQUEST['section'] . "' ";

    $section_where = " and section='" . $_REQUEST['section'] . "' ";
}



//$allsubject=$db->getRows("select subject from subject where class='$class' and session='$session'");
$sqlsec = $db->getRows("select idno, name,fincome,fname,admissionno,photo from student where session='$session' and class='$class' $conwhere and  status=1  and issue_TC=0 order by name");
// $result1 = mysql_query($sqlsec);
$jsons = array();
// while ($rowc = mysql_fetch_assoc($result1)) 
foreach ($sqlsec as $rowc) {

    $d = array();

    $photo = "";
    if ($rowc["photo"] != null) {
        $photo = "media/photo/" . $rowc["photo"];
    }

    $jsonc = array("idno" => "$rowc[idno]", "name" => "$rowc[name]", "rollno" => "$rowc[fincome]", "fname" => "$rowc[fname]", "admissionno" => "$rowc[admissionno]", "photo" => "$photo");

    $gradeD = $db->getRows("select * from " . $subject_table_name . " where class='$class' $section_where and school_id='1' and session='$session' order by id");
    //echo $ss="select * from subject where class='$class'  and school_id='1' and session='$session' order by id'";

    $subTotalObtained = 0;
    //$grandTotal = 0;
    $allTotal = 0;


    $fieldName = "";
    if ($term_app == "term1" || $term_app == "term2") {
        $fieldName = "term";
    } else {
        $fieldName = "name";
    }

    //  $exam_term_db = $db->getRows("select * from examterm where $fieldName = '$term_app' AND class = '$class' AND session = '$session'");
    $exam_term_db = $db->getRows("SELECT * FROM examname");


    // print_r($exam_term_db);

    foreach ($gradeD as $sub) {

        $chksubjectoptional = $db->getVal("select id from optional_subject where idno='$rowc[idno]' and subject='$sub[subject]' and session='$session' ");
        if($chksubjectoptional == 0){
            foreach ($exam_term_db as $itemX) {
                $term = $itemX["name"];
    
                $examTermMark = $db->getRow("SELECT subject,term_percent,total FROM examterm WHERE name = '$term' AND subject = '$sub[subject]' AND class = '$class' $section_where AND session = '$session'");
                $subjectMaxMark = 0;
                if ($examTermMark && $examTermMark != "" && count($examTermMark) > 0){
                    if ($examTermMark['term_percent'] != '' && $examTermMark['term_percent'] > 0){
                        $subjectMaxMark = $examTermMark['term_percent'];
                    }else{
                        $subjectMaxMark = $examTermMark['total'];
                    }
                }
    
                $examResultData = $db->getRow("select * from " . $exam_mark_table_name . " where school_id='1' and idno='" . $rowc["idno"] . "' and type='$term' and subject='" . $sub["subject"] . "'");
                //$examResultData = $db->getRow("select * from " . $exam_mark_table_name . " where school_id='1' and idno='" . $rowc["idno"] . "' and subject='" . $sub["subject"] . "'");
    
                //   print_r($exam_term_db);
                //   print_r($examResultData);
    
                if (count($examResultData) > 0) {
                    if (!empty($examResultData['subject'])) {
                        if($examTermMark['term_percent']==""){
                            array_push($d, array("name" => "$examResultData[subject]", "obtain" => "$examResultData[obtain]", "total" => $subjectMaxMark, "type" => "$examResultData[type]"));
                            if (is_numeric($examResultData["obtain"])) {
                                $subTotalObtained += $examResultData["obtain"];
                            }//max mark or total doesn't require numeric check coz db is int type check null only
                            if ($examResultData["total"] != null) {
                                //$grandTotal += $examResultData["total"];
                            }
                        } else {
                            $obtain = number_format($examResultData["obtain"]*$examTermMark['term_percent']/$examResultData["total"],1)+0;
                            array_push($d, array("name" => "$examResultData[subject] 123", "obtain" => round($obtain), "total" => $subjectMaxMark, "type" => "$examResultData[type]"));
                            // if (is_numeric($examResultData["obtain"])) {
                                $subTotalObtained += round($obtain);
                            // }
                        }
    
    
                        $allTotal += $subjectMaxMark; //$examResultData["total"];
                    }
                } else {
                    $subject_name = $sub["subject"];
                    //student record not found so make obtain 0 and max mark of subject
                    array_push($d, array("name" => "$subject_name", "obtain" => "0", "total" => /*"$itemX[total]"*/ $subjectMaxMark, "type" => "$term"));
                    if ($itemX["total"] != null) {
                        //$grandTotal += $itemX["total"];
                    }
    
    
                    $allTotal += $subjectMaxMark; //$itemX["total"];
                }
            }
        
        }

    }

    //get exam term detail
    $term_mark_array = array();
    foreach ($exam_term_db as $res_exam) {
        $term_mark_array[$res_exam["name"]] = $res_exam["total"];
    }


    //$percentage = ($subTotalObtained / $grandTotal) * 100;

    $jsonc["sub_total_obt"] = $subTotalObtained;
    $jsonc["grand_total"] = $allTotal; //"400";//$grandTotal;
    //$jsonc["percentage"] = number_format($percentage, 2) . "%";
    $jsonc["marks"] = $d;
    array_push($jsons, $jsonc);

}

$term_new = array();
$queryString = "SELECT exam FROM term_permission WHERE term = '$term_app' AND class = '$class' AND session = '$session' ";
if ($term_app == 'Final'){
    $queryString = "SELECT exam FROM term_permission WHERE class = '$class' AND session = '$session' ";
}
$res_term = $db->getRows($queryString);

if (is_array($res_term) && count($res_term) > 0){
    foreach ($res_term as $row_term) {
        $term_new[] = $row_term['exam'];
    }
}

$json['status'] = 1;
$json['msg'] = "Profile found Successfully..!";
$json['data'] = $jsons;
$json['term_mark'] = $term_mark_array;

$json['term_permit'] = $term_new;

echo json_encode($json);
