<?php
/** VPN server callback: register first successful connection. POST username=openz313 */
require_once 'config.php';
$input=json_decode(file_get_contents('php://input'), true) ?: $_POST;
$username=trim($input['username'] ?? $input['user'] ?? '');
$secret=trim($input['secret'] ?? '');
$expected=getSetting('vpn_callback_secret','');
if($expected && !hash_equals($expected,$secret)){ http_response_code(403); echo json_encode(['ok'=>false,'error'=>'forbidden'], JSON_UNESCAPED_UNICODE); exit; }
if(!$username){ echo json_encode(['ok'=>false,'error'=>'username required'], JSON_UNESCAPED_UNICODE); exit; }
$st=$pdo->prepare("SELECT c.*, pc.months FROM credentials c LEFT JOIN plan_categories pc ON pc.id=c.category_id OR pc.code=c.duration WHERE c.email=? LIMIT 1"); $st->execute([$username]); $c=$st->fetch();
if(!$c){ echo json_encode(['ok'=>false,'error'=>'account not found'], JSON_UNESCAPED_UNICODE); exit; }
$months=(int)($c['months'] ?: (preg_match('/^(\d+)M$/',$c['duration'],$m)?$m[1]:1));
$pdo->beginTransaction();
try{
  $st=$pdo->prepare("INSERT INTO vpn_connections(credential_id,user_id,username,source_ip,raw_payload) VALUES(?,?,?,?,?)"); $st->execute([$c['id'],$c['assigned_user_id'],$username,$_SERVER['REMOTE_ADDR']??null,json_encode($input, JSON_UNESCAPED_UNICODE)]);
  if(empty($c['first_connected_at'])){
    $st=$pdo->prepare("UPDATE credentials SET first_connected_at=NOW(), expires_at=DATE_ADD(NOW(), INTERVAL ? MONTH) WHERE id=? AND first_connected_at IS NULL"); $st->execute([$months,$c['id']]);
    $st=$pdo->prepare("INSERT IGNORE INTO first_connections(credential_id,user_id,username,first_connected_at,expires_at) VALUES(?,?,?,NOW(),DATE_ADD(NOW(), INTERVAL ? MONTH))"); $st->execute([$c['id'],$c['assigned_user_id'],$username,$months]);
  }
  $pdo->commit(); echo json_encode(['ok'=>true], JSON_UNESCAPED_UNICODE);
}catch(Throwable $e){$pdo->rollBack(); echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE);} 
