<?php
ob_start();
require_once dirname(__DIR__, 2) . '/db_bootstrap.php';
require_once dirname(__DIR__, 2) . '/install_link_lib.php';
require_once dirname(__DIR__, 2) . '/agent_service.php';
if (ob_get_length()) ob_clean();
header('Content-Type: application/json; charset=utf-8');
$conn = ensure_db(true);mysqli_report(MYSQLI_REPORT_OFF);ua_link_ensure_schema($conn);ua_agent_schema_migrate($conn);
function mobile_api_reply(int $status,array $data): void {http_response_code($status);echo json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);exit;}
function mobile_api_header(string $name): string {$key='HTTP_'.strtoupper(str_replace('-','_',$name));return trim((string)($_SERVER[$key]??''));}
function mobile_api_authenticate(mysqli $conn,?string $requiredType=null): array {
  if(strtoupper((string)($_SERVER['REQUEST_METHOD']??''))!=='POST')mobile_api_reply(405,['ok'=>false,'error'=>'METHOD_NOT_ALLOWED','message'=>'طريقة الطلب غير مسموحة.']);
  $raw=(string)file_get_contents('php://input');$instanceId=preg_replace('/[^a-zA-Z0-9_-]/','',mobile_api_header('X-UA-Instance'))??'';$timestamp=(int)mobile_api_header('X-UA-Timestamp');$nonce=substr(mobile_api_header('X-UA-Nonce'),0,120);$signature=strtolower(mobile_api_header('X-UA-Signature'));
  if($instanceId===''||$timestamp<=0||$nonce===''||!preg_match('/^[a-f0-9]{64}$/',$signature))mobile_api_reply(401,['ok'=>false,'error'=>'INVALID_AUTH_HEADERS','message'=>'بيانات مصادقة الجهاز غير مكتملة.']);
  if(abs(time()-$timestamp)>300)mobile_api_reply(401,['ok'=>false,'error'=>'STALE_REQUEST','message'=>'انتهت صلاحية الطلب. تحقق من وقت الهاتف.']);
  $instanceEsc=$conn->real_escape_string($instanceId);$rs=@$conn->query("SELECT * FROM ua_link_requests WHERE instance_id='{$instanceEsc}' AND status='approved' AND install_type IN ('agent','branch') LIMIT 1");
  if(!$rs||!$rs->num_rows)mobile_api_reply(403,['ok'=>false,'error'=>'INSTANCE_NOT_APPROVED','message'=>'هذا الجهاز غير معتمد أو تم إيقاف ربطه.']);$link=$rs->fetch_assoc();$installType=strtolower((string)($link['install_type']??''));
  if($requiredType!==null&&$installType!==$requiredType)mobile_api_reply(403,['ok'=>false,'error'=>'ROLE_NOT_ALLOWED','message'=>'هذه العملية غير متاحة لنوع النسخة الحالي.']);
  $key=strtolower(trim((string)($link['request_secret_hash']??'')));$expected=hash_hmac('sha256',$timestamp.'.'.$nonce.'.'.$raw,$key);if($key===''||!hash_equals($expected,$signature))mobile_api_reply(401,['ok'=>false,'error'=>'INVALID_SIGNATURE','message'=>'تعذر التحقق من توقيع الجهاز.']);
  $stmt=$conn->prepare('INSERT INTO agent_sync_nonces (instance_id,nonce,request_timestamp) VALUES (?,?,?)');if(!$stmt)mobile_api_reply(500,['ok'=>false,'error'=>'NONCE_STORE_FAILED','message'=>'تعذر حفظ رمز أمان الطلب.']);$stmt->bind_param('ssi',$instanceId,$nonce,$timestamp);try{$stored=$stmt->execute();}catch(Throwable $e){$stored=false;}$stmt->close();if(!$stored)mobile_api_reply(409,['ok'=>false,'error'=>'REPLAYED_REQUEST','message'=>'تم رفض طلب مكرر.']);
  @$conn->query("DELETE FROM agent_sync_nonces WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 DAY)");@$conn->query("UPDATE ua_link_requests SET last_seen_at=NOW(),updated_at=NOW() WHERE instance_id='{$instanceEsc}'");$agent=null;
  if($installType==='agent'){$agentRs=@$conn->query("SELECT * FROM agents WHERE linked_instance_id='{$instanceEsc}' AND is_active=1 AND portal_enabled=1 AND archived_at IS NULL LIMIT 1");if(!$agentRs||!$agentRs->num_rows)mobile_api_reply(409,['ok'=>false,'error'=>'INSTANCE_NOT_LINKED_TO_AGENT','message'=>'الجهاز معتمد، لكنه لم يُربط بحساب معتمد فعال بعد.']);$agent=$agentRs->fetch_assoc();}
  $payload=json_decode($raw,true);if(!is_array($payload))$payload=[];return ['raw'=>$raw,'payload'=>$payload,'instance_id'=>$instanceId,'install_type'=>$installType,'link'=>$link,'agent'=>$agent];
}
function mobile_api_money($value): float {return round((float)$value,2);}
function mobile_api_paid(array $invoice): bool {$payment=strtolower(trim((string)($invoice['payment_status']??'')));$status=strtolower(trim((string)($invoice['status']??'')));return in_array($payment,['paid','settled'],true)||in_array($status,['paid','مدفوع'],true);}

