<?php 
session_start();
// ============
include("../../asset/theme/css/myfunc.php");
//include("../../php_crud/my_class_for_web.php");
include("../../php_crud/my_class.php");
$obj = new my_class();
$branch_id = $_SESSION['LOGIN_BRANCH'];
$current_session = $_SESSION['ADMISSION_SESSION'];

$selected_method=addslashes(trim($_GET['selected_method']));
$mark_greater_input=addslashes(trim($_GET['selected_mark_greater']));
$seats_no_input=addslashes(trim($_GET['selected_seat_numbers']));
$detailed_id_as_class=addslashes(trim($_GET['detailed_id_as_class']));
//echo "selected_method=".$selected_method."--mark_greater_input=".$mark_greater_input."--seats_no_input=".$seats_no_input."--class=".$detailed_id_as_class;

$table_name='_students_admission_form f LEFT JOIN _students_admission_mark_entry e ON f.admission_id = e.admission_id';
$column="f._candidate_name,f.admission_form_id,e.exam_mark,e.result_status,e.mark_entry_id,f.branch_id";
$where_cond="f._session='".$current_session."' AND f._class='".$detailed_id_as_class."' AND  e.result_status='P' AND e.list_type!='merit' ORDER BY e.exam_mark DESC";// AND (f._approve_status='A' OR f._approve_status='S') ";


/*if($selected_method=='manual'){
	 $where_cond= $where_cond." ORDER BY e.serial_num ASC ";
	//$where_cond= $where_cond." ORDER BY e.admission_id ASC ";
}*/	
// echo 'SELECT * FROM '.$table_name.' WHERE'.$where_cond ;	
$can_list=$obj->View_all_data_row_column_By_Cond($table_name,$column, $where_cond);
$result = array();


/*$table_name='_students_admission_mark_settings';
$where_cond="branch_id='".$branch_id."' limit 1";
$column = '	total_mark,pass_mark';
$settings=$obj->View_all_data_row_column_By_Cond($table_name,$column, $where_cond);
$total_mark = $settings[0]['total_mark'];
$pass_mark = $settings[0]['pass_mark'];*/

$table_name='_students_admission_mark_settings';
$where_cond="current_session='".$current_session."'";
//$column = '	total_mark,pass_mark';
$settings=$obj->Details_By_Cond($table_name, $where_cond);
$total_mark = '';
$pass_mark = '';
if(count($settings)>0){ 
	$total_mark = $settings['total_mark'];
	$pass_mark = $settings['pass_mark'];
}
$passed_mark = ($pass_mark/100)*$total_mark;

$i = 0;
//echo '<pre>';
//print_r($can_list);


foreach ($can_list AS $index1 => $value1) {
	$got_mark = $value1['exam_mark'] ;
	$status = '';
	$status_d = '';
	$entry_status = '';
	
	if($passed_mark<=$got_mark ){
		
		$status = '<span class="label label-info arrowed arrowed-right">Pass</span> ';
		$status_d = 'Pass';
		$entry_status = 'P';
		if($selected_method=='Random'){
			if($got_mark>=$mark_greater_input){
				$got_mark = $value1['exam_mark'] ;
				$result[$i]['status'] = $status;
		
				$result[$i]['mark_entry_id'] = $value1['mark_entry_id'];
				$result[$i]['_candidate_name'] = $value1['_candidate_name'];
				$result[$i]['admission_form_id'] = $value1['admission_form_id'];
				//$result[$i]['_class'] = $value1['_class'];
				$result[$i]['exam_mark'] = $value1['exam_mark'];
				//$result[$i]['admission_exam_roll'] = $value1['admission_exam_roll'];
				$result[$i]['selection_status'] = $value1['selection_status'] ;
				$result[$i]['list_type'] = $value1['list_type'] ;
				$result[$i]['branch_id'] = $value1['branch_id'] ;
				$i++;
			}
		}else{
				$got_mark = $value1['exam_mark'] ;
				$result[$i]['status'] = $status;
				$result[$i]['mark_entry_id'] = $value1['mark_entry_id'];
				$result[$i]['_candidate_name'] = $value1['_candidate_name'];
				$result[$i]['admission_form_id'] = $value1['admission_form_id'];
				//$result[$i]['_class'] = $value1['_class'];
				$result[$i]['exam_mark'] = $value1['exam_mark'];
				$result[$i]['selection_status'] = $value1['selection_status'] ;
				$result[$i]['serial_num'] = $i+1 ;
				//$result[$i]['admission_exam_roll'] = $value1['admission_exam_roll'];
				$result[$i]['list_type'] = $value1['list_type'] ;
				$result[$i]['branch_id'] = $value1['branch_id'] ;
				$i++;
		
		}
		
		
	}else{
	 	if($selected_method=='manual'){
			$status = '&nbsp;<span class="label label-important arrowed-in">Fail  </span>&nbsp; ';
	 		$status_d = 'Fail';
	 		$entry_status = 'F';
			
				$got_mark = $value1['exam_mark'] ;
				$result[$i]['status'] = $status;
				$result[$i]['mark_entry_id'] = $value1['mark_entry_id'];
				$result[$i]['_candidate_name'] = $value1['_candidate_name'];
				$result[$i]['admission_form_id'] = $value1['admission_form_id'];
				//$result[$i]['_class'] = $value1['_class'];
				$result[$i]['exam_mark'] = $value1['exam_mark'];
				$result[$i]['selection_status'] = $value1['selection_status'] ;
				//$result[$i]['admission_exam_roll'] = $value1['admission_exam_roll'];
				$result[$i]['list_type'] = $value1['list_type'] ;
				$result[$i]['branch_id'] = $value1['branch_id'] ;
				//$result[$i]['serial_num'] = $value1['serial_num'] ;
				$i++;
		}
	}
	
	 
/*	$form_data=array(
				'result_status'=>$entry_status,
		);
	 $up=$obj->Update_Data('_students_admission_mark_entry',$form_data,'mark_entry_id="'.$value1['mark_entry_id'].'"');
*/	
//	if($selected_method=='highest_mark' ){
	
	   
//	}
	
	
	
}
function msort($array, $key, $sort_flags = SORT_REGULAR) {
    if (is_array($array) && count($array) > 0) {
        if (!empty($key)) {
            $mapping = array();
            foreach ($array as $k => $v) {
                $sort_key = '';
                if (!is_array($key)) {
                    $sort_key = $v[$key];
                } else {
                    // @TODO This should be fixed, now it will be sorted as string
                    foreach ($key as $key_key) {
                        $sort_key .= $v[$key_key];
                    }
                    $sort_flags = SORT_STRING;
                }
                $mapping[$k] = $sort_key;
            }
            asort($mapping, $sort_flags);
            $sorted = array();
            foreach ($mapping as $k => $v) {
                $sorted[] = $array[$k];
            }
            return $sorted;
        }
    }
    return $array;
}

if(($selected_method !='Random') && ($selected_method !='manual')){
	$resu = msort($result, array('exam_mark'));
	 krsort($resu);
	
}else{
	$resu = $result; 
	}
//echo '<pre>';
//print_r($resu);

if($selected_method=='highest_mark'){
	if($seats_no_input && count($resu)>$seats_no_input)
		//$result = array_slice($result, $num-$seats_no_input); 
		$resu = array_slice($resu, 0, $seats_no_input);
}
$t = array();

function array_random($arr, $num = 1) {
    $keys = array_keys($arr);
    shuffle($keys);
    
    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[$keys[$i]] = $arr[$keys[$i]];
    }
    return $r;
	
	/*shuffle($arr);
   
    $r = array();
    for ($i = 0; $i < $num; $i++) {
        $r[i] = $arr[$i];
    }
    return $num == 1 ? $r[0] : $r;*/
}

if($selected_method=='Random'){
	 if($seats_no_input && count($resu)>$seats_no_input)
	 	{	  	
			$rand_keys = array_random($resu, $seats_no_input); 
		}
		else if($seats_no_input)
		{ 
			$rand_keys = array_random($resu, count($resu)); 		
		}
	$resu = $rand_keys;
}

?>
<div class="row-fluid">
    <button class="btn btn-small btn-primary " id="print-merit-list" style="float:right; margin-bottom:10px" onclick="create_pdf_merit_list(<?php echo $detailed_id_as_class;?>)">
		<i class="icon-print "></i>
		Print
	</button>
</div> 
<div class="row-fluid">
	<form id="mark-info" >
		<?php if($selected_method=='manual') echo '<label> Approved Candidate = <span class="approved_num"> </span> </label>'; ?>  
            <table id="sample-table-22" class="table table-striped table-bordered table-hover">
                <thead>
                <th>Sl</th>
                <th>Name</th>
                <th>Form No</th>
               <!--<th>Roll No</th>
                <th>Class</th>-->
                <th>Mark</th>
                <th>Status</th>
               <?php if($selected_method=='manual') echo '<th>Serial</th> <th>Action</th>'; ?> 
            </thead>
            <tbody>
                <?php
                    $sl = 1;
					$i = 1;
					$serial = '';
					foreach ($resu AS $index1 => $value1) {
                        echo '<tr class="every">';
						if($selected_method=='manual'){
							if(isset($value1['serial_num']))
							$serial = $value1['serial_num'];	
							else
								$serial = 0;
						}else{
							$serial = $i;
						}
				?>  
                <td> <?php echo $sl ; ?>  </td>
                <td><?php echo $value1['_candidate_name'] ; ?> </td>
                <td><?php echo $value1['admission_form_id'] ?> </td>
                <!--<td><?php //echo $value1['admission_exam_roll'] ?> </td>
                <td><?php //echo $value1['_class'];   ?></td>-->
				<td> <?php echo $value1['exam_mark']; ?> </td>
                <td> <?php echo $value1['status'];?></td> 
                <?php 
					if($_SESSION['add']=='Y'){	  
						if($selected_method=='manual') 
							echo '<td><input type="text" name="serial" value="'.$serial.'" class="serial"  /></td>';
						else
							echo '<input type="hidden" name="serial" value="'.$serial.'" class="serial"  />';
				?>
                <?php 
						if($selected_method=='manual'){
							$selection_status = $value1['selection_status'];
							$list_type = $value1['list_type'];
							if($selection_status==0 || $list_type !='merit'){
								$appro_status = 'Approve';
								$approve_class = 'btn-info tooltip-success btn-single-approve';
								$data_title = 'Click to Approve';
							}else{
								$appro_status = 'Approved';
								$approve_class = 'btn-success tooltip-info  btn-single-unapprove';
								$data_title = 'Click to Unapprove';
							}
							echo '<td class="approve-button"> <span data-original-title="'.$data_title.'" class="btn  btn-small  icon-ok '.$approve_class.'" data-rel="tooltip" data-placement="top" title="">'.$appro_status.'</span></td>';
						}	 		
					}
				?> 
                <input type="hidden" name="mark" value="<?php echo $value1['mark_entry_id']; ?>" class="mark"  /> 
				<input type="hidden" value="<?php echo $value1['branch_id']; ?>" id="branch_id" class="branch_id" />
				<?php   $sl++;  $i++; } ?>
            </tbody>	
		</table>
             
	</form>             
</div>
<?php 
if($_SESSION['edit']=='Y'){
		if($selected_method !='manual'){
		?>
		<div class="row-fluid">
			<button class="btn btn-small btn-success" type="button" id="btn_approve">
				<i class="icon-ok bigger-100"></i>
				Approve
			</button>
		</div>
	<?php 
		}
} ?>
<script>
$(document).ready(function(){
	document.getElementById("print-merit-list").style.display = "block";
});
		$('[data-rel=tooltip]').tooltip();
            var oTable2 = $('#sample-table-22').dataTable({
                "aoColumns": [
                    {"bSortable": true},
                    null, null, null,  <?php if($selected_method=='manual') echo 'null,null,'; ?>  
                    {"bSortable": true}
                ]});
  	function classCount(name){
		  var num = $('.'+name).size();
		  return num;
	}
	var num = classCount('btn-single-unapprove') ;
	 $(".approved_num").text(num);
  
   $( "#btn_approve" ).click(function() {
		 $this = $(this);
		 var mark = '';
		 var i = 0;
		 var list_type='merit';
		 //branch_id = $( "#branch_id" ).val();
		 //var alldat = {"branch_id":branch_id,"list_type":list_type,data:[]};
		 var alldat = {"list_type":list_type,data:[]};
		 var sing ;
		 $( ".every" ).each(function() {
			//i++;
		    //if(i==1) mark = $( this ).find( ".mark" ).val();
			//else mark = mark+','+$( this ).find( ".mark" ).val();
			mark = $( this ).find( ".mark" ).val();
			serial = $( this ).find( ".serial" ).val();
			branch_id = $( this ).find( ".branch_id" ).val();
			sing = {"mark":mark, "serial":serial, "branch_id":branch_id}
			//i++;
			alldat.data.push(sing);
		});
		
		var details_id = <?php echo $detailed_id_as_class;?>;
		 //var datastr = "selected_admission_details="+details_id+
						//"&total_num_of_entries="+i+
						//"&operation=check_approved_std_num_for_multiple_entry";
		
		/*$.ajax({
            type: 'post',
            url: "module/admission/merit_selection_ajax.php",
            data: datastr,
            success: function (response)
            {
				data = JSON.parse(response) ;
				if(data.warning){
					alert(data.warning);	
				}
				if(data.failed){
					alert(data.failed);
				}
				if(data.success){
					$.ajax({
						type: 'post',
						url: "module/admission/update_chosen_candidat_by_exam.php",
						data: alldat,
						dataType:"json",
						success: function (response)
						{
							
							//setTimeout('$("#msg").html("")', 5000);
						   alert('Success');
						}
					});
				}			   
            }
        });*/
		// var dataStr = "mark=" + data+"&branch_id=" + branch_id; 
		$.ajax({
            type: 'post',
            url: "module/admission/update_chosen_candidat_by_exam.php",
            data: alldat,
			dataType:"json",
            success: function (response)
            {
				
				//setTimeout('$("#msg").html("")', 5000);
               alert('Success');
            }
        });
		return false;
	});		
//	$( ".btn-single-approve" ).click(function() {
// $("").on("click", function(event){	



$("table").on("click", ".btn-single-approve", function(event){		
		 $this = $(this);
		 $paent = $this.parent();
		 var details_id = <?php echo $detailed_id_as_class;?>;
		 var datastr = "selected_admission_details="+details_id+
						"&operation=check_num_of_approved_std";
		 var mark = '';
		 var branch_id = '';
		 var i = 1;
		 var list_type='merit';
		 mark = $( this ).parent().parent().find( ".mark" ).val();
		 branch_id = $( this ).parent().parent().find( ".branch_id" ).val();
		 //branch_id = $( "#branch_id" ).val();
		 var dataStr = "mark=" + mark+"&branch_id=" + branch_id+"&list_type=" + list_type; 
		//alert(dataStr);
		
		$.ajax({
            type: 'post',
            url: "module/admission/merit_selection_ajax.php",
            data: datastr,
            success: function (response)
            {
               if(response=='failed'){
				   alert('Merit list is filled up');
			   }
			   else{
				   $.ajax({
						type: 'post',
						url: "module/admission/manual_approve_selected_candidat_by_exam.php",
						data: dataStr,
						success: function (response)
						{
							
						   $this.parent().empty();
						$paent.html('<span data-original-title="Click to Unapprove" class="btn  btn-small  icon-ok btn-success tooltip-info  btn-single-unapprove" data-rel="tooltip" data-placement="top" title="">Approved</span>'); 
						  // alert(response);
						  var num = classCount('btn-single-unapprove') ;
						  $(".approved_num").text(num);
						}
					});
			   }
            }
        });/*$.ajax({
            type: 'post',
            url: "module/admission/manual_approve_selected_candidat_by_exam.php",
            data: dataStr,
            success: function (response)
            {
				
               $this.parent().empty();
			$paent.html('<span data-original-title="Click to Unapprove" class="btn  btn-small  icon-ok btn-success tooltip-info  btn-single-unapprove" data-rel="tooltip" data-placement="top" title="">Approved</span>'); 
			  // alert(response);
			  var num = classCount('btn-single-unapprove') ;
			  $(".approved_num").text(num);
            }
        });*/

		return false;
	});
	
//	$( ".btn-single-unapprove" ).click(function() {
//	$(".btn-single-unapprove").on("click", function(event){
$("table").on("click", ".btn-single-unapprove", function(event){		
		 $this = $(this);
		 $paent = $this.parent();
		 var mark = '';
		 var branch_id = '';
		 var i = 1;
		 mark = $( this ).parent().parent().find( ".mark" ).val();
		 branch_id = $( this ).parent().parent().find( ".branch_id" ).val();
		 //var dataStr = "mark=" + mark; 
		 var dataStr = "mark=" + mark+"&branch_id=" + branch_id;
		//alert(dataStr);
		$.ajax({
            type: 'post',
            url: "module/admission/manual_unapprove_selected_candidat_by_exam.php",
            data: dataStr,
            success: function (response)
            {
               
			   $this.parent().empty();
			   $paent.html('<span data-original-title="Click to Approve" class="btn  btn-small  icon-ok btn-info tooltip-success btn-single-approve" data-rel="tooltip" data-placement="top" title="">Approve</span>'); 
			   // alert(response);
			   var num = classCount('btn-single-unapprove') ;
			  $(".approved_num").text(num);
            }
        });

		return false;
	});
	
$("table").on("change", ".serial", function(event){	
	var serial = $( this ).val();
	mark = $( this ).parent().parent().find( ".mark" ).val();
	branch_id = $( this ).parent().parent().find( ".branch_id" ).val();
	var dataStr = "mark=" + mark+"&branch_id=" + branch_id+"&serial=" + serial; 
	//alert(dataStr);
	$.ajax({
            type: 'post',
            url: "module/admission/update_serial_chosen_candidat.php",
            data: dataStr,
            success: function (response)
            {
              // alert
            }
        });
	
	
});				
</script>				

