<?php
include("../../db.php");
header('Content-Type: application/json');

$class = $_GET['class'];
$session = $_GET['session'];
$section = $_GET['section'];
$myUid = $_GET['uid'];

$checkcontrol = $db->getVal("select teacher_chat_control from tbl_info");

$emptyJson = new stdClass();

if ($checkcontrol == 0) {

    $result = $db->getRows("select * from staff where session='$session' ");

    if ($result) {
        foreach ($result as $rowc) {

            $thread_name = getChatThread($myUid, "S", $rowc['idno']);
            $rec = $db->getRow("SELECT * FROM recent_message WHERE thread = '$thread_name' ") ?: $emptyJson;

            $jsonc[] = array("idno" => $rowc['idno'], "name" => $rowc['name'], "fname" => $rowc['fname'], "subject" => $rowc['experience'], "dob" => $rowc['dob'],
                "qualification" => $rowc['qualification'], "mobile" => $rowc['mobile'], "address" => $rowc['address'],
                "department" => $rowc['department'], "photo" => $rowc['photo'], "recent_msg" => $rec);

            $json['status'] = 1;
            $json['msg'] = "Profile found Successfully..!";
            $json['data'] = $jsonc;
        }
        echo json_encode($json);
    } else {
        echo json_encode(array('status' => 0, 'msg' => 'detail not found..!'));
    }

}

if ($checkcontrol == 1) {

    $result_term = $db->getRows("select distinct(s.idno), s.idno,s.department,s.name,s.experience,s.photo,e.class,e.teacher_id,e.session from staff as s inner join assign_teacher as e on s.idno=e.teacher_id where e.class='$class' and section='$section' and e.session='$session' ");
    // while ($rowc = mysql_fetch_assoc($result_term))
    foreach ($result_term as $rowc) {

        $thread_name = getChatThread($myUid, "S", $rowc['idno']);
        $rec = $db->getRow("SELECT * FROM recent_message WHERE thread = '$thread_name' ") ?: $emptyJson;

        $jsond[] = array("idno" => $rowc['idno'], "name" => "$rowc[name]", "fname" => "$rowc[fname]", "subject" => "$rowc[experience]", "dob" => "$rowc[dob]",
            "qualification" => "$rowc[qualification]", "mobile" => "$rowc[mobile]", "address" => "$rowc[address]",
            "department" => "$rowc[department]", "photo" => "$rowc[photo]", "recent_msg" => $rec);

    }

    if ($jsond == null) {
        $jsond = array();
    }

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

    if (is_array($json) && count($json) > 0) {
        echo json_encode($json);

    } else {
        echo json_encode(array('status' => 0, 'msg' => 'data not found..!'));
    }

}


function getChatThread($myId, $myutype, $otherId){
    if($myId < $otherId){
        return $myutype.$myId."_T".$otherId;
    }else{
        return "T".$otherId."_".$myutype.$myId;
    }
}