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

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

// 	 $session=mysql_real_escape_string($session);
// $arr=$db->getRows("select * from assignment where added_by='".$Added_by."' and date='$date' and session='$session' and school_id= '$school_id' and status='1'");

$sql = $db->getRows("select * from teacher_leave where  session='$session' and teacher_id='$teacher_id' ORDER BY id DESC");

$cl_count = $db->getVal("SELECT cl_count FROM staff WHERE idno = '$teacher_id'");

// 	$result = mysql_query($sql);
//   while ($row = mysql_fetch_assoc($result))

$array_store = array();

foreach ($sql as $row) {


//    $jsonn[] = array("id" => $row['id'], "teacher_id" => $row['teacher_id'], "subject" => $row['subject'], "details" => $row['details'], "date" => $row['date'], "image" => "uploads/assignment/" . $row['image'], "leave_status" => $row['leave_status'], "remarks" => $row['remarks']);

    ///
    $tmp = array("id" => $row['id'], "date" => $row['date'], "leave_status" => $row['leave_status'], "is_half_day" => $row['is_half_day']);

    $ct_id = $row['content_id'];

    if ($ct_id == 0) {
        $jsonn[] = array("id" => $row['id'], "teacher_id" => $row['teacher_id'], "subject" => $row['subject'], "details" => $row['details'], "date" => $row['date'], "image" => "uploads/assignment/" . $row['image'],
            "leave_status" => $row['leave_status'], "remarks" => $row['remarks'],"leave_date" => array($tmp));

    } else {
        if (array_key_exists($ct_id, $array_store)) {
            $array_store[$ct_id]['leave_date'][] = $tmp; //$new_date;
        } else {
            $array_store[$ct_id] =  array("id" => $row['id'], "teacher_id" => $row['teacher_id'], "subject" => $row['subject'], "details" => $row['details'], "date" => $row['date'],
                "image" => "uploads/assignment/" . $row['image'], "leave_status" => $row['leave_status'], "remarks" => $row['remarks'],"leave_date" => array($tmp));
        }
    }

    ///

}

foreach ($array_store as $item) {
    $jsonn[] = $item;
}

$json['status'] = 1;
$json['msg'] = "successful";
$json['data'] = $jsonn;

$json['cl_count'] = $cl_count;

$usedRow = $db->getRows("SELECT id,is_half_day FROM teacher_leave WHERE teacher_id = '$teacher_id' AND session = '$session' AND leave_status = '1' AND content_id != '0' ");

$used_leave = 0;
foreach ($usedRow as $single_row) {
    if ($single_row['is_half_day'] == 1){
        $used_leave = $used_leave + 0.5;
    }else{
        $used_leave = $used_leave + 1;
    }
}

$json['cl_remaining'] = ($cl_count - $used_leave);

if (is_array($jsonn) && count($jsonn) > 0) {
    echo json_encode($json);
} else {
    echo json_encode(array('status' => 0, 'msg' => 'data not found..!'));
}