<?php
require_once __DIR__.'/../app/bootstrap.php';
use App\Core\Auth;use App\Core\Database;use App\Core\Response;use App\Core\Security;
Auth::requireLogin('public/login.php');if($_SERVER['REQUEST_METHOD']!=='POST'||!verify_csrf())Response::json(['ok'=>false,'message'=>'Invalid request.'],419);$d=request_data();$purpose=preg_replace('/[^a-z0-9_-]/i','',(string)($d['purpose']??'security'))?:'security';
if(!Security::rateLimit('otp:'.Auth::id(),5,3600))Response::json(['ok'=>false,'message'=>'Too many OTP requests.'],429);$otp=Security::otp();Database::safeExecute('DELETE FROM otp_verifications WHERE user_id=? AND purpose=? AND verified_at IS NULL',[Auth::id(),$purpose]);Database::execute('INSERT INTO otp_verifications (user_id,purpose,otp_code,expires_at,created_at) VALUES (?,?,?,?,NOW())',[Auth::id(),$purpose,password_hash($otp,PASSWORD_DEFAULT),date('Y-m-d H:i:s',time()+600)]);$u=Auth::user();if(!empty($u['email']))@mail($u['email'],APP_NAME.' verification code','Your verification code is '.$otp.'. It expires in 10 minutes.');$res=['ok'=>true,'message'=>'OTP generated and sent to your registered contact.'];if(APP_ENV!=='production')$res['debug_otp']=$otp;Response::json($res);
