<?php
session_start();
require_once "../includes/db.php";
if (!isset($_SESSION['admin'])) { http_response_code(403); exit; }
function colExists(mysqli $db, string $t, string $c): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss",$t,$c); $st->execute();
  $r=$st->get_result(); return ($r && $r->num_rows>0);
}
$hasCreated = colExists($conn,'students','created_at');
$hasPlain1  = colExists($conn,'students','password_plain');
$hasPlain2  = !$hasPlain1 && colExists($conn,'students','plain_password');
$plainCol   = $hasPlain1 ? 'password_plain' : ($hasPlain2 ? 'plain_password' : null);

$course = trim($_GET['course_name'] ?? '');
$unit   = trim($_GET['unit_exam'] ?? '');
$q      = trim($_GET['q'] ?? '');
$days   = (int)($_GET['days'] ?? 0);
$where=" WHERE 1=1 "; $params=[]; $types="";
if ($course!==""){ $where.=" AND course_name=?"; $params[]=$course; $types.="s"; }
if ($unit  !==""){ $where.=" AND unit_exam=?";   $params[]=$unit;   $types.="s"; }
if ($q     !==""){ $like="%$q%"; $where.=" AND (name LIKE ? OR nic_number LIKE ? OR course_reg_no LIKE ?)";
  array_push($params,$like,$like,$like); $types.="sss"; }
if ($hasCreated && $days>0){ $where.=" AND created_at >= (NOW() - INTERVAL ? DAY)"; $params[]=$days; $types.="i"; }

$cols="name, course_reg_no, nic_number, course_name, unit_exam";
if ($plainCol) $cols.=", `$plainCol` AS password";
if ($hasCreated) $cols.=", created_at";
$sql="SELECT $cols FROM students $where ORDER BY ".($hasCreated?'created_at DESC, ':'')."id DESC";
$st=$conn->prepare($sql); if($types) $st->bind_param($types,...$params); $st->execute(); $res=$st->get_result();

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=students_created.csv');
$out = fopen('php://output', 'w');
$header = ['Name','Reg No.','NIC','Course','Module'];
if ($plainCol) $header[]='Password';
if ($hasCreated) $header[]='Created';
fputcsv($out,$header);
while($r=$res->fetch_assoc()){
  $row = [$r['name'],$r['course_reg_no'],$r['nic_number'],$r['course_name'],$r['unit_exam']];
  if ($plainCol) $row[] = $r['password'];
  if ($hasCreated) $row[] = $r['created_at'];
  fputcsv($out,$row);
}
fclose($out);
