<?php

// Check not accessed directly.
if (!isset($post_add)) {
    echo "Are you searching for something? You maybe in wrong place then!!";
    return;
}
// Common Add Code for database
$obj = new $_GET['master']();
$suc = $obj->set_assoc_array($_POST);
//var_dump($suc);
//var_dump($obj);
if (Master::isLegit($suc)) {
    //Database Part
    $dbh = new MyDbCon();
    $dbh->insert($obj);
    $dbh->prepare();
    if ($dbh->execute()) {
        $final = sprintf("%s Added Successfully!!", $_GET['master']::HEADING);
        $done = true;
    }
    echo json_encode(array("done" => $done, "final" => $final));
} else {
    echo json_encode($suc);
}
     $today = new DateTime();
     $lec_date = new DateTime($_POST['date']);
     $st_date = new DateTime($students['metadata']['start_date']);
     $end_date = new DateTime($students['metadata']['end_date']);
 } catch (\Exception $e) {
     attd_error(HTTP_Status::BAD_REQUEST, "Invalid lecture date format.");
 }
 if ($lec_date < $st_date || $lec_date > $today) {
     attd_error(HTTP_Status::BAD_REQUEST, "Lecture date must be within " . $st_date->format("d-m-Y") . " to " . $today->format("d-m-Y") . ".");
 }
 $lec_date = $lec_date->format("Y-m-d");
 try {
     $db = new MyDbCon();
     $db->beginTransaction();
     $obj = new Lectures(array('lec_date' => $lec_date, 'attd_mst_id' => $queries['mst']));
     $db->insert($obj);
     $db->prepare();
     $db->execute();
     $lec_id = $db->getLastGeneratedValue();
     $db->setInsert(new Attendance());
     $abs_objs = array();
     foreach ($students['data'] as $stud) {
         //$ids[]=$stud['stud_id'];
         $presence = 1;
         if (in_array($stud['stud_id'], $abs_ids)) {
             $presence = 0;
         }
         $abs_objs[] = new Attendance(array('lec_id' => $lec_id, 'stud_id' => $stud['stud_id'], 'presence' => $presence));
     }
     $db->multiInsert($abs_objs);
     $db->execute();