<?php
   include('../config.php');
   include('inc.session-create.php');

   // Check if the user is logged in
   if (!isset($_SESSION['SUPER_ADMIN'])) {
       die("Unauthorized access.");
   }

   $admin = $db->getRow("SELECT * FROM admin_login WHERE id ='" . $_SESSION['SUPER_ADMIN']['id'] . "'");
   $distict_name = $admin['distict_name'];
   $usertype = $admin['usertype'];

   // Fetch data specific to the district or all if super admin
   if ($usertype == 0) { // 0 = super admin
       $aryList = $db->getRows("SELECT * FROM registration");
   } else {
       $aryList = $db->getRows("SELECT * FROM registration WHERE distict_name='" . $distict_name . "'");
   }
   // Set headers for CSV download
   header('Content-Type: text/csv; charset=utf-8');
   header('Content-Disposition: attachment; filename="district_data.csv"');

   // Open output stream
   $output = fopen('php://output', 'w');

   fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); // Add BOM for UTF-8

   // Write the header row
   fputcsv($output, [
       'ID',
       'District Name',
       'Block Name',
       'Game Name',
       'Name (Hindi)',
       'Name (English)',
       'Parents/Husband Name',
       'Gender',
       'DOB',
       'Address',
       'Adhar No.',
       'Blood Group',
       'Email ID',
       'Mobile NO.',
       "What's App NO.",
       'Category',
   ]);

   // Write data rows
   foreach ($aryList as $iList) {
       $districtname = $db->getRow("SELECT * FROM district WHERE id='" . $iList['distict_name'] . "'");
       $blockname = $db->getRow("SELECT * FROM block WHERE id='" . $iList['block_name'] . "'");

       fputcsv($output, [
           $iList['id'],
           $districtname['distict_name'],
           $blockname['block_name'],
           $iList['game_name'],
           $iList['name_hi'],
           $iList['name_en'],
           $iList['parents'],
           $iList['gender_name'],
           $iList['dob'],
           $iList['address'],
           $iList['addhar'],
           $iList['blood_group'],
           $iList['email'],
           $iList['mobileno'],
           $iList['whatsno'],
           $iList['category_name'],
       ]);
   }

   fclose($output);
   exit();
   ?>
