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

$status = 0;
$msg = "Unable to fetch data..! Please retry later";
$student_array = array();

$holiday_flag = "";
$day_name = "";

if (isset($_REQUEST['session']) && isset($_REQUEST['date']) && isset($_REQUEST['class'])) {

    $session = $_REQUEST['session'];
    $date    = $_REQUEST['date'];
    $class   = $_REQUEST['class'];

    $con_where = "";

    if (isset($_REQUEST['section']) && trim($_REQUEST['section']) != "") {
        $con_where = " AND section='" . $_REQUEST['section'] . "' ";
    }

    //$student_att_join_query = "SELECT t1.idno, t1.admissionno, t1.name, t1.fincome, t1.class, t1.section, t1.mobile, t1.photo, t2.id, t2.date, t2.late_flag FROM student t1 LEFT JOIN attandenc t2 ON t1.idno = t2.idno WHERE t1.class = '$class' $con_where AND t1.session = '$session' AND t1.status = 1 AND t1.issue_TC=0 AND t2.date='$date' AND t2.type='2' ORDER BY t1.name";
    //$db_result = $db->getRows($student_att_join_query);

    $db_result = $db->getRows("select idno,admissionno,name,fname,fincome,class,section,mobile,photo from student where class = '$class' $con_where AND session='$session' and status=1 and issue_TC=0 order by name");

    if (is_array($db_result) && count($db_result) > 0) {

        $status = 1;
        $msg = "Record found";

        foreach ($db_result as $row) {
            if (!empty($row['photo'])) {
                $row['photo'] = URL_ROOT . "media/photo/" . $row['photo'];
            } else {
                $row['photo'] = "";
            }

            $result_att = $db->getRow("SELECT id,idno,status,period,late_flag from attandenc where date='$date' and session='$session' and type='2' and idno = '$row[idno]' ");

            if ($result_att && count($result_att) > 1) {

                if ($result_att['late_flag'] == 'LATE') {
                    $row['att_status'] = 2;
                } else {
                    $row['att_status'] = 1;
                }

                $row['att_id'] = $result_att['id'];
                
            } else {
                $row['att_status'] = 0;
                $row['att_id'] = 0;
            }

            $student_array[] = $row;
        }
    }else{
        $msg = "Record not found";
    }

    //Holiday Check
    $holiday = $db->getVal("select reasion from holiday where date = '$date' and class = '$class' and session = '$session' and school_id= '1' ");

    if (!empty($holiday)) {
        $holiday_flag = 'H';
    }

    $day_name = date('l', strtotime($date));

}

echo json_encode(array("status" => $status, "data" => $student_array, "holiday_flag" => $holiday_flag, "day_name" => $day_name, "msg" => $msg));