<?php
declare(strict_types=1);
function platform_defaults(): array {return ['revision'=>0,'institution'=>'Rockview University','support_email'=>'','support_phone'=>'','academic_year'=>(int)date('Y'),'registration_open'=>true,'idle_minutes'=>30,'session_hours'=>8,'ai_enabled'=>true,'ai_model'=>'','public_url'=>''];}
function platform_settings(bool $fresh=false): array {
 static $cached=null;if($cached!==null&&!$fresh)return $cached;
 try{$q=db()->prepare('SELECT setting_value FROM system_settings WHERE setting_key=?');$q->execute(['platform']);$raw=$q->fetchColumn();$value=$raw?json_decode($raw,true):[];return $cached=array_merge(platform_defaults(),is_array($value)?$value:[]);}catch(Throwable $e){return $cached=platform_defaults();}
}
function platform_validate(array $data): array {
 $out=platform_defaults();$out['institution']=trim((string)($data['institution']??''));if($out['institution']===''||strlen($out['institution'])>150)throw new InvalidArgumentException('Enter an institution name up to 150 characters.');
 foreach(['support_email'=>254,'support_phone'=>40,'ai_model'=>150] as $key=>$max){$out[$key]=trim((string)($data[$key]??''));if(strlen($out[$key])>$max||preg_match('/[\x00-\x1f]/',$out[$key]))throw new InvalidArgumentException('Invalid '.$key.'.');}
 $out['public_url']=rtrim(trim((string)($data['public_url']??'')),'/');if($out['public_url']!==''&&(strlen($out['public_url'])>200||!filter_var($out['public_url'],FILTER_VALIDATE_URL)||!in_array(parse_url($out['public_url'],PHP_URL_SCHEME),['http','https'],true)||parse_url($out['public_url'],PHP_URL_USER)||parse_url($out['public_url'],PHP_URL_PASS)||parse_url($out['public_url'],PHP_URL_QUERY)||parse_url($out['public_url'],PHP_URL_FRAGMENT)))throw new InvalidArgumentException('Enter a valid http/https system base URL without credentials or query parameters.');
 if($out['support_email']!==''&&!filter_var($out['support_email'],FILTER_VALIDATE_EMAIL))throw new InvalidArgumentException('Enter a valid support email.');
 if($out['ai_model']!==''&&!preg_match('~^[a-zA-Z0-9][a-zA-Z0-9/_.:+-]*$~',$out['ai_model']))throw new InvalidArgumentException('Enter a valid OpenRouter model identifier.');
 foreach(['academic_year'=>[2000,2100],'idle_minutes'=>[5,120],'session_hours'=>[1,24]] as $key=>[$min,$max]){$value=filter_var($data[$key]??null,FILTER_VALIDATE_INT);if($value===false||$value<$min||$value>$max)throw new InvalidArgumentException('Invalid '.str_replace('_',' ',$key).'.');$out[$key]=$value;}
 foreach(['registration_open','ai_enabled'] as $key){if(!is_bool($data[$key]??null))throw new InvalidArgumentException('Invalid switch value.');$out[$key]=$data[$key];}
 if($out['idle_minutes']>$out['session_hours']*60)throw new InvalidArgumentException('Inactivity timeout must not exceed the total session duration.');
 return $out;
}
function settings_backup_root(): string {
 $path=private_storage_root().'/backups';if(!is_dir($path)&&!mkdir($path,0700,true)&&!is_dir($path))throw new RuntimeException('Backup storage is not writable.');
 if(file_put_contents($path.'/.htaccess',"Require all denied\nDeny from all\n")===false)throw new RuntimeException('Cannot protect backup storage.');return $path;
}
function settings_sql_value($value): string {return $value===null?'NULL':"X'".bin2hex((string)$value)."'";}
function settings_make_backup(int $actor): int {
 if(!function_exists('gzopen'))throw new RuntimeException('Enable PHP zlib to create backups.');
 $root=settings_backup_root();$lock=fopen($root.'/.lock','c');if(!$lock||!flock($lock,LOCK_EX|LOCK_NB))throw new RuntimeException('Another backup is running. Try again shortly.');
 $key=bin2hex(random_bytes(24)).'.sql.gz';$file=$root.'/'.$key;$gzip=null;$db=db();$id=0;
 try{
  $q=$db->prepare("INSERT INTO system_backups(backup_storage_key,created_by,backup_status) VALUES(?,?,'pending')");$q->execute([$key,$actor]);$id=$db->lastInsertId();$gzip=gzopen($file,'wb6');if(!$gzip)throw new RuntimeException('Cannot create backup.');chmod($file,0600);$bytes=0;
  $write=static function(string $sql)use($gzip,&$bytes){$bytes+=strlen($sql);if($bytes>262144000)throw new RuntimeException('Database exceeds the 250 MB export limit. Use your database backup tools.');if(gzwrite($gzip,$sql)!==strlen($sql))throw new RuntimeException('Backup storage is full.');};
  $db->beginTransaction();$tables=$db->query("SHOW FULL TABLES WHERE Table_type='BASE TABLE'")->fetchAll();
  $write("-- SLPS database backup (database only; uploaded files and server configuration are separate)\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\n");
  foreach($tables as $table){$name=(string)array_values($table)[0];$identifier='`'.str_replace('`','``',$name).'`';$definition=$db->query('SHOW CREATE TABLE '.$identifier)->fetch();$write('DROP TABLE IF EXISTS '.$identifier.";\n".array_values($definition)[1].";\n");
   for($offset=0;;$offset+=100){$rows=$db->query('SELECT * FROM '.$identifier.' LIMIT 100 OFFSET '.$offset)->fetchAll();if(!$rows)break;foreach($rows as $row){$columns=implode(',',array_map(static fn($c)=>'`'.str_replace('`','``',$c).'`',array_keys($row)));$write('INSERT INTO '.$identifier.' ('.$columns.') VALUES('.implode(',',array_map('settings_sql_value',array_values($row))).");\n");}}
  }
  $write("SET FOREIGN_KEY_CHECKS=1;\n");$db->commit();if(!gzclose($gzip))throw new RuntimeException('Backup could not finish.');$gzip=null;$db->prepare("UPDATE system_backups SET backup_status='complete' WHERE id=?")->execute([$id]);return $id;
 }catch(Throwable $e){if($db->inTransaction())$db->rollBack();if(is_resource($gzip))gzclose($gzip);if(is_file($file))unlink($file);if($id)$db->prepare("UPDATE system_backups SET backup_status='failed' WHERE id=?")->execute([$id]);throw $e;}finally{flock($lock,LOCK_UN);fclose($lock);}
}
