<? include ("../settings.php"); ?>
<? include("session.php"); ?>
<?

    //$output = "\"SN\",\"Full Name\",\"Organisation\",\"Email\",\"RSVP\",\"Category\",\"Date Time Registered\",\"Registrant SN\",\"Replaced\",\"Replacing\",\"Attended\"\n";
    $results = $db->run("select * from tbl_registrant  limit 1");
    $result = $results[0];
    $output = "";
    foreach (array_keys($result) as $key){
        if ($output=="")
            $output = "\"".$key."\"";
        else
            $output .= ",\"".$key."\"";
    }
    //$output .= ",\"Attended 1\",\"Attended 2\",\"Attended 3\",\"Attended 4\",\"Attended 5\",\"Attended 6\",\"Attended 7\",\"Attended 8\"\n";
    $output .= ",\"Attended 1\",\"Attended 2\"\n";

	$file = $_SERVER['DOCUMENT_ROOT']."/APCOT2024/csv/SASO2025.csv";
	$fp = fopen($file, 'w');
	fwrite($fp, $output);
    $results = $db->run("select * from tbl_registrant ORDER by registrant_id ASC");
	foreach ($results as $result){

        $bind = array(
            ":search1" => $result['registrant_id']
        );
        $attend = $db->select("tbl_registrant_attendance", "registrant_id = :search1 AND session_id=1", $bind);
        if (count($attend)>0)
            $attended1 = "Yes (".$attend[0]['attendance_datetime'].")- Admin ".$attend[0]['user_id'];
        else
            $attended1 = "No";
        $attend = $db->select("tbl_registrant_attendance", "registrant_id = :search1 AND session_id=2", $bind);
        if (count($attend)>0)
            $attended2 = "Yes (".$attend[0]['attendance_datetime'].")- Admin ".$attend[0]['user_id'];
        else
            $attended2 = "No";

        $output = "";
        foreach ($result as $record){
            if ($output=="")
                $output = "\"".$record."\"";
            else
                $output .= ",\"".$record."\"";
        }
        
        //$output .= ",\"$attended1\",\"$attended2\",\"$attended3\",\"$attended4\",\"$attended5\",\"$attended6\",\"$attended7\",\"$attended8\"\n";
        $output .= ",\"$attended1\",\"$attended2\"\n";
        //echo $output;
		fwrite($fp, $output);
	}

	fclose($fp);

     // Set headers
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=SASO2025.csv");
     header("Content-Type: application/zip");
     header("Content-Transfer-Encoding: binary");

     // Read the file from disk
     readfile($file);

?>