<?php
$page_title = 'إدارة القطاعات VLAN';
require_once __DIR__ . '/auth.php';
require_login();
if(function_exists('require_perm')) require_perm('can_settings');
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSectors = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = ['assets/css/pages/sectors_admin.css'];
if ($uaAndroidSectors) $UA_PAGE_CSS[] = 'assets/css/android_sectors.css';
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';

$comms_active = 'vlans';
require_once __DIR__ . '/comms_admin_lib.php';

$conn = $GLOBALS['conn'];
comms_ensure_tables($conn);

$action = $_POST['action'] ?? '';
$msg=null; $msg_type='success';

function postv($k,$def=''){ return trim($_POST[$k] ?? $def); }

// ملاحظة: تم نقل Ensure Networking إلى comms_admin_lib.php لتجنب التكرار.

if($action==='save_sector'){
  $id=intval($_POST['id'] ?? 0);
  $name=postv('name');
  $vlan_id=intval($_POST['vlan_id'] ?? 0);
  $router_id=intval($_POST['router_id'] ?? 0);
  $trunk=postv('trunk_interface','ether2');
  $bridge=postv('bridge_name','bridge-pppoe');
  $pppoe_pool_name = postv('pppoe_pool_name');
  $pppoe_pool_range= postv('pppoe_pool_range');
  $pppoe_local_ip  = postv('pppoe_local_ip');
  $pppoe_service   = postv('pppoe_service');
  $pppoe_server_name = postv('pppoe_server_name');
  $is_enabled=isset($_POST['is_enabled'])?1:0;
  $notes=postv('notes');

  if($name==='' || $vlan_id<=0 || $router_id<=0){
    $msg_type='danger'; $msg='يرجى إدخال اسم القطاع و VLAN ID واختيار الراوتر.';
  } else {
    $nameE=$conn->real_escape_string($name);
    $trunkE=$conn->real_escape_string($trunk);
    $bridgeE=$conn->real_escape_string($bridge);
    $notesE=$conn->real_escape_string($notes);
    $poolNameE=$conn->real_escape_string($pppoe_pool_name);
    $poolRangeE=$conn->real_escape_string($pppoe_pool_range);
    $localIpE=$conn->real_escape_string($pppoe_local_ip);
    $serviceE=$conn->real_escape_string($pppoe_service);
    $serverNameE=$conn->real_escape_string($pppoe_server_name);

    if($id>0){
      $conn->query("UPDATE sectors SET name='$nameE',vlan_id=$vlan_id,router_id=$router_id,trunk_interface='$trunkE',bridge_name='$bridgeE',is_enabled=$is_enabled,notes='$notesE',pppoe_pool_name='$poolNameE',pppoe_pool_range='$poolRangeE',pppoe_local_ip='$localIpE',pppoe_service='$serviceE',pppoe_server_name='$serverNameE' WHERE id=$id");
      $msg='تم تحديث القطاع.';
    } else {
      $conn->query("INSERT INTO sectors(name,vlan_id,router_id,trunk_interface,bridge_name,is_enabled,notes,pppoe_pool_name,pppoe_pool_range,pppoe_local_ip,pppoe_service,pppoe_server_name) VALUES('$nameE',$vlan_id,$router_id,'$trunkE','$bridgeE',$is_enabled,'$notesE','$poolNameE','$poolRangeE','$localIpE','$serviceE','$serverNameE')");
      $msg='تمت إضافة القطاع.';
    }
  }
}

if($action==='delete_sector'){
  $id=intval($_POST['id'] ?? 0);
  if($id>0){ $conn->query("DELETE FROM sectors WHERE id=$id"); $msg='تم حذف القطاع.'; }
}

if($action==='suggest_pool'){
  $id=intval($_POST['id'] ?? 0);
  $sector=null;
  $r=$conn->query("SELECT * FROM sectors WHERE id=$id LIMIT 1");
  if($r && $r->num_rows){ $sector=$r->fetch_assoc(); }
  if(!$sector){ $msg_type='danger'; $msg='القطاع غير موجود.'; }
  else{
    $plan = comms_suggest_pool_for_vlan(intval($sector['vlan_id']));
    comms_update_sector_pool($conn,$id,$plan);
    $msg_type='success';
    $msg='تم اقتراح وتجهيز Pool/Local IP تلقائياً لهذا القطاع. يمكنك تعديلها إن رغبت.';
  }
}

if($action==='apply_sector'){
  $id=intval($_POST['id'] ?? 0);
  $sector=null;
  $r=$conn->query("SELECT * FROM sectors WHERE id=$id LIMIT 1");
  if($r && $r->num_rows){ $sector=$r->fetch_assoc(); }
  if(!$sector){ $msg_type='danger'; $msg='القطاع غير موجود.'; }
  else{
    $router = comms_get_router($conn, intval($sector['router_id']));
    if(!$router){ $msg_type='danger'; $msg='الراوتر غير موجود.'; }
    else{
      $payload = [
        'router_id'=>intval($router['id']),
        'vlan_id'=>intval($sector['vlan_id']),
        'trunk'=>$sector['trunk_interface'],
        'bridge'=>$sector['bridge_name'],
        'enabled'=>intval($sector['is_enabled']),
        'pool_name'=>$sector['pppoe_pool_name'] ?? '',
        'pool_range'=>$sector['pppoe_pool_range'] ?? '',
        'local_ip'=>$sector['pppoe_local_ip'] ?? ''
      ];
      $user_id = $_SESSION['user_id'] ?? null;
      $res = comms_action_once($conn, 'apply_sector_'.$id, $payload, $user_id, function() use ($conn,$router,$sector){
        $err='';
        // تطبيق VLAN + Pool + PPPoE per VLAN
        return comms_apply_sector_pppoe($conn,$router,$sector,$err);
      });
      if(!empty($res['ok'])){
        $msg_type = !empty($res['skipped']) ? 'warning' : 'success';
        $msg = $res['msg'] ?? ($res['skipped']?'تم التخطي':'تم.');
      } else {
        $msg_type='danger'; $msg=$res['msg'] ?? 'فشل غير معروف.';
      }
    }
  }
}

$edit_id=intval($_GET['edit'] ?? 0);
$edit=null;
if($edit_id){
  $r=$conn->query("SELECT * FROM sectors WHERE id=$edit_id LIMIT 1");
  if($r && $r->num_rows) $edit=$r->fetch_assoc();
}

$routers = comms_get_routers($conn);
$sectors=[];
$r=$conn->query("SELECT s.*, r.name AS router_name FROM sectors s LEFT JOIN routers r ON r.id=s.router_id ORDER BY s.id ASC");
if($r) while($row=$r->fetch_assoc()) $sectors[]=$row;

$sector_total = count($sectors);
$sector_enabled = 0;
$sector_with_pool = 0;
$sector_vlan_max = 0;
foreach ($sectors as $s) {
  if (!empty($s['is_enabled'])) $sector_enabled++;
  if (trim((string)($s['pppoe_pool_range'] ?? '')) !== '') $sector_with_pool++;
  $sector_vlan_max = max($sector_vlan_max, intval($s['vlan_id'] ?? 0));
}

if ($uaAndroidSectors) {
  require __DIR__ . '/android_sectors.php';
  require_once __DIR__ . '/footer.php';
  exit;
}

$active_tab = 'sectors';
?>
<div class="content-wrapper ua-manual-page ua-network-admin-page ua-network-sectors ua-u-rtl-right" dir="rtl">
  <section class="content-header ua-net-hero">
    <div class="ua-net-hero__main">
      <span class="ua-net-kicker"><i class="fa fa-sitemap"></i> VLAN / PPPoE</span>
    <h1 class="ua-u-text-right">إدارة القطاعات VLAN</h1>
    <p class="text-muted">كل قطاع = VLAN. يدعم Pool مختلف لكل VLAN + PPPoE Server لكل VLAN. زر "تطبيق" ينفّذ Ensure ويمنع التكرار.</p>
    </div>
    <div class="ua-net-hero__actions">
      <a class="ua-net-action" href="routers.php"><i class="fa fa-server"></i><span>Routers</span></a>
      <a class="ua-net-action ua-net-action--ghost" href="wizard_network.php"><i class="fa fa-magic"></i><span>Wizard</span></a>
    </div>
  </section>

  <section class="content">
    <?php if($msg): ?>
      <div class="alert alert-<?=h($msg_type)?>"><?=h($msg)?></div>
    <?php endif; ?>

    <div class="box box-primary ua-net-panel ua-sector-form-strip">
      <div class="box-header with-border">
        <h3 class="box-title"><?= $edit ? 'تعديل قطاع' : 'إضافة قطاع' ?></h3>
        <span class="ua-sector-pool-hint">يمكن ترك حقول PPPoE Pool فارغة ثم استخدام «اقتراح Pool» من الجدول.</span>
      </div>
      <div class="box-body">
        <form method="post" class="ua-net-form ua-sector-inline-form">
          <input type="hidden" name="action" value="save_sector">
          <input type="hidden" name="id" value="<?=h($edit['id'] ?? 0)?>">
          <div class="form-group"><label>اسم القطاع</label><input class="form-control" name="name" value="<?=h($edit['name'] ?? '')?>" placeholder="Tower1 - SectorA"></div>
          <div class="form-group"><label>VLAN ID</label><input class="form-control" name="vlan_id" value="<?=h($edit['vlan_id'] ?? '')?>" placeholder="10"></div>
          <div class="form-group">
            <label>الراوتر (غالباً PPPoE)</label>
            <select class="form-control" name="router_id">
              <option value="">-- اختر --</option>
              <?php foreach($routers as $r): ?>
                <?php $sel = (($edit['router_id'] ?? 0)==$r['id']) ? 'selected' : ''; ?>
                <option value="<?=h($r['id'])?>" <?=$sel?>><?=h($r['name'])?> (<?=h($r['role'])?>)</option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group"><label>Trunk Interface</label><input class="form-control" name="trunk_interface" value="<?=h($edit['trunk_interface'] ?? 'ether2')?>"></div>
          <div class="form-group"><label>Bridge Name</label><input class="form-control" name="bridge_name" value="<?=h($edit['bridge_name'] ?? 'bridge-pppoe')?>"></div>
          <div class="form-group"><label>PPPoE Pool Name</label><input class="form-control" name="pppoe_pool_name" value="<?=h($edit['pppoe_pool_name'] ?? '')?>" placeholder="pool_vlan10"></div>
          <div class="form-group"><label>PPPoE Pool Range</label><input class="form-control" name="pppoe_pool_range" value="<?=h($edit['pppoe_pool_range'] ?? '')?>" placeholder="10.10.10.2-10.10.10.254"></div>
          <div class="form-group"><label>PPPoE Local Address</label><input class="form-control" name="pppoe_local_ip" value="<?=h($edit['pppoe_local_ip'] ?? '')?>" placeholder="10.10.10.1"></div>
          <div class="form-group"><label>PPPoE Server Name</label><input class="form-control" name="pppoe_server_name" value="<?=h($edit['pppoe_server_name'] ?? '')?>" placeholder="pppoe_vlan10"></div>
          <div class="form-group"><label>Service Name</label><input class="form-control" name="pppoe_service" value="<?=h($edit['pppoe_service'] ?? '')?>" placeholder="ISP-VLAN10"></div>
          <div class="form-group ua-sector-enabled-field"><label><input type="checkbox" name="is_enabled" <?=(!isset($edit) || ($edit['is_enabled'] ?? 1) ? 'checked':'')?> > مفعل</label></div>
          <div class="form-group ua-sector-notes-field"><label>ملاحظات</label><textarea class="form-control" name="notes" rows="1"><?=h($edit['notes'] ?? '')?></textarea></div>
          <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> حفظ</button>
          <?php if($edit): ?><a class="btn btn-default ua-sector-cancel" href="sectors.php">إلغاء</a><?php endif; ?>
        </form>
      </div>
    </div>

    <div class="ua-net-stats" aria-label="Network sector summary">
      <div class="ua-net-stat"><i class="fa fa-sitemap"></i><span>Sectors</span><strong><?=h((string)$sector_total)?></strong></div>
      <div class="ua-net-stat is-green"><i class="fa fa-check-circle"></i><span>Enabled</span><strong><?=h((string)$sector_enabled)?></strong></div>
      <div class="ua-net-stat is-cyan"><i class="fa fa-database"></i><span>With Pool</span><strong><?=h((string)$sector_with_pool)?></strong></div>
      <div class="ua-net-stat is-gold"><i class="fa fa-tag"></i><span>Max VLAN</span><strong><?=h((string)$sector_vlan_max)?></strong></div>
    </div>

    <div class="row ua-net-layout">
      <div class="col-md-12">
        <div class="box box-info ua-net-panel">
          <div class="box-header with-border"><h3 class="box-title">القطاعات</h3></div>
          <div class="box-body table-responsive">
            <table class="table table-bordered table-striped ua-net-table">
              <thead>
                <tr>
                  <th>#</th><th>الاسم</th><th>VLAN</th><th>الراوتر</th><th>Trunk</th><th>Bridge</th><th>الحالة</th><th>إجراءات</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($sectors as $s): ?>
                  <tr>
                    <td><?=h($s['id'])?></td>
                    <td><?=h($s['name'])?></td>
                    <td><?=h($s['vlan_id'])?></td>
                    <td><?=h($s['router_name'] ?? '-')?></td>
                    <td><?=h($s['trunk_interface'])?></td>
                    <td><?=h($s['bridge_name'])?></td>
                    <td><?=($s['is_enabled']?'مفعل':'متوقف')?></td>
                    <td class="ua-net-actions ua-u-nowrap">
                      <a class="btn btn-xs btn-warning" href="sectors.php?edit=<?=h($s['id'])?>">تعديل</a>
                      <form class="ua-u-inline" method="post" onsubmit="return confirm('حذف القطاع؟');">
                        <input type="hidden" name="action" value="delete_sector">
                        <input type="hidden" name="id" value="<?=h($s['id'])?>">
                        <button class="btn btn-xs btn-danger" type="submit">حذف</button>
                      </form>
                      <form class="ua-u-inline" method="post">
                        <input type="hidden" name="action" value="apply_sector">
                        <input type="hidden" name="id" value="<?=h($s['id'])?>">
                        <button class="btn btn-xs btn-success" type="submit">تطبيق</button>
                      </form>
                      <form class="ua-u-inline" method="post">
                        <input type="hidden" name="action" value="suggest_pool">
                        <input type="hidden" name="id" value="<?=h($s['id'])?>">
                        <button class="btn btn-xs btn-info" type="submit">اقتراح Pool</button>
                      </form>
                    </td>
                  </tr>
                <?php endforeach; ?>
                <?php if(count($sectors)==0): ?>
                  <tr><td colspan="8" class="text-center text-muted">لا يوجد قطاعات بعد.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
