<?php
declare(strict_types=1);
require_once __DIR__.'/../shared/lib/system_settings.php';
function settings_check($ok){if(!$ok)throw new RuntimeException('Settings assertion failed');}
$data=platform_defaults();settings_check(platform_validate($data)['idle_minutes']===30);
foreach(['institution'=>'','support_email'=>'invalid','idle_minutes'=>0,'session_hours'=>25,'ai_model'=>"bad\r\nheader",'registration_open'=>'yes'] as $key=>$value){$bad=$data;$bad[$key]=$value;try{platform_validate($bad);throw new RuntimeException('Invalid setting accepted');}catch(InvalidArgumentException $e){}}
settings_check(settings_sql_value(null)==='NULL');settings_check(settings_sql_value("a'\x00") === "X'612700'");
$root=sys_get_temp_dir().'/slps-settings-test-'.bin2hex(random_bytes(5));function private_storage_root(){return $GLOBALS['root'];}
class SettingsTestDatabase {public bool $transaction=false,$fail=false;public array $updates=[];function beginTransaction(){$this->transaction=true;}function commit(){$this->transaction=false;}function inTransaction(){return $this->transaction;}function rollBack(){$this->transaction=false;}function lastInsertId(){return 5;}function prepare($sql){return new SettingsTestQuery($this,$sql);}function query($sql){if($this->fail&&str_starts_with($sql,'SELECT *'))throw new RuntimeException('Simulated export failure');return new SettingsTestQuery($this,$sql);}}
class SettingsTestQuery {function __construct(public SettingsTestDatabase $db,public string $sql){}function execute($args=[]){$this->db->updates[]=[$this->sql,$args];}function fetchAll(){if(str_starts_with($this->sql,'SHOW FULL'))return [['Table'=>'test','Table_type'=>'BASE TABLE']];if(str_contains($this->sql,'OFFSET 0'))return [['id'=>1,'value'=>"quote'\x00"]];return [];}function fetch(){return ['Table'=>'test','Create Table'=>'CREATE TABLE `test` (`id` INT,`value` BLOB)'];}}
$db=new SettingsTestDatabase();function db(){return $GLOBALS['db'];}
settings_check(settings_make_backup(9)===5);$files=glob($root.'/backups/*.sql.gz');settings_check(count($files)===1);$sql=gzdecode(file_get_contents($files[0]));settings_check(str_contains($sql,"X'71756f74652700'"));settings_check(str_contains($sql,'CREATE TABLE'));settings_check(str_contains($db->updates[1][0],"backup_status='complete'"));unlink($files[0]);
$db->fail=true;try{settings_make_backup(9);throw new RuntimeException('Expected export failure');}catch(RuntimeException $e){settings_check($e->getMessage()==='Simulated export failure');}settings_check(!$db->transaction);settings_check(!glob($root.'/backups/*.sql.gz'));settings_check(str_contains(end($db->updates)[0],"backup_status='failed'"));foreach(glob($root.'/backups/.*') as $p)if(is_file($p))unlink($p);rmdir($root.'/backups');rmdir($root);
echo "PASS: settings validation, safe SQL encoding, compressed backup generation and failed-backup cleanup.\n";
