<?php
@ini_set('display_errors', '0');
@ini_set('log_errors', '0');
error_reporting(0);
if (!ob_get_level()) { @ob_start(); }

register_shutdown_function(function(){
  $err = error_get_last();
  if ($err && !headers_sent()) {
    while (ob_get_level()) { @ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(500);
    echo json_encode(['ok'=>false,'message'=>'خطأ داخلي: '.$err['message']], JSON_UNESCAPED_UNICODE);
  }
});

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/api_common.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../mikrotik_lib.php';
require_once __DIR__ . '/../subscriber_history_lib.php';
require_once __DIR__ . '/../subscriber_pppoe_action_lib.php';
require_once __DIR__ . '/../subscribers_bulk_action_lib.php';

if (!function_exists('out')) {
  function out($arr, int $code=200){
    api_json_out_clean($arr, $code, JSON_UNESCAPED_UNICODE);
  }
}

require_login();
$conn = ensure_db(true);
if (!($conn instanceof mysqli)) out(['ok'=>false,'message'=>'Database connection error'], 500);
if(function_exists('require_perm')) @require_perm('can_pppoe_cut_restore');

$sub_id = (int)($_POST['subscriber_id'] ?? 0);
$pass   = (string)($_POST['super_password'] ?? '');
if($sub_id<=0) out(['ok'=>false,'message'=>'subscriber_id مطلوب'], 400);
if (!isset($_SESSION['super_admin_fail_count']) || !is_numeric($_SESSION['super_admin_fail_count'])) { $_SESSION['super_admin_fail_count'] = 0; }
if(!ua_pppoe_action_verify_super($conn, $pass)) {
  $_SESSION['super_admin_fail_count'] = (int)($_SESSION['super_admin_fail_count'] ?? 0) + 1;
  if ((int)$_SESSION['super_admin_fail_count'] >= 3) {
    $_SESSION['super_admin_fail_count'] = 0;
    auth_force_logout_response(true, 'login.php');
  }
  $remaining = 3 - (int)$_SESSION['super_admin_fail_count'];
  out(['ok'=>false,'message'=>'كلمة مرور السوبر أدمن غير صحيحة. المحاولات المتبقية: '.$remaining], 403);
}
$_SESSION['super_admin_fail_count'] = 0;

ua_pppoe_action_ensure_disable_columns($conn);

try {
  $result = bulk_execute_actions($conn, 'restore', [$sub_id], [
    'source' => 'api_single',
    'router_context' => 'استعادة مشترك يدوي',
    'max_ids' => 1,
    'max_errors' => 1,
    'refresh_cache' => true,
    'message_prefix' => 'تم تنفيذ ',
  ]);
  if ((int)($result['changed'] ?? 0) > 0 && (int)($result['failed'] ?? 0) === 0) {
    out(['ok'=>true,'message'=>'تمت الاستعادة بنجاح.']);
  }
  out(['ok'=>false,'message'=>(string)($result['message'] ?? 'فشلت الاستعادة.')], 500);
} catch (InvalidArgumentException $e) {
  out(['ok'=>false,'message'=>$e->getMessage()], 400);
} catch (Throwable $e) {
  out(['ok'=>false,'message'=>$e->getMessage()], 500);
}
