<?php
// admin/agent_pos.php
// واجهة نقطة البيع للمعتمدين: تفعيل كرت بعد الدفع + تبديل جهاز مرة واحدة (MAC reset)

$agentRedirect = (int)($_GET['agent'] ?? 0);
$agentPortal = 'agent_portal.php' . ($agentRedirect > 0 ? ('?agent=' . $agentRedirect) : '');
if (!headers_sent()) {
  header('Location: ' . $agentPortal);
  exit;
}

$page_title = 'واجهة نقطة البيع';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/lang.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/vouchers_lib.php';
require_once __DIR__ . '/shop_lib.php';
require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/app_assets.php';
require_once __DIR__ . '/agent_service.php';

if (session_status() === PHP_SESSION_NONE) session_start();
$conn = ensure_db(true);
vouchers_ensure_tables($conn);

// Ensure agent columns exist (for older dbs)
$conn->query("CREATE TABLE IF NOT EXISTS agents (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  username VARCHAR(120) NULL,
  password_hash VARCHAR(255) NULL,
  pin_hash VARCHAR(255) NULL,
  pos_enabled TINYINT(1) NOT NULL DEFAULT 1,
  phone VARCHAR(50) NULL,
  balance DECIMAL(12,2) NOT NULL DEFAULT 0,
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8");

function agent_get(mysqli $conn, int $id): ?array {
  $q = $conn->prepare('SELECT * FROM agents WHERE id=? LIMIT 1');
  $q->bind_param('i',$id);
  $q->execute();
  $r = $q->get_result();
  $row = $r && $r->num_rows ? $r->fetch_assoc() : null;
  $q->close();
  return $row ?: null;
}

function agent_tx_add(mysqli $conn, int $agent_id, string $type, float $amount = 0, string $note = ''): void {
  if ($amount != 0.0) return;
  ua_agent_activity_add($conn, [
    'agent_id'=>$agent_id,
    'event_type'=>strtoupper(substr($type, 0, 60)),
    'summary'=>$note,
    'actor_type'=>'agent',
    'actor_id'=>$agent_id,
  ]);
}


// MikroTik helpers (guarded to avoid redeclare; core implementation lives in mikrotik_lib.php)
if (!function_exists('mt_ensure_hotspot_profile')) {
function mt_ensure_hotspot_profile(mysqli $conn, string $profile_name, string $rate_limit = ''): void {
  $profile_name = trim($profile_name);
  if ($profile_name === '') return;
  $api = mt_api_connect($conn);
  try {
    $exists = $api->command(['/ip/hotspot/user/profile/print', '?name=' . $profile_name]);
    $found_id = null;
    foreach ($exists as $r) {
      if (($r['.type'] ?? '') !== '!re') continue;
      $found_id = $r['.id'] ?? null;
      break;
    }
    if ($found_id) {
      // update rate-limit if provided
      if ($rate_limit !== '') {
        $api->command(['/ip/hotspot/user/profile/set', '=.id=' . $found_id, '=rate-limit=' . $rate_limit]);
      }
      return;
    }
    $cmd = ['/ip/hotspot/user/profile/add', '=name=' . $profile_name];
    if ($rate_limit !== '') $cmd[] = '=rate-limit=' . $rate_limit;
    $api->command($cmd);
  } finally {
    $api->disconnect();
  }
}
}


function mt_build_on_login_script(bool $wallclock_enabled, bool $single_device, bool $device_lock_enabled, string $steps_csv): string {
  if (!$wallclock_enabled && !$single_device) return '';

  // sanitize steps (minutes) for device lock
  $steps = array_values(array_filter(array_map('trim', explode(',', $steps_csv)), fn($x)=>$x!==''));
  $mins = [];
  foreach ($steps as $s) {
    if (preg_match('/^\d+$/', $s)) {
      $n = (int)$s;
      if ($n > 0 && $n <= 240) $mins[] = (string)$n;
    }
  }
  if (!$mins) $mins = ['1','5','10','30'];
  $arr = '{"' . implode('";"', $mins) . '"}';

  $script = ':local u $user; :local m $mac; :local id [/ip hotspot user find name=$u];'
    . ' :if ([:len $id] = 0) do={ :return; }'
    . ' :local c [/ip hotspot user get $id comment];';

  if ($wallclock_enabled) {
    $script .= ' :local pd [:find $c "durm="];'
      . ' :if ($pd != nil) do={'
      . '   :local started ([:find $c "start=1"] != nil);'
      . '   :if (!$started) do={'
      . '     :local rest [:pick $c ($pd+5) [:len $c]]; :local sp [:find $rest " "]; :if ($sp != nil) do={ :set rest [:pick $rest 0 $sp]; }'
      . '     :local dur [:tonum $rest];'
      . '     :if ($dur > 0) do={'
      . '       /ip hotspot user set $id comment=($c . " start=1 rem=" . $dur);'
      . '       :local s ("vexp-" . $u);'
      . '       /system scheduler remove [find name=$s];'
      . '       /system scheduler add name=$s interval=1m on-event=('
      . '         ":local u \\"".$u."\\"; :local s \\"vexp-".$u."\\"; :local id [/ip hotspot user find name=$u];'
      . '          :if ([:len $id]=0) do={ /system scheduler remove [find name=$s]; :return; };'
      . '          :local c [/ip hotspot user get $id comment]; :local pr [:find $c \\"rem=\\"];'
      . '          :if ($pr = nil) do={ /system scheduler remove [find name=$s]; :return; };'
      . '          :local r [:pick $c ($pr+4) [:len $c]]; :local sp [:find $r \\" \\\"]; :if ($sp != nil) do={ :set r [:pick $r 0 $sp]; };'
      . '          :local rem [:tonum $r]; :set rem ($rem-1);'
      . '          :if ($rem <= 0) do={ /ip hotspot active remove [find user=$u]; /ip hotspot cookie remove [find user=$u]; /ip hotspot user disable $id; /system scheduler remove [find name=$s]; }'
      . '          else={'
      . '            :local pre [:pick $c 0 ($pr+4)]; :local rest2 [:pick $c ($pr+4) [:len $c]]; :local sp2 [:find $rest2 \\" \\\"]; :local suf \\"\\"; :if ($sp2 != nil) do={ :set suf [:pick $rest2 $sp2 [:len $rest2]]; };'
      . '            /ip hotspot user set $id comment=($pre . $rem . $suf);'
      . '          }"'
      . '       );'
      . '     }'
      . '   }'
      . ' };';
  }

  if ($single_device) {
    $script .= ' :local cur [/ip hotspot user get $id mac-address];'
      . ' :if ([:len $cur] = 0) do={ /ip hotspot user set $id mac-address=$m; }';
    if ($device_lock_enabled) {
      $script .= ' else={ :if ($cur != $m) do={'
        . ' :local c [/ip hotspot user get $id comment]; :local v 0;'
        . ' :local p [:find $c "viol="];'
        . ' :if ($p != nil) do={ :local rest [:pick $c ($p+5) [:len $c]]; :local sp [:find $rest " "]; :if ($sp != nil) do={ :set rest [:pick $rest 0 $sp]; } :set v [:tonum $rest]; }'
        . ' :set v ($v+1);'
        . ' :local pre $c;'
        . ' :if ($p != nil) do={ :set pre [:pick $c 0 $p]; :local rest2 [:pick $c ($p+5) [:len $c]]; :local sp2 [:find $rest2 " "]; :local suf ""; :if ($sp2 != nil) do={ :set suf [:pick $rest2 $sp2 [:len $rest2]]; } :set c ($pre . "viol=" . $v . $suf); } else={ :set c ($c . " viol=" . $v); }'
        . ' /ip hotspot user set $id comment=$c;'
        . ' :local steps ' . $arr . ';'
        . ' :local idx ($v-1); :if ($idx < 0) do={ :set idx 0; } :if ($idx >= [:len $steps]) do={ :set idx ([:len $steps]-1); }'
        . ' :local mins ($steps->$idx); :local mm $mins; :if ([:len $mm] = 1) do={ :set mm ("0".$mm); }'
        . ' :local interval ("00:".$mm.":00"); :local s ("unlock-".$u);'
        . ' /system scheduler remove [find name=$s];'
        . ' /ip hotspot active remove [find user=$u]; /ip hotspot cookie remove [find user=$u];'
        . ' /ip hotspot user disable $id;'
        . ' /system scheduler add name=$s interval=$interval on-event=("/ip hotspot user enable [find name=\\\"".$u."\\\"]; /system scheduler remove [find name=\\\"".$s."\\\"]; ");'
        . ' } };';
    }
    $script .= ' };';
  }

  return $script;
}

function mt_ensure_voucher_profile($api, string $profile_name, bool $wallclock_enabled, bool $single_device, bool $device_lock_enabled, string $steps_csv, string $rate_limit=''): void {
  $profile_name = trim($profile_name);
  if ($profile_name === '') $profile_name = 'voucher';

  $onLogin = mt_build_on_login_script($wallclock_enabled, $single_device, $device_lock_enabled, $steps_csv);

  $exists = $api->command(['/ip/hotspot/user/profile/print', '?name=' . $profile_name]);
  $found_id = null;
  foreach ($exists as $r) {
    if (($r['.type'] ?? '') === '!re' && isset($r['.id'])) { $found_id = $r['.id']; break; }
  }

  if ($found_id !== null) {
    $cmd = ['/ip/hotspot/user/profile/set', '=.id=' . $found_id];
    if ($rate_limit !== '') $cmd[] = '=rate-limit=' . $rate_limit;
    if ($single_device) $cmd[] = '=shared-users=1';
    if ($onLogin !== '') $cmd[] = '=on-login=' . $onLogin;
    $api->command($cmd);
    return;
  }

  $cmd = ['/ip/hotspot/user/profile/add', '=name=' . $profile_name];
  if ($rate_limit !== '') $cmd[] = '=rate-limit=' . $rate_limit;
  if ($single_device) $cmd[] = '=shared-users=1';
  if ($onLogin !== '') $cmd[] = '=on-login=' . $onLogin;
  $api->command($cmd);
}

function mt_create_hotspot_user_for_voucher(mysqli $conn, array $v, string $profile_name, bool $single_device): array {
  $username = (string)($v['code'] ?? '');
  $password = (string)($v['passcode'] ?? '');
  $rate = trim((string)($v['rate_limit'] ?? ''));

  $limit_uptime = '';
  $limit_bytes = '';

  if (($v['type'] ?? '') === 'time' || ($v['type'] ?? '') === 'both') {
    $mins = (int)($v['duration_minutes'] ?? 0);
    if ($mins > 0) {
      // RouterOS uptime format: 1d00:00:00
      $d = intdiv($mins, 1440);
      $rem = $mins % 1440;
      $h = intdiv($rem, 60);
      $m = $rem % 60;
      $limit_uptime = ($d>0 ? $d.'d' : '') . sprintf('%02d:%02d:00', $h, $m);
    }
  }
  if (($v['type'] ?? '') === 'data' || ($v['type'] ?? '') === 'both') {
    $b = (int)($v['data_bytes'] ?? 0);
    if ($b > 0) $limit_bytes = (string)$b;
  }

  $comment = 'voucher:' . $username;
    $wallclock_enabled = (bool)($GLOBALS['VOUCHER_TIME_WALLCLOCK'] ?? false);
  if ($wallclock_enabled && !empty($v['duration_minutes'])) { $comment .= ' durm=' . (int)$v['duration_minutes']; $limit_uptime=''; }
  if ($single_device) $comment .= ' | single_device=1';

  $api = mt_api_connect($conn);
  try {
    mt_ensure_voucher_profile($api, $profile_name, (bool)($GLOBALS['VOUCHER_TIME_WALLCLOCK'] ?? false), $single_device, (bool)($GLOBALS['VOUCHER_DEVICE_LOCK_ENABLED'] ?? false), (string)($GLOBALS['VOUCHER_DEVICE_LOCK_STEPS'] ?? '1,5,10,30'), $rate);

    $exists = $api->command(['/ip/hotspot/user/print', '?name=' . $username]);
    $found_id = null;
    foreach ($exists as $r) {
      if (($r['.type'] ?? '') !== '!re') continue;
      $found_id = $r['.id'] ?? null;
      break;
    }
    if ($found_id) {
      $cmd = ['/ip/hotspot/user/set', '=.id=' . $found_id, '=password=' . $password, '=comment=' . $comment, '=profile=' . $profile_name];
      if ($rate !== '') $cmd[] = '=rate-limit=' . $rate;
      if ($limit_uptime) $cmd[] = '=limit-uptime=' . $limit_uptime;
      if ($limit_bytes) $cmd[] = '=limit-bytes-total=' . $limit_bytes;
      if ($single_device) $cmd[] = '=shared-users=1';
      $api->command($cmd);
    } else {
      $cmd = ['/ip/hotspot/user/add', '=name=' . $username, '=password=' . $password, '=comment=' . $comment, '=profile=' . $profile_name];
      if ($rate !== '') $cmd[] = '=rate-limit=' . $rate;
      if ($limit_uptime) $cmd[] = '=limit-uptime=' . $limit_uptime;
      if ($limit_bytes) $cmd[] = '=limit-bytes-total=' . $limit_bytes;
      if ($single_device) $cmd[] = '=shared-users=1';
      $api->command($cmd);
    }
  } finally {
    $api->disconnect();
  }
  return ['username'=>$username,'password'=>$password,'rate'=>$rate,'uptime'=>$limit_uptime,'bytes'=>$limit_bytes,'profile'=>$profile_name];
}

function mt_reset_hotspot_mac(mysqli $conn, string $username): void {
  $username = trim($username);
  if ($username==='') throw new RuntimeException('اسم المستخدم غير صالح');
  $api = mt_api_connect($conn);
  try {
    $u = $api->command(['/ip/hotspot/user/print', '?name=' . $username]);
    $uid = null;
    foreach ($u as $r) {
      if (($r['.type'] ?? '') !== '!re') continue;
      $uid = $r['.id'] ?? null;
      break;
    }
    if (!$uid) throw new RuntimeException('المستخدم غير موجود على MikroTik');

    // clear mac binding
    $api->command(['/ip/hotspot/user/set', '=.id=' . $uid, '=mac-address=']);
    // kill sessions/cookies
    $api->command(['/ip/hotspot/active/remove', '?user=' . $username]);
    $api->command(['/ip/hotspot/cookie/remove', '?user=' . $username]);
  } finally {
    $api->disconnect();
  }
}

$agent_id = (int)($_GET['agent'] ?? 0);

// إذا لم يتم تحديد معتمد: اعرض قائمة المعتمدين المتاحين بدل رسالة خطأ
if ($agent_id <= 0) {
  $agents = [];
  try {
    $q = $conn->query("SELECT id, name, phone, balance, is_active, pos_enabled FROM agents ORDER BY id DESC");
    if ($q) {
      while($r = $q->fetch_assoc()) {
        if ((int)($r['is_active'] ?? 1) !== 1) continue;
        if ((int)($r['pos_enabled'] ?? 1) !== 1) continue;
        $agents[] = $r;
      }
    }
  } catch (Throwable $e) {}

  $UA_FORCE_DESIGN_V2 = true;
  require_once __DIR__ . '/header.php';
  require_once __DIR__ . '/sidebar.php';
  ?>
  <div class="content-wrapper ua-extracted-page ua-u-text-right" dir="rtl">
    <section class="content-header">
      <h1>واجهة نقطة البيع</h1>
      <ol class="breadcrumb ua-u-float-left">
        <li><a href="dashboard.php"><i class="fa fa-dashboard"></i> الرئيسية</a></li>
        <li class="active">نقطة البيع</li>
      </ol>
    </section>

    <section class="content">
      <div class="box box-primary">
        <div class="box-header with-border"><h3 class="box-title">اختر معتمد</h3></div>
        <div class="box-body">
          <?php if (empty($agents)): ?>
            <div class="alert alert-warning">لا يوجد معتمدون مفعّلون لنقطة البيع.</div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-striped ua-u-text-right">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>الاسم</th>
                    <th>الهاتف</th>
                    <th>الرصيد</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach($agents as $a): ?>
                    <tr>
                      <td><?= (int)$a['id'] ?></td>
                      <td><?= h($a['name'] ?? '') ?></td>
                      <td><?= h($a['phone'] ?? '') ?></td>
                      <td><?= h($a['balance'] ?? '0') ?></td>
                      <td><a class="btn btn-primary btn-sm" href="agent_pos.php?agent=<?= (int)$a['id'] ?>">فتح</a></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </section>
  </div>
  <?php
  require_once __DIR__ . '/footer.php';
  exit;
}

$agent = agent_get($conn, $agent_id);
if (!$agent) { http_response_code(404); echo 'Agent not found'; exit; }
if ((int)$agent['is_active'] !== 1) { echo 'هذا المعتمد غير مفعل'; exit; }
if ((int)$agent['pos_enabled'] !== 1) { echo 'واجهة نقطة البيع موقوفة لهذا المعتمد'; exit; }

// Session check
$session_key = 'agent_pos_' . $agent_id;
$logged = isset($_SESSION[$session_key]) && $_SESSION[$session_key] === true;

$msg = ''; $err = '';

if (isset($_POST['login'])) {
  $pin = trim((string)($_POST['pin'] ?? ''));
  if ($pin==='') $err = 'أدخل PIN';
  elseif (empty($agent['pin_hash']) || !password_verify($pin, (string)$agent['pin_hash'])) $err = 'PIN غير صحيح';
  else {
    $_SESSION[$session_key] = true;
    $logged = true;
    $msg = 'تم تسجيل الدخول ✅';
  }
}

if (isset($_POST['logout'])) {
  unset($_SESSION[$session_key]);
  $logged = false;
}

// Settings
$voucher_paid_only = get_app_setting($conn,'voucher_qr_paid_only','1') === '1';
$voucher_auto_mt_on_redeem = get_app_setting($conn,'voucher_auto_mt_on_redeem','1') === '1';
$voucher_single_device = get_app_setting($conn,'voucher_single_device','1') === '1';
$voucher_hotspot_profile = get_app_setting($conn,'voucher_hotspot_profile','voucher');
$device_reset_max = (int)get_app_setting($conn,'voucher_device_reset_max','1');
$device_lock_enabled = get_app_setting($conn,'voucher_device_lock_enabled','1') === '1';
$device_lock_steps = (string)get_app_setting($conn,'voucher_device_lock_steps','1,5,10,30');
$voucher_time_wallclock = get_app_setting($conn,'voucher_time_wallclock','1') === '1';

if ($logged && isset($_POST['sell_activate'])) {
  $code = trim((string)($_POST['code'] ?? ''));
  $sold_to = trim((string)($_POST['sold_to'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $price = ($_POST['price'] ?? '');
  $price = ($price==='' ? null : (float)$price);

  if ($code==='') $err = 'أدخل كود الكرت';
  else {
    $c = $conn->real_escape_string($code);
    $q = $conn->query("SELECT * FROM voucherss WHERE code='$c' LIMIT 1");
    $v = ($q && $q->num_rows) ? $q->fetch_assoc() : null;
    if (!$v) $err = 'الكرت غير موجود';
    elseif (in_array($v['status'], ['cancelled','expired'], true)) $err = 'الكرت ملغي/منتهي';
    else {
      // Make sale + payment (always, in agent portal)
      $final_price = $price;
      if ($final_price === null && $v['price'] !== null) $final_price = (float)$v['price'];
      if ($final_price === null) $final_price = 0.0;

      // Update voucher sold
      $stmt = $conn->prepare("UPDATE voucherss SET status='sold', sold_at=NOW(), sold_by=?, sold_to=?, price=? WHERE id=? AND status IN ('new','sold')");
      $aid = (int)$agent_id;
      $sold_to_db = $sold_to;
      $pid = (int)$v['id'];
      $stmt->bind_param('isdi', $aid, $sold_to_db, $final_price, $pid);
      @$stmt->execute();
      $stmt->close();

      // Create shop sale only if missing
      $sale_id = (int)($v['shop_sale_id'] ?? 0);
      if ($sale_id <= 0) {
        $item_name = 'كرت إنترنت (' . $v['code'] . ')';
        if (($v['type'] ?? '') === 'time' && !empty($v['duration_minutes'])) {
          $hrs = round(((int)$v['duration_minutes'])/60, 2);
          $item_name .= ' — ' . $hrs . 'h';
        } elseif (($v['type'] ?? '') === 'data' && !empty($v['data_bytes'])) {
          $gb = round(((int)$v['data_bytes'])/1024/1024/1024, 2);
          $item_name .= ' — ' . $gb . 'GB';
        } elseif (($v['type'] ?? '') === 'both') {
          $parts = [];
          if (!empty($v['duration_minutes'])) $parts[] = round(((int)$v['duration_minutes'])/60, 2) . 'h';
          if (!empty($v['data_bytes'])) $parts[] = round(((int)$v['data_bytes'])/1024/1024/1024, 2) . 'GB';
          if ($parts) $item_name .= ' — ' . implode(' + ', $parts);
        }

        $payload = [
          'customer_name' => $sold_to,
          'customer_phone' => $phone,
          'discount' => 0,
          'notes' => 'Voucher: ' . $v['code'] . ' | Agent: ' . ($agent['name'] ?? ''),
          'created_by' => 0,
          'agent_id' => $agent_id,
          'items' => [
            ['product_id'=>0,'name'=>$item_name,'qty'=>1,'price'=>$final_price]
          ]
        ];
        $sale_id = shop_create_sale($conn, $payload);
        if ($sale_id) {
          $up = $conn->prepare('UPDATE voucherss SET shop_sale_id=? WHERE id=?');
          $up->bind_param('ii', $sale_id, $pid);
          @$up->execute();
          $up->close();
        }
      }

      // Cash payment (one time)
      $payment_id = (int)($v['payment_id'] ?? 0);
      if ($sale_id && $payment_id <= 0) {
        $payment_id = vouchers_create_cash_payment_for_shop_sale($conn, (int)$sale_id, (float)$final_price, (string)$v['code'], 'AGENT: '.($agent['name'] ?? ''), $agent_id);
        if ($payment_id) {
          $up2 = $conn->prepare('UPDATE voucherss SET payment_id=? WHERE id=?');
          $up2->bind_param('ii', $payment_id, $pid);
          @$up2->execute();
          $up2->close();
        }
      }
      // log sold by agent
      vouchers_log($conn, $pid, 'sold', ['sale_id'=>$sale_id,'payment_id'=>$payment_id,'amount'=>$final_price,'sold_to'=>$sold_to], $agent_id, 'agent');
      agent_tx_add($conn, $agent_id, 'voucher_sale', (float)$final_price, 'Voucher '.$v['code'].' | Sale#'.$sale_id.' | Pay#'.$payment_id);

      // Auto-create MikroTik user on redeem (if enabled)
      if ($voucher_auto_mt_on_redeem) {
        // enforce paid-only if configured
        if ($voucher_paid_only && $payment_id <= 0) {
          $err = 'لم يتم تسجيل الدفع بعد';
        } else {
          try {
            $profile_used = vouchers_resolve_mt_profile($conn, (int)($v['product_id'] ?? 0), $voucher_hotspot_profile);
            $info = mt_create_hotspot_user_for_voucher($conn, $v + ['price'=>$final_price,'shop_sale_id'=>$sale_id,'payment_id'=>$payment_id], $profile_used, $voucher_single_device);
            $msg = 'تم البيع + التفعيل على MikroTik ✅ ('.h($info['username']).')';
          } catch (Throwable $e) {
            $err = 'تم البيع لكن فشل التفعيل على MikroTik: ' . $e->getMessage();
          }
        }
      } else {
        $msg = 'تم البيع ✅';
      }
    }
  }
}

if ($logged && isset($_POST['reset_device'])) {
  $code = trim((string)($_POST['code'] ?? ''));
  if ($code==='') $err = 'أدخل كود الكرت';
  else {
    $c = $conn->real_escape_string($code);
    $q = $conn->query("SELECT * FROM voucherss WHERE code='$c' LIMIT 1");
    $v = ($q && $q->num_rows) ? $q->fetch_assoc() : null;
    if (!$v) $err = 'الكرت غير موجود';
    else {
      $pid = (int)$v['id'];
      $paid = ((int)($v['payment_id'] ?? 0)) > 0 || in_array($v['status'], ['sold','used'], true);
      if (!$paid) $err = 'لا يمكن تبديل الجهاز قبل الدفع';
      else {
        $used_resets = (int)($v['device_resets'] ?? 0);
        if ($used_resets >= $device_reset_max) {
          $err = 'تم استهلاك عدد تبديل الجهاز المسموح ('.$device_reset_max.')';
        } else {
          try {
            mt_reset_hotspot_mac($conn, (string)$v['code']);
            $conn->query("UPDATE voucherss SET device_resets=device_resets+1, bound_mac=NULL WHERE id=$pid");
            vouchers_log($conn, $pid, 'device_reset', ['agent_name'=>$agent['name'] ?? ''], $agent_id, 'agent');
            agent_tx_add($conn, $agent_id, 'device_reset', 0, 'Voucher '.$v['code']);
            $msg = 'تم تبديل الجهاز (فك ربط MAC) ✅';
          } catch (Throwable $e) {
            $err = 'فشل تبديل الجهاز: ' . $e->getMessage();
          }
        }
      }
    }
  }
}

?><!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h($page_title) ?></title>
  <?= ua_asset_tag_css('bootstrap_533_rtl_css') ?>
</head>
<body class="hold-transition layout-top-nav">
<div class="wrapper">
  <nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <span class="navbar-brand mb-0 h1">واجهة نقطة البيع — <?= h($agent['name']) ?></span>
    <div class="ml-auto">
      <?php if($logged){ ?>
        <form method="post" class="mb-0"><button class="btn btn-outline-danger btn-sm" name="logout">خروج</button></form>
      <?php } ?>
    </div>
  </nav>

  <div class="content-wrapper">
    <section class="content pt-3"><div class="container">
      <?php if($msg){?><div class="alert alert-success"><?= $msg ?></div><?php }?>
      <?php if($err){?><div class="alert alert-danger"><?= h($err) ?></div><?php }?>

      <?php if(!$logged){ ?>
        <div class="card"><div class="card-body">
          <h5 class="mb-3">تسجيل الدخول (PIN)</h5>
          <form method="post" class="row ua-u-gap-075">
            <div class="col-md-4">
              <label>PIN</label>
              <input name="pin" type="password" class="form-control" placeholder="PIN" autofocus>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button class="btn btn-primary w-100" name="login">دخول</button>
            </div>
          </form>
          <div class="text-muted mt-3 ua-u-fs-09">
            هذه الصفحة خاصة بالمعتمد. لا يتم تفعيل أي كرت إلا بعد الدفع.
          </div>
        </div></div>
      <?php } else { ?>

        <div class="card"><div class="card-body">
          <h5 class="mb-3">1) بيع + تفعيل كرت</h5>
          <form method="post">
            <div class="row">
              <div class="col-md-3"><label>كود الكرت</label><input name="code" class="form-control" placeholder="V-XXXX" required></div>
              <div class="col-md-3"><label>اسم العميل</label><input name="sold_to" class="form-control" placeholder="اختياري"></div>
              <div class="col-md-2"><label>هاتف</label><input name="phone" class="form-control" placeholder="اختياري"></div>
              <div class="col-md-2"><label>السعر</label><input name="price" class="form-control" type="number" step="0.01" placeholder="اتركه فارغاً لسعر الدفعة"></div>
              <div class="col-md-2 d-flex align-items-end"><button class="btn btn-success w-100" name="sell_activate">بيع + تفعيل</button></div>
            </div>
          </form>
          <div class="text-muted mt-2 ua-u-fs-09">
            سيتم إنشاء فاتورة + قبض تلقائي، ثم تفعيل حساب Hotspot على MikroTik (إذا كان مفعلاً من الإعدادات).
          </div>
        </div></div>

        <div class="card"><div class="card-body">
          <h5 class="mb-3">2) تبديل جهاز (مرة واحدة)</h5>
          <form method="post" class="row">
            <div class="col-md-3"><label>كود الكرت</label><input name="code" class="form-control" required></div>
            <div class="col-md-3 d-flex align-items-end">
              <button class="btn btn-warning w-100" name="reset_device">فك ربط MAC</button>
            </div>
            <div class="col-md-6 d-flex align-items-end text-muted ua-u-fs-09">
              الحد الأقصى: <?= (int)$device_reset_max ?> مرة.
            </div>
          </form>
        </div></div>

      <?php } ?>

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

  <footer class="main-footer text-center">
    <small>نقطة بيع — نظام الكروت</small>
  </footer>
</div>
<?php echo ua_asset_tag_js('bootstrap_533_bundle_js'); ?>
</body>
</html>
