<?php
declare(strict_types=1);
const STORE=__DIR__.'/../private/';
ini_set('display_errors','0');
function respond($v,int $status=200):void {http_response_code($status);header('Content-Type: application/json; charset=utf-8');header('Cache-Control: private, no-store');echo json_encode($v,JSON_UNESCAPED_UNICODE|JSON_HEX_TAG);exit;}
function state(callable $fn){$f=fopen(STORE.'state.json','c+');if(!$f||!flock($f,LOCK_EX))throw new Exception('存储不可用');try{$raw=stream_get_contents($f);$s=$raw?json_decode($raw,true,512,JSON_THROW_ON_ERROR):['accounts'=>[],'posts'=>[],'rate'=>[]];$result=$fn($s);rewind($f);ftruncate($f,0);fwrite($f,json_encode($s,JSON_UNESCAPED_UNICODE));fflush($f);return $result;}finally{flock($f,LOCK_UN);fclose($f);}}
function origin():void{$expected='https://'.($_SERVER['HTTP_HOST']??'');if(($_SERVER['HTTP_ORIGIN']??'')!==$expected)respond(['error'=>'请求来源不正确'],403);}
function admin(array $u):void{if(empty($u['admin']))respond(['error'=>'仅管理员可操作'],403);}
function rate(array &$s,string $key,int $limit,int $seconds):bool{$now=time();$v=$s['rate'][$key]??['start'=>$now,'count'=>0];if($now-$v['start']>$seconds)$v=['start'=>$now,'count'=>0];$v['count']++;$s['rate'][$key]=$v;return $v['count']<=$limit;}
function phone($v):string{$p=trim((string)$v);if(!preg_match('/^1[3-9]\d{9}$/',$p))respond(['error'=>'请输入有效手机号'],400);return $p;}
session_name('fj_hr_session');session_save_path(STORE.'sessions');session_set_cookie_params(['lifetime'=>28800,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Strict']);ini_set('session.use_strict_mode','1');session_start();
$path=parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);$method=$_SERVER['REQUEST_METHOD'];
try{
 $body=[];if($method==='POST'){origin();$raw=file_get_contents('php://input');if(strlen($raw)>10000)respond(['error'=>'内容过长'],413);$body=json_decode($raw,true,32,JSON_THROW_ON_ERROR);}
 if($path==='/api/auth/login'){
  if($method!=='POST')respond(['error'=>'不支持的请求'],405);$p=phone($body['phone']??'');$password=(string)($body['password']??'');
  $result=state(function(&$s)use($p,$password){$key=hash('sha256',$p.'|'.($_SERVER['REMOTE_ADDR']??''));if(!rate($s,$key,5,900))return ['status'=>429];$u=$s['accounts'][$p]??null;if(!$u||empty($u['enabled'])||!password_verify($password,$u['hash']))return ['status'=>401];return ['status'=>200,'u'=>$u];});
  if($result['status']!==200)respond(['error'=>$result['status']===429?'尝试过于频繁，请15分钟后重试':'手机号或密码不正确，或账号停用'],$result['status']);session_regenerate_id(true);$_SESSION=['phone'=>$p,'version'=>$result['u']['version'],'expires'=>time()+28800];respond(['ok'=>true]);
 }
 if($path==='/api/auth/logout'){if($method!=='POST')respond(['error'=>'不支持的请求'],405);$_SESSION=[];session_destroy();setcookie(session_name(),'', ['expires'=>1,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Strict']);respond(['ok'=>true]);}
 $u=state(function(&$s){$p=$_SESSION['phone']??'';$u=$s['accounts'][$p]??null;return $u&&!empty($u['enabled'])&&$u['version']===($_SESSION['version']??-1)&&($_SESSION['expires']??0)>time()?$u+['phone'=>$p]:null;});
 if(!$u){if(str_starts_with($path,'/api/'))respond(['error'=>'请先登录'],401);header('Location: /login.html',true,303);exit;}
 if($path==='/admin'||$path==='/admin.html'){admin($u);header('Content-Type: text/html; charset=utf-8');readfile(STORE.'admin.html');exit;}
 if($path==='/api/admin/members'){
  admin($u);if($method==='GET')respond(state(function(&$s){$out=[];foreach($s['accounts'] as $p=>$v)if(empty($v['admin']))$out[]=['phone'=>(string)$p,'name'=>$v['name'],'enabled'=>$v['enabled'],'updated_at'=>$v['updatedAt'],'hr'=>$v['hr']??false];return ['members'=>$out];}));
  if($method!=='POST')respond(['error'=>'不支持的请求'],405);$p=phone($body['phone']??'');$name=trim((string)($body['name']??''));if(mb_strlen($name)>40||!is_bool($body['enabled']??null))respond(['error'=>'备注或状态不正确'],400);
  $result=state(function(&$s)use($p,$name,$body){$old=$s['accounts'][$p]??null;if(!empty($old['admin']))return ['error'=>'不能通过此入口更改管理员'];$pw=(string)($body['password']??'');if(!$old&&!$pw)return ['error'=>'新账号需要密码'];if($pw&&(strlen($pw)<12||strlen($pw)>128))return ['error'=>'密码需要12至128个字符'];$s['accounts'][$p]=['name'=>$name,'enabled'=>$body['enabled'],'hash'=>$pw?password_hash($pw,PASSWORD_DEFAULT):$old['hash'],'version'=>($old['version']??0)+1,'hr'=>$old['hr']??false,'updatedAt'=>(int)(microtime(true)*1000)];return ['saved'=>true];});respond($result,isset($result['error'])?400:200);
 }
 if($path==='/api/community'){
  if($method==='GET')respond(state(function(&$s)use($u){$posts=array_values(array_filter($s['posts'],fn($p)=>empty($p['deleted'])));usort($posts,fn($a,$b)=>$b['createdAt']<=>$a['createdAt']);$offset=max(0,(int)($_GET['cursor']??0));$page=array_slice($posts,$offset,60);return ['posts'=>$page,'cursor'=>count($posts)>$offset+60?(string)($offset+60):null,'canReply'=>!empty($u['admin'])||!empty($u['hr']),'canModerate'=>!empty($u['admin'])];}));
  if($method!=='POST')respond(['error'=>'不支持的请求'],405);$result=state(function(&$s)use($body,$u){$action=$body['action']??'';if($action==='hr'){if(empty($u['admin']))return ['error'=>'仅管理员可授权'];$p=(string)($body['phone']??'');if(!isset($s['accounts'][$p])||!is_bool($body['enabled']??null))return ['error'=>'账号不正确'];$s['accounts'][$p]['hr']=$body['enabled'];return ['ok'=>true];}
   if($action==='delete'){if(empty($u['admin']))return ['error'=>'仅管理员可隐藏评论'];$id=(string)($body['id']??'');if(!isset($s['posts'][$id]))return ['error'=>'评论不存在'];$s['posts'][$id]['deleted']=true;return ['ok'=>true];}
   $text=trim((string)($body['text']??''));$cat=$body['category']??'';$parent=(string)($body['parent']??'');if(mb_strlen($text)<5||mb_strlen($text)>2000||!in_array($cat,['意见反馈','用工咨询'],true))return ['error'=>'请填写5至2000字并选择分类'];if($parent&& (empty($u['admin'])&&empty($u['hr'])))return ['error'=>'仅授权HR可回复'];if($parent&&(!isset($s['posts'][$parent])||!empty($s['posts'][$parent]['deleted'])))return ['error'=>'问题已移除'];if(!rate($s,'comment-'.$u['phone'],6,300))return ['error'=>'发布较频繁，请稍后再试'];$id=bin2hex(random_bytes(16));$s['posts'][$id]=['id'=>$id,'text'=>$text,'parent'=>$parent,'category'=>$cat,'name'=>$u['name']?:'用户','badge'=>!empty($u['admin'])?'管理员':(!empty($u['hr'])?'HR':'用户'),'createdAt'=>(int)(microtime(true)*1000)];return ['ok'=>true,'id'=>$id];});respond($result,isset($result['error'])?400:200);
 }
 if($path==='/api/data'){header('Content-Type: application/javascript; charset=utf-8');header('Cache-Control: private, no-store');echo 'window.POLICY='.json_encode(json_decode(file_get_contents(STORE.'catalog.json'),true,512,JSON_THROW_ON_ERROR),JSON_HEX_TAG|JSON_UNESCAPED_UNICODE).';';exit;}
 if($path==='/api/status'){respond(['deployment'=>'standalone-php','syncStatus'=>json_decode(file_get_contents(STORE.'catalog.json'),true)['syncStatus']??null]);}
 $assets=json_decode(file_get_contents(STORE.'assets.json'),true,512,JSON_THROW_ON_ERROR);$key=$path==='/'?'/index.html':$path;$asset=$assets[$key]??$assets[$key.'.html']??null;if(!$asset)respond(['error'=>'页面不存在'],404);$owner=!empty($u['admin'])?'<a class="utility-item utility-admin" href="/admin.html"><span class="utility-icon">⚙</span><span>账号管理</span><small>管理授权用户</small></a>':'';header('Content-Type: '.$asset['type']);header('Cache-Control: private, no-store');header('X-Robots-Tag: noindex, noarchive');header('X-Content-Type-Options: nosniff');echo str_replace('__OWNER_ADMIN__',$owner,$asset['body']);
}catch(Throwable $e){error_log('HR standalone: '.$e->getMessage());respond(['error'=>'服务暂时不可用，请联系管理员'],503);}

