<?php
declare(strict_types=1);
$root=dirname(__DIR__); $cfg=$root.'/storage/config.php';
if (file_exists($cfg)) { http_response_code(403); exit('Portal already installed.'); }
if (!extension_loaded('pdo_sqlite')) { http_response_code(503); exit('PDO SQLite is unavailable. Run INSTALL.bat in the windows folder.'); }
$installSessionDir=$root.'/storage/sessions'; if(!is_dir($installSessionDir)) @mkdir($installSessionDir,0750,true);
if(!is_dir($installSessionDir)||!is_writable($installSessionDir)){http_response_code(503);exit('Session directory is not writable.');}
session_name('NEXUSINSTALL'); ini_set('session.use_strict_mode','1'); ini_set('session.use_only_cookies','1'); ini_set('session.use_trans_sid','0'); ini_set('session.cookie_httponly','1'); ini_set('session.cookie_samesite','Lax');
session_set_cookie_params(['lifetime'=>0,'path'=>'/','secure'=>(!empty($_SERVER['HTTPS'])&&strtolower((string)$_SERVER['HTTPS'])!=='off'),'httponly'=>true,'samesite'=>'Lax']); session_save_path($installSessionDir); session_start();
if(empty($_SESSION['install_csrf'])) $_SESSION['install_csrf']=bin2hex(random_bytes(32));
function esc($s){return htmlspecialchars((string)$s,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');}
$err='';
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(!hash_equals($_SESSION['install_csrf']??'',$_POST['csrf']??'')){http_response_code(419);exit('Installation session expired. Reload the installer.');}
 $name=trim($_POST['username']??'');$email=trim($_POST['email']??'');$pw=$_POST['password']??'';$confirm=$_POST['confirm']??'';
 if(strlen($name)<3||strlen($name)>40||!preg_match('/^[a-zA-Z0-9_.-]+$/',$name))$err='Username must be 3–40 characters (letters, numbers, dot, dash or underscore).';
 elseif(!filter_var($email,FILTER_VALIDATE_EMAIL))$err='Enter a valid email address.';
 elseif(strlen($pw)<12)$err='Password must be at least 12 characters.';
 elseif($pw!==$confirm)$err='Passwords do not match.';
 else {
  $db=null;$configWritten=false;$tmp=$cfg.'.tmp';
  try{
   foreach(['storage','storage/files','storage/logs','storage/sessions','storage/tmp'] as $d){if(!is_dir($root.'/'.$d)&&!mkdir($root.'/'.$d,0750,true))throw new RuntimeException('Cannot create storage directory.');}
   $db=new PDO('sqlite:'.$root.'/storage/portal.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$db->exec('PRAGMA foreign_keys=ON');$db->exec('PRAGMA busy_timeout=8000');$db->beginTransaction();
   $db->exec("CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT UNIQUE NOT NULL,email TEXT UNIQUE NOT NULL,password_hash TEXT NOT NULL,is_admin INTEGER NOT NULL DEFAULT 0,created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);");
   $db->exec("CREATE TABLE requests(id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER NOT NULL,service TEXT NOT NULL,region TEXT NOT NULL DEFAULT '',notes TEXT NOT NULL DEFAULT '',status TEXT NOT NULL DEFAULT 'pending',file_name TEXT,file_path TEXT,created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE);");
   $db->exec('CREATE INDEX idx_requests_user ON requests(user_id)');$db->exec('CREATE INDEX idx_requests_status ON requests(status)');$db->exec('CREATE TABLE portal_sessions (id TEXT PRIMARY KEY, data TEXT NOT NULL, last_activity INTEGER NOT NULL)');
   $st=$db->prepare('INSERT INTO users(username,email,password_hash,is_admin) VALUES(?,?,?,1)');$st->execute([$name,$email,password_hash($pw,PASSWORD_DEFAULT)]);
   $config=['installed'=>true,'app_key'=>bin2hex(random_bytes(32)),'site_name'=>'NEXUS VPN Portal','max_upload_mb'=>25];
   $written=file_put_contents($tmp,"<?php\nreturn ".var_export($config,true).";\n",LOCK_EX);if($written===false)throw new RuntimeException('Cannot write portal config.');@chmod($tmp,0640);
   if(!rename($tmp,$cfg))throw new RuntimeException('Cannot finalize config file.');$configWritten=true;$db->commit();header('Location: /login?installed=1');exit;
  }catch(Throwable $e){if($db instanceof PDO&&$db->inTransaction())$db->rollBack();if($configWritten&&file_exists($cfg))@unlink($cfg);if(file_exists($tmp))@unlink($tmp);$err='Installation failed. Ensure storage is writable and PHP SQLite is enabled.';}
 }
}
?><!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Install NEXUS</title><link rel="stylesheet" href="/assets/style.css"></head><body><main class="installer"><div class="brand"><span class="logo">N</span><span>NEXUS<span class="blue"> VPN</span><small>FIRST-TIME SETUP</small></span></div><h1>Initialize your portal.</h1><p class="muted">Create the first administrator. Installation initializes the database and local configuration.</p><?php if($err):?><div class="flash error"><?=esc($err)?></div><?php endif?><form method="post" class="form"><input type="hidden" name="csrf" value="<?=esc($_SESSION['install_csrf'])?>"><label>Administrator username<input name="username" required minlength="3" maxlength="40" autocomplete="username" value="<?=esc($_POST['username']??'')?>"></label><label>Email address<input name="email" type="email" required autocomplete="email" value="<?=esc($_POST['email']??'')?>"></label><label>Password<input name="password" type="password" required minlength="12" autocomplete="new-password"></label><label>Confirm password<input name="confirm" type="password" required autocomplete="new-password"></label><button class="btn primary full">Install portal <span>→</span></button></form><p class="fine">Installer is available only before initialization. Remove or deny access to install.php after setup.</p></main></body></html>
