<?php
if (!defined('ALLOW_MANUAL_PPP_CUT_EXECUTION')) define('ALLOW_MANUAL_PPP_CUT_EXECUTION', true);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/subscribers_lib.php';
require_once __DIR__ . '/subscriber_history_lib.php';
require_once __DIR__ . '/ppp_speed_map.php';
require_once __DIR__ . '/subscriber_plan_schema.php';
require_once __DIR__ . '/subscriber_reference_data_lib.php';
require_once __DIR__ . '/subscriber_upload_lib.php';
require_once __DIR__ . '/finance_payment_lib.php';
require_once __DIR__ . '/agent_service.php';
require_once __DIR__ . '/subscriber_id_sequence_lib.php';

require_login('index.php?login=1');
if (function_exists('require_perm')) require_perm('can_add_subscriber');
if (function_exists('ensure_db')) ensure_db(true);

$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) die('DB connection failed');
mysqli_report(MYSQLI_REPORT_OFF);
@set_time_limit(45);

$page_title = 'إضافة مشترك';
if (!defined('UA_EMBED')) define('UA_EMBED', isset($_GET['embed']) && $_GET['embed'] == '1');
$msg = '';
$err = '';
$warn = '';
$createdSubscriberId = 0;
$pppoeAccountSuffix = subs_policy_pppoe_domain($conn);

// ---- Schema safety ----
// Stage 13: schema preparation is centralized in subscriber_plan_schema.php.
if (function_exists('subscriber_plan_ensure_schema')) { @subscriber_plan_ensure_schema($conn); }
if (function_exists('subs_ensure_pppoe_cols')) { @subs_ensure_pppoe_cols($conn); }

function sa_old(string $key, $default = ''): string {
  return htmlspecialchars((string)($_POST[$key] ?? $default), ENT_QUOTES, 'UTF-8');
}

function sa_digits(string $v): string {
  return function_exists('subs_policy_digits') ? subs_policy_digits($v) : (preg_replace('/\D+/', '', $v) ?? '');
}

function sa_ar_to_en_word(string $text): string {
  if (function_exists('subs_policy_ar_to_en_word')) return subs_policy_ar_to_en_word($text);
  $text = trim((string)$text);
  if ($text === '') return '';
  $text = strtolower(preg_replace('/[^a-z0-9\s]+/i', ' ', $text) ?? '');
  return trim(preg_replace('/\s+/', ' ', $text) ?? '');
}

function sa_slug_local(string $firstName, string $lastName): string {
  $slug = function_exists('subs_policy_slug_local')
    ? subs_policy_slug_local($firstName, $lastName)
    : strtolower(trim(preg_replace('/[^a-z0-9]+/i', '.', trim($firstName.'.'.$lastName)) ?? '', '.'));
  return $slug !== '' ? $slug : 'subscriber';
}

function sa_unique_pppoe(mysqli $conn, string $local, string $domain=''): string {
  if ($domain === '') $domain = subs_policy_pppoe_domain($conn);
  return subs_policy_unique_pppoe($conn, $local, $domain, 0, '');
}

function sa_password_preview(string $motherName, string $phone): string {
  return function_exists('subs_policy_password') ? subs_policy_password($motherName, $phone) : ('X' . substr(str_pad(sa_digits($phone), 5, '0', STR_PAD_LEFT), -5));
}

function sa_handle_upload(string $key, string $prefix): ?string {
  return function_exists('subscriber_identity_upload') ? subscriber_identity_upload($key, $prefix) : null;
}

function sa_invoice_insert(mysqli $conn, int $subscriberId, float $amount, bool $isPaid, string $note='', int $agentId=0): int {
  $status = $isPaid ? 'مدفوع' : 'غير مدفوع';
  $paymentStatus = $isPaid ? 'paid' : 'unpaid';
  $paidAmount = $isPaid ? $amount : 0.00;
  $remaining = $isPaid ? 0.00 : $amount;
  $paidAt = $isPaid ? date('Y-m-d H:i:s') : null;
  $cycle = date('Y-m');
  $stmt = $conn->prepare("INSERT INTO invoices (subscriber_id, amount, status, cycle_month, invoice_type, notes, paid_at, created_at, paid_amount, remaining_amount, payment_status, paid_by_type, paid_by_id, updated_at) VALUES (?,?,?,?,?,?,?,NOW(),?,?,?,?,?,NOW())");
  if (!$stmt) return 0;
  $type = 'NEW_SUB';
  $paidByType = $isPaid ? ($agentId > 0 ? 'agent' : 'admin') : null;
  $paidById = $isPaid && $agentId > 0 ? $agentId : null;
  $stmt->bind_param('idsssssddssi', $subscriberId, $amount, $status, $cycle, $type, $note, $paidAt, $paidAmount, $remaining, $paymentStatus, $paidByType, $paidById);
  $ok = $stmt->execute();
  $id = $ok ? (int)$stmt->insert_id : 0;
  $stmt->close();
  return $id;
}

function sa_payment_insert(mysqli $conn, int $invoiceId, int $subscriberId, float $amount, string $note='', int $agentId=0): int {
  $by = (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin');
  $result = finance_record_payment_row(
    $conn, $invoiceId, $subscriberId, $amount, 'نقدي', $note, $by, date('Y-m-d H:i:s'),
    'NEW_SUB#' . $subscriberId, $agentId > 0 ? $agentId : null,
    [
      'idempotency_key'=>'NEW_SUB_PAYMENT:' . $subscriberId,
      'source_type'=>$agentId > 0 ? 'agent' : 'main',
      'source_ref'=>$agentId > 0 ? (string)$agentId : 'main',
      'source_name'=>$agentId > 0 ? ('معتمد #' . $agentId) : 'النسخة الرئيسية',
      'channel'=>'desktop',
    ]
  );
  if (!$result['ok']) throw new RuntimeException($result['error']);
  return (int)($result['id'] ?? 0);
}

function sa_build_breakdown(array $speedRow, array $packageRow): array {
  $speedPrice = (float)($speedRow['price'] ?? 0);
  $packagePrice = (float)($packageRow['price'] ?? 0);
  $subscriptionFee = (float)($packageRow['subscription_fee'] ?? 0);
  $total = $speedPrice + $packagePrice + $subscriptionFee;
  $parts = [];
  if (($speedRow['speed_name'] ?? '') !== '') $parts[] = 'السرعة: ' . $speedRow['speed_name'] . ' = ' . number_format($speedPrice, 2);
  if (($packageRow['package_name'] ?? '') !== '') $parts[] = 'الباقة: ' . $packageRow['package_name'] . ' = ' . number_format($packagePrice, 2);
  if ($subscriptionFee > 0) $parts[] = 'رسوم اشتراك لمرة واحدة = ' . number_format($subscriptionFee, 2);
  $parts[] = 'الإجمالي = ' . number_format($total, 2);
  return [$total, implode(' | ', $parts)];
}

function sa_fetch_speeds(mysqli $conn): array {
  return function_exists('subscriber_ref_fetch_speeds') ? subscriber_ref_fetch_speeds($conn) : [];
}

function sa_fetch_packages(mysqli $conn): array {
  return function_exists('subscriber_ref_fetch_packages') ? subscriber_ref_fetch_packages($conn) : [];
}

function sa_fetch_sectors(mysqli $conn): array {
  return function_exists('subscriber_ref_fetch_sectors') ? subscriber_ref_fetch_sectors($conn, true) : [];
}

$speeds = sa_fetch_speeds($conn);
$packages = sa_fetch_packages($conn);
$sectors = sa_fetch_sectors($conn);
$nationalityOptions = function_exists('subscriber_identity_nationalities') ? subscriber_identity_nationalities($conn) : ['سوري','فلسطيني سوري'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array(($_POST['action'] ?? ''), ['save_only', 'save_paid'], true)) {
  $action = (string)$_POST['action'];
  $isPaid = $action === 'save_paid';
  $sourceAgentId = max(0, (int)($_POST['agent_id'] ?? 0));

  $firstName = trim((string)($_POST['first_name'] ?? ''));
  $fatherName = trim((string)($_POST['father_name'] ?? ''));
  $lastName = trim((string)($_POST['last_name'] ?? ''));
  $motherName = trim((string)($_POST['mother_name'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $address = trim((string)($_POST['address_area'] ?? ''));
  $nationalId = trim((string)($_POST['national_id'] ?? ''));
  $recordNumber = trim((string)($_POST['record_number'] ?? ''));
  $documentTypeRaw = trim((string)($_POST['document_type'] ?? 'هوية شخصية'));
  $documentType = function_exists('subscriber_document_type_normalize')
    ? subscriber_document_type_normalize($documentTypeRaw)
    : ($documentTypeRaw ?: 'هوية شخصية');
  $nationality = trim((string)($_POST['nationality'] ?? 'سوري')) ?: 'سوري';
  $documentNumber = trim((string)($_POST['document_number'] ?? ''));
  $birthDate = trim((string)($_POST['birth_date'] ?? ''));
  $notes = trim((string)($_POST['notes'] ?? ''));
  $sectorId = (int)($_POST['sector_id'] ?? 0);
  $speedId = (int)($_POST['speed_id'] ?? 0);
  $packageId = (int)($_POST['package_id'] ?? 0);
  $staticIp = function_exists('subs_static_ip_normalize') ? subs_static_ip_normalize((string)($_POST['ip_address'] ?? '')) : trim((string)($_POST['ip_address'] ?? ''));

  if ($firstName === '' || $lastName === '' || $fatherName === '' || $motherName === '' || $phone === '') {
    $err = 'الاسم واسم الأب والكنية واسم الأم والهاتف مطلوبة.';
  }
  if (!$err && $speedId <= 0) $err = 'الرجاء اختيار السرعة.';
  if (!$err && $packageId <= 0) $err = 'الرجاء اختيار الباقة.';
  if (!$err && $sectorId <= 0) $err = 'الرجاء اختيار القطاع.';
  if (!$err && $documentType === '') $err = 'نوع الوثيقة غير صالح.';

  $speedRow = [];
  $packageRow = [];
  $sectorRow = [];

  if (!$err) {
    foreach ($speeds as $s) if ((int)$s['id'] === $speedId) { $speedRow = $s; break; }
    foreach ($packages as $p) if ((int)$p['id'] === $packageId) { $packageRow = $p; break; }
    foreach ($sectors as $s) if ((int)$s['id'] === $sectorId) { $sectorRow = $s; break; }
    if (empty($speedRow)) $err = 'السرعة المحددة غير موجودة.';
    if (!$err && empty($packageRow)) $err = 'الباقة المحددة غير موجودة.';
    if (!$err && empty($sectorRow)) $err = 'القطاع المحدد غير موجود.';
  }

  $fullName = trim($firstName . ' ' . $fatherName . ' ' . $lastName);
  $localPart = sa_slug_local($firstName, $lastName);
  $generatedPpp = !$err ? sa_unique_pppoe($conn, $localPart, $pppoeAccountSuffix) : '';
  $generatedPass = sa_password_preview($motherName, $phone);

  if (!$err) {
    $phoneDigits = sa_digits($phone);
    if (strlen($phoneDigits) < 5) $err = 'رقم الهاتف يجب أن يحتوي 5 أرقام على الأقل.';
  }

  if (!$err && $staticIp !== '') {
    $ipErr = function_exists('subs_static_ip_validate') ? subs_static_ip_validate($staticIp) : '';
    if ($ipErr !== '') $err = $ipErr;
  }
  if (!$err && $staticIp !== '' && function_exists('subs_static_ip_db_conflict')) {
    $dbConflict = subs_static_ip_db_conflict($conn, $staticIp, 0);
    if ($dbConflict) {
      $who = trim((string)($dbConflict['ppp_username'] ?? $dbConflict['username'] ?? ''));
      $err = 'هذا الـ IP مستخدم مسبقاً في قاعدة البيانات للمشترك #' . (int)($dbConflict['id'] ?? 0) . ($who !== '' ? ' / ' . $who : '') . '.';
    }
  }

  if (!$err) {
    try {
      mt_require_router_online_or_throw($conn, 'إضافة مشترك');
    } catch (Throwable $e) {
      $err = $e->getMessage();
    }
  }

  if (!$err) {
    $pppUsername = $generatedPpp;
    $username = $generatedPpp;
    $pppPassword = $generatedPass;
    $speedName = trim((string)($speedRow['speed_name'] ?? ''));
    $packageName = trim((string)($packageRow['package_name'] ?? ''));
    $status = $isPaid ? 'نشط' : 'متوقف';
    $mtDisabled = $isPaid ? 0 : 1;
    $vlanId = (int)($sectorRow['vlan_id'] ?? 0);
    $quotaGb = isset($packageRow['quota_gb']) && $packageRow['quota_gb'] !== null && $packageRow['quota_gb'] !== '' ? (int)$packageRow['quota_gb'] : null;
    if ($quotaGb === null && preg_match('/(\d+)\s*G/i', $packageName, $m)) $quotaGb = (int)$m[1];
    $mtProfile = trim((string)($speedRow['mikrotik_profile'] ?? ''));
    if ($mtProfile === '') $mtProfile = trim((string)($packageRow['mikrotik_profile'] ?? ''));
    if ($mtProfile === '') $mtProfile = trim((string)($sectorRow['pppoe_profile'] ?? ''));
    if ($mtProfile === '') $mtProfile = ppp_profile_from_speed($speedName, $packageName, 'pppoe-prof');
    $rateLimit = trim((string)($speedRow['rate_limit'] ?? ''));
    if ($rateLimit === '' && $speedName !== '') $rateLimit = $speedName . '/' . $speedName;

    if ($staticIp !== '' && !$err && function_exists('mt_ppp_static_ip_preflight')) {
      $mtIpCheck = mt_ppp_static_ip_preflight($conn, $staticIp, $pppUsername);
      if (empty($mtIpCheck['ok'])) {
        $err = (string)($mtIpCheck['message'] ?? 'تعذر فحص تكرار الـ IP على MikroTik.');
      } elseif (!empty($mtIpCheck['pool_hits'])) {
        $poolNames = [];
        foreach ((array)$mtIpCheck['pool_hits'] as $hit) {
          $poolNames[] = trim((string)($hit['name'] ?? 'pool'));
        }
        $poolNames = array_values(array_unique(array_filter($poolNames)));
        $warn = 'تنبيه: الـ IP المختار موجود ضمن Pool على MikroTik (' . implode('، ', $poolNames) . '). تم السماح به لأنه غير مستخدم، لكن الأفضل تخصيص رينج ثابت خارج الـ pool الديناميكي.';
      }
    }

    $passwordPlain = $pppPassword;
    [$invoiceAmount, $invoiceBreakdown] = sa_build_breakdown($speedRow, $packageRow);

    // duplicate checks
    $checks = [];
    $checks[] = ["ppp_username", $pppUsername, 'اسم حساب PPPoE موجود مسبقًا.'];
    $checks[] = ["username", $username, 'اسم المستخدم موجود مسبقًا.'];
    if ($phone !== '') $checks[] = ["phone", $phone, 'رقم الهاتف مستخدم مسبقًا.'];
    if ($nationalId !== '') $checks[] = ["national_id", $nationalId, 'الرقم الوطني مستخدم مسبقًا.'];

    foreach ($checks as $ck) {
      [$col, $value, $msgCheck] = $ck;
      if (!col_exists($conn, 'subscribers', $col)) continue;
      $vEsc = $conn->real_escape_string($value);
      $q = $conn->query("SELECT id FROM subscribers WHERE $col='$vEsc' AND is_deleted=0 LIMIT 1");
      if ($q && $q->num_rows > 0) { $err = $msgCheck; break; }
    }

    if (!$err) {
      $frontPath = sa_handle_upload('id_card_front', 'front');
      $backPath  = sa_handle_upload('id_card_back', 'back');
      $pdfPath   = sa_handle_upload('id_card_pdf', 'pdf');
      if ($frontPath === null && $backPath === null && $pdfPath === null) {
        // allow save without files
      }

      try {
        $conn->begin_transaction();

        $cols = [
          'username','password_plain','full_name','father_name','mother_name','birth_date','phone',
          'speed','package','status','notes','speed_state','base_speed','current_speed',
          'package_name','speed_name','address_area','national_id','is_deleted','ppp_username',
          'ppp_password','ppp_profile','ppp_rate_limit','quota_gb','used_gb','sector_id','vlan_id',
          'provision_status','mt_disabled','pppoe_profile'
        ];
        $vals = [
          $username,$passwordPlain,$fullName,$fatherName,$motherName,($birthDate!==''?$birthDate:null),$phone,
          $speedName,$packageName,$status,$notes,'ORIGINAL',$speedName,$speedName,
          $packageName,$speedName,$address,$nationalId,0,$pppUsername,
          $pppPassword,$mtProfile,$rateLimit,$quotaGb,0,$sectorId,$vlanId,
          ($isPaid ? 'active' : 'pending_payment'),$mtDisabled,$mtProfile
        ];
        $types = 'ssssssssssssssssssisssssiiisis';

        if (col_exists($conn,'subscribers','first_name')) { $cols[]='first_name'; $vals[]=$firstName; $types.='s'; }
        if (col_exists($conn,'subscribers','last_name')) { $cols[]='last_name'; $vals[]=$lastName; $types.='s'; }
        if (col_exists($conn,'subscribers','record_number')) { $cols[]='record_number'; $vals[]=$recordNumber; $types.='s'; }
        if (col_exists($conn,'subscribers','document_type')) { $cols[]='document_type'; $vals[]=$documentType; $types.='s'; }
        if (col_exists($conn,'subscribers','nationality')) { $cols[]='nationality'; $vals[]=$nationality; $types.='s'; }
        if (col_exists($conn,'subscribers','document_number')) { $cols[]='document_number'; $vals[]=$documentNumber; $types.='s'; }
        if (col_exists($conn,'subscribers','id_card_front')) { $cols[]='id_card_front'; $vals[]=$frontPath; $types.='s'; }
        if (col_exists($conn,'subscribers','id_card_back')) { $cols[]='id_card_back'; $vals[]=$backPath; $types.='s'; }
        if (col_exists($conn,'subscribers','id_front')) { $cols[]='id_front'; $vals[]=$frontPath; $types.='s'; }
        if (col_exists($conn,'subscribers','id_back')) { $cols[]='id_back'; $vals[]=$backPath; $types.='s'; }
        if (col_exists($conn,'subscribers','id_pdf')) { $cols[]='id_pdf'; $vals[]=$pdfPath; $types.='s'; }
        if (col_exists($conn,'subscribers','provisioned_at')) { $cols[]='provisioned_at'; $vals[] = date('Y-m-d H:i:s'); $types.='s'; }
        if (col_exists($conn,'subscribers','ip_address')) { $cols[]='ip_address'; $vals[]=$staticIp; $types.='s'; }
        if (col_exists($conn,'subscribers','created_by_type')) { $cols[]='created_by_type'; $vals[]=$sourceAgentId > 0 ? 'agent' : 'admin'; $types.='s'; }
        if (col_exists($conn,'subscribers','created_by_id')) { $cols[]='created_by_id'; $vals[]=$sourceAgentId > 0 ? $sourceAgentId : null; $types.='i'; }

        ua_subscriber_ensure_id_sequence($conn);
        $placeholders = implode(',', array_fill(0, count($cols), '?'));
        $sql = "INSERT INTO subscribers (`".implode('`,`',$cols)."`) VALUES ($placeholders)";
        $stmt = $conn->prepare($sql);
        if (!$stmt) throw new RuntimeException('فشل تجهيز حفظ المشترك: ' . $conn->error);
        $bind = [$types];
        foreach ($vals as $k => $v) $bind[] = &$vals[$k];
        call_user_func_array([$stmt, 'bind_param'], $bind);
        if (!$stmt->execute()) throw new RuntimeException('فشل حفظ المشترك: ' . $stmt->error);
        $subscriberId = (int)$stmt->insert_id;
        $stmt->close();
        if (function_exists('sh_mark_registered')) { sh_mark_registered($conn, $subscriberId); }

        $serial = 'ISP-12200-SUB-' . $subscriberId;
        $serialEsc = $conn->real_escape_string($serial);
        @ $conn->query("UPDATE subscribers SET mikrotik_serial='$serialEsc' WHERE id=$subscriberId LIMIT 1");

        $invoiceId = sa_invoice_insert($conn, $subscriberId, $invoiceAmount, $isPaid, $invoiceBreakdown, $sourceAgentId);
        if ($invoiceId <= 0) throw new RuntimeException('فشل إنشاء الفاتورة الأولية.');
        if ($isPaid) sa_payment_insert($conn, $invoiceId, $subscriberId, $invoiceAmount, 'تسديد مباشر أثناء إضافة المشترك', $sourceAgentId);
        if ($sourceAgentId > 0) {
          $charge = ua_agent_service_charge_subscriber($conn, $sourceAgentId, $subscriberId, $invoiceId, $invoiceAmount, [
            'type'=>'agent',
            'id'=>$sourceAgentId,
            'manage_transaction'=>false,
          ]);
          if (!$charge['ok']) throw new RuntimeException($charge['error']);
          ua_agent_activity_add($conn, [
            'agent_id'=>$sourceAgentId,
            'event_type'=>'SUBSCRIBER_CREATED',
            'direction'=>'TO_MAIN',
            'entity_type'=>'subscriber',
            'entity_id'=>(string)$subscriberId,
            'summary'=>'تم تسجيل مشترك جديد وترحيل رسومه إلى رصيد المعتمد.',
            'payload'=>['invoice_id'=>$invoiceId,'amount'=>$invoiceAmount],
            'actor_type'=>'agent',
            'actor_id'=>$sourceAgentId,
          ]);
        }

        $conn->commit();

        $mtOk = false;
        $mtError = '';
        if ($mtProfile !== '') {
          $mtOk = mt_ppp_profile_ensure($conn, $mtProfile, $rateLimit);
          if (!$mtOk) $mtError = (string)($GLOBALS['mt_last_error'] ?? 'فشل إنشاء/تحديث بروفايل PPP');
        } else {
          $mtOk = true;
        }
        if ($mtOk) {
          $mtOk = mt_ppp_secret_upsert($conn, $pppUsername, $pppPassword, $mtProfile, $staticIp, $serial, $rateLimit);
          if (!$mtOk) $mtError = (string)($GLOBALS['mt_last_error'] ?? 'فشل إنشاء/تحديث حساب PPPoE على MikroTik');
        }
        if ($mtOk) {
          @ mt_ppp_secret_set_disabled($conn, $pppUsername, !$isPaid);
          $now = $conn->real_escape_string(date('Y-m-d H:i:s'));
          @ $conn->query("UPDATE subscribers SET ppp_last_sync='$now', mt_last_sync='$now', mt_disabled=" . ($isPaid ? 0 : 1) . ", ppp_is_disabled=" . ($isPaid ? 0 : 1) . " WHERE id=$subscriberId LIMIT 1");
        } else {
          @ $conn->query("UPDATE subscribers SET mt_disabled=1, ppp_is_disabled=1 WHERE id=$subscriberId LIMIT 1");
        }

        $msg = $isPaid
          ? 'تم حفظ المشترك وتسديده محليًا ✅'
          : 'تم حفظ المشترك وإنشاء فاتورته محليًا ✅';
        if ($mtOk) {
          $msg .= ' وتمت مزامنته مع MikroTik.';
          if ($staticIp !== '') $msg .= ' وتم حجز IP ثابت: ' . $staticIp . '.';
        } else {
          $warn = 'تم الحفظ محليًا لكن فشلت مزامنة MikroTik: ' . $mtError;
        }
        $createdSubscriberId = $subscriberId;
        $_POST = [];
      } catch (Throwable $e) {
        if ($conn->errno || $conn->warning_count >= 0) {
          try { $conn->rollback(); } catch (Throwable $ignore) {}
        }
        $err = $e->getMessage();
      }
    }
  }
}

$speedMap = [];
foreach ($speeds as $s) { $speedMap[(int)$s['id']] = $s; }
$packageMap = [];
foreach ($packages as $p) { $packageMap[(int)$p['id']] = $p; }

$defaultSectorId = (int)($_POST['sector_id'] ?? 0);
if ($defaultSectorId <= 0 && !empty($sectors)) {
  $defaultSectorId = (int)($sectors[0]['id'] ?? 0);
}

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidAdd = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/subscriber_info_print_actions.css'];
if ($uaAndroidAdd) $UA_PAGE_CSS[] = 'assets/css/android_subscriber_add.css';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
?>
<div class="content-wrapper ua-manual-page ua-subscriber-child-page ua-sub-child-add sa-figma-page">
  <section class="content">
    <div class="ua-page-v2 sa-wrap">
      <?php if ($uaAndroidAdd): ?>
        <header class="asa-heading">
          <div>
            <span>حساب جديد</span>
            <h1>إضافة مشترك</h1>
            <p>أدخل البيانات الأساسية، ثم اختر الخدمة وراجع الملخص قبل الحفظ.</p>
          </div>
          <a href="subscribers.php" aria-label="العودة إلى قائمة المشتركين"><i class="fa fa-users"></i><b>القائمة</b></a>
        </header>
        <ol class="asa-steps" aria-label="مراحل إضافة المشترك">
          <li class="is-current"><i>1</i><span>البيانات</span></li>
          <li><i>2</i><span>الخدمة</span></li>
          <li><i>3</i><span>المراجعة</span></li>
        </ol>
      <?php endif; ?>
      <?php if($err): ?><div class="ua-alert alert-danger"><?= h($err) ?></div><?php endif; ?>
      <?php if($warn): ?><div class="ua-alert alert-warning"><?= h($warn) ?></div><?php endif; ?>
      <?php if($msg): ?><div class="ua-alert alert-success"><?= h($msg) ?></div><?php endif; ?>
      <?php if($createdSubscriberId > 0): ?>
        <section class="asa-router-next">
          <div><i class="fa fa-wifi"></i><span><b>الخطوة التالية المقترحة</b><small>أعدّ راوتر المشترك، ولّد شبكات Wi‑Fi وكلمات المرور واطبع QR.</small></span></div>
          <div class="sip-action-row">
            <a href="<?= $uaAndroidAdd ? 'android_router_setup.php?ua_android=1&amp;' : 'subscriber_router_setup.php?' ?>subscriber_id=<?= (int)$createdSubscriberId ?>"><i class="fa fa-wifi"></i><span>إعداد الراوتر</span></a>
            <a href="subscriber_info_print.php?subscriber_id=<?= (int)$createdSubscriberId ?>" data-subscriber-info-print data-subscriber-id="<?= (int)$createdSubscriberId ?>"><i class="fa fa-print"></i><span>طباعة معلومات المشترك</span></a>
          </div>
        </section>
      <?php endif; ?>
      <?php if(empty($speeds) || empty($packages) || empty($sectors)): ?>
        <div class="ua-alert alert-warning sa-empty">
          يلزم وجود سرعات وباقات وقطاعات مفعلة قبل إضافة مشترك. راجع الإعدادات أولًا.
        </div>
      <?php endif; ?>


      <form method="post" enctype="multipart/form-data" <?= $uaAndroidAdd ? 'data-ua-android-native-layout' : '' ?>>
        <div class="sa-grid">
          <div class="sa-input-zone">
          <div class="sa-card">
            <div class="sa-card-head">
              <h3>بيانات المشترك</h3>
            </div>
            <div class="sa-card-body">
              <div class="sa-form-grid sa-personal-grid">
                <div class="sa-field">
                  <label>الاسم</label>
                  <input name="first_name" class="form-control" value="<?= sa_old('first_name') ?>" required>
                </div>
                <div class="sa-field">
                  <label>اسم الأب</label>
                  <input name="father_name" class="form-control" value="<?= sa_old('father_name') ?>" required>
                </div>
                <div class="sa-field">
                  <label>الكنية</label>
                  <input name="last_name" class="form-control" value="<?= sa_old('last_name') ?>" required>
                </div>
                <div class="sa-field">
                  <label>اسم الأم</label>
                  <input name="mother_name" class="form-control" value="<?= sa_old('mother_name') ?>" required>
                </div>
                <div class="sa-field">
                  <label>تاريخ الميلاد</label>
                  <input type="date" name="birth_date" class="form-control" value="<?= sa_old('birth_date') ?>">
                </div>
                <div class="sa-field">
                  <label>نوع الوثيقة</label>
                  <?php $oldDocumentType=(string)($_POST['document_type']??'هوية شخصية'); ?>
                  <select name="document_type" class="form-select" required>
                    <?php foreach((function_exists('subscriber_document_types') ? subscriber_document_types() : ['هوية شخصية','إخراج قيد','جواز سفر']) as $type): ?><option value="<?= h($type) ?>" <?= $oldDocumentType===$type?'selected':'' ?>><?= h($type) ?></option><?php endforeach; ?>
                  </select>
                </div>
                <div class="sa-field">
                  <label>الجنسية</label>
                  <input name="nationality" class="form-control" list="subscriberNationalityOptions" value="<?= sa_old('nationality','سوري') ?>" required autocomplete="off">
                </div>
                <div class="sa-field">
                  <label>رقم الوثيقة</label>
                  <input name="document_number" class="form-control" value="<?= sa_old('document_number') ?>">
                </div>
                <div class="sa-field">
                  <label>رقم الهاتف</label>
                  <input name="phone" class="form-control" inputmode="tel" value="<?= sa_old('phone') ?>" required>
                </div>
                <div class="sa-field">
                  <label>القيد</label>
                  <input name="record_number" class="form-control" value="<?= sa_old('record_number') ?>">
                </div>
                <div class="sa-field sa-field-span-2">
                  <label>الرقم الوطني <button type="button" class="sa-help-tip" aria-label="تلميح" data-tip="يمكن إدخاله يدويا أو تمريره مباشرة من قارئ الباركود إذا كان يعمل كلوحة مفاتيح.">?</button></label>
                  <input name="national_id" class="form-control" inputmode="numeric" value="<?= sa_old('national_id') ?>">
                </div>
                <div class="sa-field sa-field-full">
                  <label>العنوان الحالي</label>
                  <input name="address_area" class="form-control" value="<?= sa_old('address_area') ?>">
                </div>
                <div class="sa-field sa-field-full">
                  <label>ملاحظات</label>
                  <textarea name="notes" class="form-control" rows="2" placeholder="اختياري"><?= sa_old('notes') ?></textarea>
                </div>
              </div>
              <datalist id="subscriberNationalityOptions"><?php foreach($nationalityOptions as $nationalityOption): ?><option value="<?= h($nationalityOption) ?>"><?php endforeach; ?></datalist>

            </div>
          </div>
          <div class="sa-card sa-service-card">
                <div class="sa-card-head">
                  <h3>الخدمة والفاتورة <button type="button" class="sa-help-tip sa-help-tip--section" aria-label="تلميح" data-tip="عند الضغط على حفظ فقط يتم إنشاء المشترك والفاتورة ويبقى المشترك موقوفا حتى التسديد. وعند الضغط على حفظ وتسديد يتم السداد والتفعيل مباشرة.">?</button></h3>
                </div>
                <div class="sa-card-body">
                  <input type="hidden" name="sector_id" value="<?= (int)$defaultSectorId ?>">
                  <div class="sa-form-grid sa-3 sa-service-line">
                    <div class="sa-field">
                      <label>السرعة</label>
                      <select name="speed_id" id="speed_id" class="form-select" required>
                        <option value="">— اختر السرعة —</option>
                        <?php foreach($speeds as $speed): ?>
                          <option value="<?= (int)$speed['id'] ?>" <?= ((int)($_POST['speed_id'] ?? 0)===(int)$speed['id'] ? 'selected' : '') ?>>
                            <?= h($speed['speed_name']) ?> — <?= number_format((float)($speed['price'] ?? 0), 2) ?>
                          </option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="sa-field">
                      <label>الباقة</label>
                      <select name="package_id" id="package_id" class="form-select" required>
                        <option value="">— اختر الباقة —</option>
                        <?php foreach($packages as $package): ?>
                          <option value="<?= (int)$package['id'] ?>" <?= ((int)($_POST['package_id'] ?? 0)===(int)$package['id'] ? 'selected' : '') ?>>
                            <?= h($package['package_name']) ?>
                            <?php if($package['quota_gb'] !== null && $package['quota_gb'] !== ''): ?> — <?= (int)$package['quota_gb'] ?>GB<?php endif; ?>
                            — <?= number_format((float)($package['price'] ?? 0), 2) ?>
                          </option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="sa-field">
                      <label>IP ثابت للمشترك <button type="button" id="staticIpHint" class="sa-help-tip" aria-label="تلميح" data-tip="اختياري، إذا ترك فارغ يأخذ المشترك IP من الـ Pool">?</button></label>
                      <input name="ip_address" id="staticIpInput" class="form-control" inputmode="decimal" dir="ltr" value="<?= sa_old('ip_address') ?>" placeholder="192.168.1.100">
                    </div>
                  </div>
                </div>
              </div>

          <div class="sa-card sa-identity-card">
                <div class="sa-card-head">
                  <h3>الهوية والمرفقات</h3>
                </div>
                <div class="sa-card-body">
                  <div class="sa-form-grid sa-3">
                    <div class="sa-field">
                      <label>صورة الهوية - الوجه الأمامي</label>
                      <label class="sa-file-upload">
                        <input type="file" name="id_card_front" accept=".jpg,.jpeg,.png,.webp,.pdf,image/*,application/pdf" capture="environment">
                        <span>اضغط للرفع</span>
                        <small>JPG, PNG</small>
                      </label>
                    </div>
                    <div class="sa-field">
                      <label>صورة الهوية - الوجه الخلفي</label>
                      <label class="sa-file-upload">
                        <input type="file" name="id_card_back" accept=".jpg,.jpeg,.png,.webp,.pdf,image/*,application/pdf" capture="environment">
                        <span>اضغط للرفع</span>
                        <small>JPG, PNG</small>
                      </label>
                    </div>
                    <div class="sa-field">
                      <label>ملف هوية واحد PDF (اختياري)</label>
                      <label class="sa-file-upload">
                        <input type="file" name="id_card_pdf" accept=".pdf,application/pdf">
                        <span>اضغط للرفع</span>
                        <small>PDF فقط</small>
                      </label>
                    </div>
                  </div>
                </div>
              </div>

          </div>

          <div class="sa-preview">
            <div class="sa-card">
              <div class="sa-card-head"><h3>معاينة الحساب</h3></div>
              <div class="sa-card-body">
                <div class="sa-kpi">
                  <div class="sa-kpi-title">اسم حساب PPPoE</div>
                  <div class="sa-kpi-value" id="pppPreview">—</div>
                </div>
                <div class="sa-kpi mt-2">
                  <div class="sa-kpi-title">كلمة المرور التلقائية</div>
                  <div class="sa-kpi-value" id="passPreview">—</div>
                </div>
              </div>
            </div>

            <div class="sa-card">
              <div class="sa-card-head"><h3>ملخص السرعة والفاتورة</h3></div>
              <div class="sa-card-body">
                <div class="sa-summary">
                  <ul>
                    <li>السرعة: <strong id="speedPreview">—</strong></li>
                    <li>الباقة: <strong id="packagePreview">—</strong></li>
                    <li>الـ Rate Limit: <strong id="ratePreview">—</strong></li>
                    <li>الملف التعريفي: <strong id="profilePreview">—</strong></li>
                    <li>نوع IP: <strong id="ipTypePreview">IP ديناميكي</strong></li>
                    <li>من الـ Pool: <strong id="poolPreview">نعم</strong></li>
                    <li>الحجز: <strong id="quotaPreview">مفتوح/غير محدد</strong></li>
                    <li>سعر السرعة: <strong id="speedPricePreview">0.00</strong></li>
                    <li>سعر الباقة: <strong id="packagePricePreview">0.00</strong></li>
                    <li>رسوم الاشتراك: <strong id="feePreview">0.00</strong></li>
                    <li>الإجمالي الأولي: <strong id="totalPreview">0.00</strong></li>
                  </ul>
                </div>
              </div>
            </div>

            <div class="sa-actions">
              <button class="btn btn-success" type="submit" name="action" value="save_paid" <?= (empty($speeds) || empty($packages) || empty($sectors)) ? 'disabled' : '' ?>>
                حفظ وتسديد
              </button>
              <button class="btn btn-outline-secondary" type="submit" name="action" value="save_only" <?= (empty($speeds) || empty($packages) || empty($sectors)) ? 'disabled' : '' ?>>
                حفظ فقط
              </button>
            </div>

          </div>
        </div>
      </form>
    </div>
  </section>
</div>

<script>
  const pppoeAccountSuffix = <?= json_encode($pppoeAccountSuffix, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  const saHelpBtn = document.getElementById('saHelpBtn');
  const saHelpText = document.getElementById('saHelpText');
  if (saHelpBtn && saHelpText) {
    saHelpBtn.addEventListener('click', function(){
      const isOpen = !saHelpText.hidden;
      saHelpText.hidden = isOpen;
      saHelpBtn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
      saHelpBtn.classList.toggle('is-active', !isOpen);
    });
  }

  const speedMap = <?= json_encode($speedMap, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  const packageMap = <?= json_encode($packageMap, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

  function translitAr(text){
    const map = {
      'ا':'a','أ':'a','إ':'e','آ':'a','ء':'','ؤ':'o','ئ':'e','ى':'a','ة':'a',
      'ب':'b','ت':'t','ث':'th','ج':'j','ح':'h','خ':'kh','د':'d','ذ':'dh','ر':'r','ز':'z','س':'s','ش':'sh','ص':'s','ض':'d','ط':'t','ظ':'z',
      'ع':'e','غ':'gh','ف':'f','ق':'q','ك':'k','ل':'l','م':'m','ن':'n','ه':'h','و':'w','ي':'y'
    };
    return (text || '').split('').map(ch => map[ch] ?? ch).join('').toLowerCase().replace(/[^a-z0-9\s]+/g,' ').replace(/\s+/g,' ').trim();
  }
  function buildSlug(){
    const firstPart = value => (value || '').trim().split(/[\s,،؛;]+/u)[0] || '';
    const first = firstPart(document.querySelector('[name="first_name"]').value);
    const last  = firstPart(document.querySelector('[name="last_name"]').value);
    const raw = (translitAr(first).replace(/\s+/g,'.') + '.' + translitAr(last).replace(/\s+/g,'.')).replace(/\.+/g,'.').replace(/^\.|\.$/g,'');
    return (raw || 'subscriber') + '@' + pppoeAccountSuffix;
  }
  function buildPass(){
    const mother = document.querySelector('[name="mother_name"]').value || '';
    const phone  = (document.querySelector('[name="phone"]').value || '').replace(/\D+/g,'');
    const latin = translitAr(mother).replace(/[^a-z]/g,'');
    const initial = (latin.charAt(0) || 'X').toUpperCase();
    const tail = (phone.padStart(5,'0')).slice(-5) || '00000';
    return initial + tail;
  }
  function getSelectedProfile(){
    const speedId = parseInt(document.getElementById('speed_id').value || '0', 10);
    const packageId = parseInt(document.getElementById('package_id').value || '0', 10);
    const speed = speedMap[speedId] || {};
    const pkg = packageMap[packageId] || {};
    return speed.mikrotik_profile || pkg.mikrotik_profile || 'pppoe-prof';
  }

  function updatePreview(){
    const speedId = parseInt(document.getElementById('speed_id').value || '0', 10);
    const packageId = parseInt(document.getElementById('package_id').value || '0', 10);
    const speed = speedMap[speedId] || {};
    const pkg = packageMap[packageId] || {};
    const speedPrice = parseFloat(speed.price || 0);
    const pkgPrice = parseFloat(pkg.price || 0);
    const fee = parseFloat(pkg.subscription_fee || 0);
    const total = speedPrice + pkgPrice + fee;
    const profile = getSelectedProfile();
    const rate = speed.rate_limit || ((speed.speed_name || '') ? `${speed.speed_name}/${speed.speed_name}` : '—');
    const quota = (pkg.quota_gb !== null && pkg.quota_gb !== undefined && pkg.quota_gb !== '') ? `${pkg.quota_gb} GB` : 'مفتوح / غير محدد';

    document.getElementById('pppPreview').textContent = buildSlug();
    document.getElementById('passPreview').textContent = buildPass();
    document.getElementById('speedPreview').textContent = speed.speed_name || '—';
    document.getElementById('packagePreview').textContent = pkg.package_name || '—';
    document.getElementById('ratePreview').textContent = rate;
    document.getElementById('profilePreview').textContent = profile;
    const staticIpValue = (document.getElementById('staticIpInput')?.value || '').trim();
    const ipTypePreview = document.getElementById('ipTypePreview');
    const poolPreview = document.getElementById('poolPreview');
    if(ipTypePreview) ipTypePreview.textContent = staticIpValue ? 'IP ثابت' : 'IP ديناميكي';
    if(poolPreview) poolPreview.textContent = staticIpValue ? 'لا' : 'نعم';
    document.getElementById('quotaPreview').textContent = quota;
    document.getElementById('speedPricePreview').textContent = speedPrice.toFixed(2);
    document.getElementById('packagePricePreview').textContent = pkgPrice.toFixed(2);
    document.getElementById('feePreview').textContent = fee.toFixed(2);
    document.getElementById('totalPreview').textContent = total.toFixed(2);
  }
  ['first_name','last_name','mother_name','phone'].forEach(name => {
    const el = document.querySelector(`[name="${name}"]`);
    if (el) el.addEventListener('input', updatePreview);
  });
  ['speed_id','package_id'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('change', updatePreview);
  });
  const staticIpInput = document.getElementById('staticIpInput');
  if(staticIpInput) staticIpInput.addEventListener('input', updatePreview);
  updatePreview();
</script>

<script src="assets/js/subscriber_info_print_launcher.js?v=<?= (int)(@filemtime(__DIR__ . '/assets/js/subscriber_info_print_launcher.js') ?: 1) ?>"></script>
<?php include __DIR__ . '/footer.php'; ?>
