<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';require_once __DIR__.'/../lib/system_settings.php';require_once __DIR__.'/../lib/openrouter.php';
$user=require_auth();if(!in_array($user['role'],['admin','staff'],true))reply(403,['message'=>'Management access required.']);
try{
 if(($_SERVER['REQUEST_METHOD']??'GET')==='GET'){
  $config=platform_settings(true);$ai=assistant_settings();$backups=db()->query('SELECT b.id,b.backup_status,b.created_at,COALESCE(u.full_name,u.username) created_by FROM system_backups b LEFT JOIN users u ON u.id=b.created_by ORDER BY b.id DESC LIMIT 30')->fetchAll();
  $checks=['Database connection'=>true,'PHP 8.1 or newer'=>version_compare(PHP_VERSION,'8.1','>='),'cURL for AI'=>function_exists('curl_init'),'ZIP extraction'=>class_exists('ZipArchive'),'Compressed backups'=>function_exists('gzopen'),'AI enabled and configured'=>$ai['key']!==''];
  try{$q=db()->query('SELECT started_on FROM login_attendance_settings WHERE id=1');$started=$q->fetchColumn();}catch(Throwable $e){$started=null;}$checks['Attendance migration installed']=(bool)$started;
  $audit=db()->query("SELECT a.action,a.summary,a.created_at,COALESCE(u.full_name,u.username) actor FROM system_audit_log a LEFT JOIN users u ON u.id=a.actor_id WHERE a.entity='system_settings' ORDER BY a.id DESC LIMIT 15")->fetchAll();
  reply(200,['settings'=>$config,'backups'=>$backups,'checks'=>$checks,'attendance_started'=>$started,'audit'=>$audit,'csrf_token'=>$_SESSION['csrf_token']]);
 }
 if(($_SERVER['REQUEST_METHOD']??'')!=='POST')reply(405,['message'=>'Use GET or POST.']);$data=post_data(16000);$action=(string)($data['action']??'');
 if($action==='save'){
  $values=platform_validate($data);$db=db();$db->beginTransaction();try{$db->prepare("INSERT IGNORE INTO system_settings(setting_key,setting_value) VALUES('platform','{}')")->execute();$q=$db->prepare("SELECT setting_value FROM system_settings WHERE setting_key='platform' FOR UPDATE");$q->execute();$old=json_decode($q->fetchColumn(),true)?:[];if((int)($data['revision']??-1)!==(int)($old['revision']??0)){ $db->rollBack();reply(409,['message'=>'Settings changed elsewhere. Reload before saving.']);}$values['revision']=(int)($old['revision']??0)+1;$db->prepare("UPDATE system_settings SET setting_value=?,updated_by=? WHERE setting_key='platform'")->execute([json_encode($values,JSON_THROW_ON_ERROR),(int)$user['id']]);$db->commit();}catch(Throwable $e){if($db->inTransaction())$db->rollBack();throw $e;}
  audit_event((int)$user['id'],$user['role'],'system_settings',null,'save_settings','Updated system preferences');reply(200,['message'=>'Settings saved and applied.']);
 }
 if($action==='backup'){@set_time_limit(180);$id=settings_make_backup((int)$user['id']);audit_event((int)$user['id'],$user['role'],'system_settings',$id,'create_backup','Created database backup');reply(201,['message'=>'Database backup created. Download it from the backup list.']);}
 if(in_array($action,['download','delete'],true)){
  $q=db()->prepare('SELECT * FROM system_backups WHERE id=?');$q->execute([(int)($data['id']??0)]);$b=$q->fetch();if(!$b)reply(404,['message'=>'Backup not found.']);$key=(string)$b['backup_storage_key'];if(!preg_match('/^[a-f0-9]{48}\.sql\.gz$/D',$key))reply(422,['message'=>'This legacy backup must be managed on the server.']);$file=settings_backup_root().'/'.$key;
  if($action==='delete'){if(is_file($file)&&!unlink($file))throw new RuntimeException('Cannot delete backup file.');db()->prepare('DELETE FROM system_backups WHERE id=?')->execute([$b['id']]);audit_event((int)$user['id'],$user['role'],'system_settings',(int)$b['id'],'delete_backup','Deleted database backup');reply(200,['message'=>'Backup deleted.']);}
  if($b['backup_status']!=='complete'||!is_file($file))reply(404,['message'=>'Backup file is unavailable.']);audit_event((int)$user['id'],$user['role'],'system_settings',(int)$b['id'],'download_backup','Downloaded database backup');header('Content-Type: application/gzip');header('Content-Disposition: attachment; filename="slps-database-'.(int)$b['id'].'.sql.gz"');header('Cache-Control: no-store');header('X-Content-Type-Options: nosniff');readfile($file);exit;
 }
 reply(400,['message'=>'Unknown settings action.']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('Settings: '.$e->getMessage());reply(503,['message'=>'Settings could not complete this action. Check database tables, PHP extensions and private storage permissions.']);}
