<?php
require_once __DIR__ . '/inc/bootstrap.php'; require_login('admin');
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_FILES['qfile'])){
    $file=$_FILES['qfile']; if($file['error']!==UPLOAD_ERR_OK){ flash_set('Upload error code: '.$file['error']); header('Location: admin.php'); exit; }
    $ext=strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); if(!in_array($ext,['xlsx','csv'])){ flash_set('Unsupported file type: .'.$ext); header('Location: admin.php'); exit; }
    if(!file_exists(DATA_DIR)) @mkdir(DATA_DIR,0775,true);
    $target=DATA_DIR.'questions.' . $ext; if(!move_uploaded_file($file['tmp_name'],$target)){ flash_set('Failed to move uploaded file.'); header('Location: admin.php'); exit; }
    if($ext==='csv'){ copy($target, DATA_DIR.'questions.csv'); } else { copy($target, DATA_DIR.'questions.xlsx'); }
    flash_set('Questions file uploaded successfully.');
}
header('Location: admin.php'); exit;