<?php
// admin/subscribers_distribution.php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!ob_get_level()) ob_start();

$page_title = 'توزيع المشتركين | Assign Sector/VLAN';

$comms_tab = 'assign';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/comms_admin_lib.php';
require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/super_admin_guard.php';

require_login();
if(function_exists('require_perm')) require_perm('can_view_subscribers');

// حماية توزيع/تسديد بكلمة مرور السوبر أدمن
require_super_admin_confirmation('توزيع وتسديد المشتركين');

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidDistribution = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/pages/subscribers_distribution_admin.css'];
if ($uaAndroidDistribution) $UA_PAGE_CSS[] = 'assets/css/android_subscribers_distribution.css';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

function ensure_sub_cols(mysqli $conn): void {
  if(!table_exists($conn,'subscribers')) return;
  $alts = [];
  if(!col_exists($conn,'subscribers','sector_id')) $alts[] = "ADD COLUMN sector_id INT NULL";
  if(!col_exists($conn,'subscribers','vlan_id')) $alts[] = "ADD COLUMN vlan_id INT NULL";
  if(!col_exists($conn,'subscribers','pppoe_profile')) $alts[] = "ADD COLUMN pppoe_profile VARCHAR(100) NULL";
  if(!col_exists($conn,'subscribers','provision_status')) $alts[] = "ADD COLUMN provision_status VARCHAR(30) NULL";
  if(!col_exists($conn,'subscribers','provisioned_at')) $alts[] = "ADD COLUMN provisioned_at DATETIME NULL";
  if($alts){
    try { $conn->query("ALTER TABLE subscribers ".implode(", ", $alts)); } catch(Throwable $e) {}
  }
}
ensure_sub_cols($conn);

// sectors
comms_ensure_tables($conn);
$sectors_rs = $conn->query("SELECT id, name, vlan_id, pppoe_pool_name AS pool_name, pppoe_pool_range AS pool_range, pppoe_local_ip, pppoe_server_name, pppoe_profile FROM sectors ORDER BY vlan_id ASC, id ASC");
$sectors = [];
if($sectors_rs){ while($s=$sectors_rs->fetch_assoc()){ $sectors[]=$s; } }

// determine password column
$pass_col = null;
foreach(['sub_password','password','pass'] as $c){
  if(col_exists($conn,'subscribers',$c)){ $pass_col=$c; break; }
}

$flash = null; $flash_type='success';

if($_SERVER['REQUEST_METHOD']==='POST'){
  $action = $_POST['action'] ?? '';
  $ids = $_POST['ids'] ?? [];
  if(!is_array($ids)) $ids = [];

  if($action==='save_assign'){
    // sector per subscriber
    $map = $_POST['sector'] ?? [];
    if(!is_array($map)) $map = [];
    $cnt=0;
    foreach($ids as $sid){
      $sid = (int)$sid;
      $sector_id = isset($map[$sid]) ? (int)$map[$sid] : 0;
      $vlan_id = null;
      if($sector_id>0){
        foreach($sectors as $sx){ if((int)$sx['id']===$sector_id){ $vlan_id = (int)($sx['vlan_id'] ?? 0); break; } }
      }
      $vlan_sql = ($vlan_id===null || $vlan_id===0) ? "NULL" : (string)$vlan_id;
      $sector_sql = ($sector_id>0) ? (string)$sector_id : "NULL";
      $conn->query("UPDATE subscribers SET sector_id=$sector_sql, vlan_id=$vlan_sql WHERE id=$sid");
      $cnt++;
    }
    $flash = "تم حفظ التوزيع لـ {$cnt} مشترك/مشتركين.";
    $flash_type='success';

    // سجل العملية
    @audit_log($conn, 'SUBSCRIBER_DISTRIBUTION_SAVE', 'subscribers', 0, 'count='.$cnt);
  }

  if($action==='sync_pppoe_bulk'){
    if(function_exists('require_perm')) require_perm('can_mikrotik_sync');
    if(!$pass_col){
      $flash = "لا يوجد عمود كلمة مرور في جدول subscribers (sub_password/password/pass). لا يمكن المزامنة.";
      $flash_type = 'danger';
    } else {
      $ok=0; $fail=0; $skipped=0;
      $details = [];
      try {
        $api = mt_api_connect($conn); // يعتمد على إعدادات MikroTik الحالية
        try {
          foreach($ids as $sid){
            $sid = (int)$sid;
            $rs = $conn->query("SELECT id, full_name, username, {$pass_col} AS pass, pppoe_profile, vlan_id FROM subscribers WHERE id=$sid AND ".(function_exists('subs_active_where_sql') ? subs_active_where_sql($conn) : 'COALESCE(is_deleted,0)=0'));
            $r = $rs ? $rs->fetch_assoc() : null;
            if(!$r){ $skipped++; continue; }

            $u = trim((string)($r['username'] ?? ''));
            $p = trim((string)($r['pass'] ?? ''));
            if($u==='' || $p===''){
              $skipped++;
              $details[] = "⚠️ تخطي #{$sid}: username/pass ناقص.";
              continue;
            }

            $profile = trim((string)($r['pppoe_profile'] ?? ''));
            if($profile==='') $profile = 'default';

            // remote-address: إذا عنده vlan_id وربطه بقطاع وله pool/local، ما نثبت IP هون (يُترك للـ pool)
            $remote = '';

            // find existing secret
            $resp = $api->command(['/ppp/secret/print', '?name='.$u]);
            $id = null;
            foreach($resp as $row){
              if(($row['.type'] ?? '') !== '!re') continue;
              $id = $row['.id'] ?? null;
              break;
            }
            if($id){
              $cmd = ['/ppp/secret/set', '=.id='.$id, '=password='.$p, '=profile='.$profile];
              if($remote!=='') $cmd[] = '=remote-address='.$remote;
              $api->command($cmd);
            } else {
              $cmd = ['/ppp/secret/add', '=name='.$u, '=password='.$p, '=service=pppoe', '=profile='.$profile];
              if($remote!=='') $cmd[] = '=remote-address='.$remote;
              $api->command($cmd);
            }

            // disconnect active session to apply changes
            try {
              $act = $api->command(['/ppp/active/print', '?name='.$u]);
              foreach($act as $ar){
                if(($ar['.type'] ?? '') !== '!re') continue;
                $aid = $ar['.id'] ?? '';
                if($aid!=='') $api->command(['/ppp/active/remove', '=.id='.$aid]);
                break;
              }
            } catch(Throwable $e){}

            $conn->query("UPDATE subscribers SET provision_status='synced', provisioned_at=NOW() WHERE id=$sid");
            $ok++;
          }
        } finally {
          $api->disconnect();
        }
        $flash = "تمت مزامنة PPPoE: نجاح {$ok} / تخطي {$skipped}.";
        if($fail>0) $flash .= " فشل {$fail}.";
        $flash_type = ($fail>0) ? 'warning' : 'success';

        // سجل المزامنة
        @audit_log($conn, 'SUBSCRIBER_PPPOE_SYNC', 'subscribers', 0, 'ok='.$ok.'; skipped='.$skipped.'; fail='.$fail);
      } catch(Throwable $e){
        $flash = "فشل الاتصال بـ MikroTik أو تنفيذ المزامنة: ".$e->getMessage();
        $flash_type='danger';
      }
    }
  }
}

// load subscribers
// select only existing columns to avoid fatal
$cols = ['id','full_name','username','phone','sector_id','vlan_id','pppoe_profile','provision_status','provisioned_at'];
$sel = [];
foreach($cols as $c){
  if(col_exists($conn,'subscribers',$c)) $sel[] = $c;
}
if(!in_array('id',$sel,true)) $sel[]='id';
if(!in_array('full_name',$sel,true) && col_exists($conn,'subscribers','name')) $sel[]='name AS full_name';

$sel_sql = implode(", ", $sel);
$distWhere = function_exists('subs_active_where_sql') ? subs_active_where_sql($conn) : 'COALESCE(is_deleted,0)=0';
$distQuery = trim((string)($_GET['q'] ?? ''));
$distPage = max(1,(int)($_GET['page'] ?? 1));
$distPerPage = 30;
$distTotal = 0;
if ($uaAndroidDistribution && $distQuery !== '') {
  $distEsc=$conn->real_escape_string($distQuery);
  $distId = ctype_digit($distQuery) ? ('id=' . (int)$distQuery . ' OR ') : '';
  $distWhere .= " AND ({$distId}full_name LIKE '%$distEsc%' OR username LIKE '%$distEsc%' OR phone LIKE '%$distEsc%')";
}
if ($uaAndroidDistribution) {
  $countRs=$conn->query("SELECT COUNT(*) c FROM subscribers WHERE $distWhere");
  if($countRs&&$countRow=$countRs->fetch_assoc())$distTotal=(int)$countRow['c'];
  $distPages=max(1,(int)ceil($distTotal/$distPerPage));$distPage=min($distPage,$distPages);$distOffset=($distPage-1)*$distPerPage;
  $subs_rs=$conn->query("SELECT $sel_sql FROM subscribers WHERE $distWhere ORDER BY id DESC LIMIT $distPerPage OFFSET $distOffset");
  $distributionSubs=[];if($subs_rs)while($row=$subs_rs->fetch_assoc())$distributionSubs[]=$row;
  require __DIR__ . '/android_subscribers_distribution.php';
  include __DIR__ . '/footer.php';
  exit;
}
$subs_rs = $conn->query("SELECT $sel_sql FROM subscribers WHERE $distWhere ORDER BY id DESC LIMIT 1000");

$active_tab = 'dist';
?>
<div class="content-wrapper ua-extracted-page ua-subscriber-child-page ua-sub-child-distribution ua-network-distribution-page">
  <section class="content">
    <div class="ua-page-v2">
      <header class="ua-page-head">
        <div class="ua-page-title">
          <h1>توزيع المشتركين | Assign</h1>
          <p>اختيار القطاع/VLAN ثم حفظ التوزيع أو مزامنة PPPoE للمشتركين المحددين.</p>
        </div>
      </header>

      <?php if($flash){ ?>
        <div class="ua-alert alert-<?= h($flash_type) ?>"><?= h($flash) ?></div>
      <?php } ?>

      <form method="post">
        <section class="ua-panel-v2">
          <div class="ua-panel-body d-flex gap-2 align-items-center flex-wrap">
            <button class="btn btn-primary" name="action" value="save_assign" type="submit"><i class="fa fa-save"></i> حفظ التوزيع للمختارين</button>
            <button class="btn btn-success" name="action" value="sync_pppoe_bulk" type="submit"><i class="fa fa-refresh"></i> Sync PPPoE للمختارين (Bulk)</button>
            <div class="ua-child-summary ms-auto">
              <small>
              * المزامنة تحتاج عمود كلمة مرور (sub_password/password/pass) + إعدادات MikroTik.
              </small>
            </div>
          </div>
        </section>

        <section class="ua-panel-v2">
          <div class="ua-panel-body">
            <div class="ua-table-wrap">
            <table class="ua-table">
              <thead>
                <tr>
                  <th class="ua-u-w-40"><input type="checkbox" onclick="document.querySelectorAll('.ck').forEach(x=>x.checked=this.checked)"></th>
                  <th>#</th>
                  <th>الاسم</th>
                  <th>المستخدم</th>
                  <th>الهاتف</th>
                  <th>Sector/VLAN</th>
                  <th>Provision</th>
                </tr>
              </thead>
              <tbody>
              <?php if($subs_rs && $subs_rs->num_rows){ while($r=$subs_rs->fetch_assoc()){ $sid=(int)$r['id']; ?>
                <tr>
                  <td><input class="ck" type="checkbox" name="ids[]" value="<?= $sid ?>"></td>
                  <td><?= $sid ?></td>
                  <td><?= h($r['full_name'] ?? '-') ?></td>
                  <td><?= h($r['username'] ?? '-') ?></td>
                  <td><?= h($r['phone'] ?? '-') ?></td>
                  <td>
                    <select class="form-control" name="sector[<?= $sid ?>]">
                      <option value="0">-- بدون --</option>
                      <?php foreach($sectors as $s){ $sel = ((int)($r['sector_id'] ?? 0) === (int)$s['id']) ? 'selected' : ''; ?>
                        <option value="<?= (int)$s['id'] ?>" <?= $sel ?>>
                          <?= h(($s['name'] ?? 'Sector').' | VLAN '.($s['vlan_id'] ?? '')) ?>
                        </option>
                      <?php } ?>
                    </select>
                  </td>
                  <td>
                    <?php $ps = $r['provision_status'] ?? ''; ?>
                    <span class="<?= $ps==='synced'?'text-success':'' ?>"><?= h($ps ?: '-') ?></span>
                  </td>
                </tr>
              <?php } } else { ?>
                <tr><td colspan="7" class="text-center">لا يوجد مشتركين</td></tr>
              <?php } ?>
              </tbody>
            </table>
            </div>
          </div>
        </section>
      </form>

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

<script>
// small UX: keep scrolling position after submit (optional)
</script>

<?php include __DIR__ . '/footer.php'; ?>
