<?php

$page_title = 'إدارة المعتمدين';
$UA_FORCE_DESIGN_V2 = true;

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/agent_service.php';
require_once __DIR__ . '/install_link_lib.php';

require_login();
$conn = ensure_db(true);
if (function_exists('require_any_perm')) require_any_perm(['can_edit_agents','can_manage_agents']);
ua_agent_schema_migrate($conn);
ua_link_ensure_schema($conn);

$actorId = (int)($_SESSION['admin_id'] ?? $_SESSION['admin_user_id'] ?? 0);
$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!ua_csrf_verify()) {
    $err = 'انتهت صلاحية الطلب. أعد تحميل الصفحة وحاول مجدداً.';
  } else {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'save') {
      $agentId = (int)($_POST['id'] ?? 0);
      $linkedInstance = trim((string)($_POST['linked_instance_id'] ?? ''));
      if ($linkedInstance !== '') {
        $instanceEsc = $conn->real_escape_string($linkedInstance);
        $validLink = @$conn->query("SELECT id FROM ua_link_requests WHERE instance_id='{$instanceEsc}' AND install_type='agent' AND status='approved' LIMIT 1");
        if (!$validLink || !$validLink->num_rows) $err = 'النسخة المحددة ليست نسخة معتمد معتمدة.';
        $used = @$conn->query("SELECT id FROM agents WHERE linked_instance_id='{$instanceEsc}' AND archived_at IS NULL AND id<>{$agentId} LIMIT 1");
        if (!$err && $used && $used->num_rows) $err = 'هذه النسخة مرتبطة بمعتمد آخر.';
      }
      if (!$err) {
        $result = ua_agent_service_save($conn, $_POST, ['type'=>'admin','id'=>$actorId]);
        if ($result['ok']) {
          $msg = $agentId > 0 ? 'تم تحديث بيانات المعتمد.' : 'تمت إضافة المعتمد.';
          $_GET['edit'] = (int)$result['id'];
        } else {
          $err = (string)$result['error'];
        }
      }
    } elseif ($action === 'archive') {
      $agentId = (int)($_POST['id'] ?? 0);
      if (ua_agent_repo_archive($conn, $agentId, $actorId)) {
        ua_agent_activity_add($conn, [
          'agent_id'=>$agentId,
          'event_type'=>'AGENT_ARCHIVED',
          'summary'=>'تمت أرشفة المعتمد وتعطيل الوصول.',
          'actor_type'=>'admin',
          'actor_id'=>$actorId,
        ]);
        $msg = 'تمت أرشفة المعتمد مع الاحتفاظ بجميع حركاته.';
      } else {
        $err = 'تعذر أرشفة المعتمد.';
      }
    }
  }
}

$editId = (int)($_GET['edit'] ?? 0);
$editing = $editId > 0 ? ua_agent_repo_get($conn, $editId) : null;
$q = trim((string)($_GET['q'] ?? ''));
$activeFilter = isset($_GET['active']) ? (string)$_GET['active'] : '';
$agents = ua_agent_repo_list($conn, ['q'=>$q,'active'=>$activeFilter]);
$links = [];
$linkRs = @$conn->query("SELECT instance_id,instance_name,last_seen_at FROM ua_link_requests WHERE install_type='agent' AND status='approved' ORDER BY instance_name,instance_id");
if ($linkRs) while ($row = $linkRs->fetch_assoc()) $links[] = $row;

$uaAndroidAgents = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAgents) $UA_PAGE_CSS = ['assets/css/android_agents.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
if ($uaAndroidAgents) {
  require __DIR__ . '/android_agents.php';
  include __DIR__ . '/footer.php';
  return;
}
?>
<div class="content-wrapper ua-extracted-page ua-agents-page">
  <section class="content-header">
    <div class="container-fluid">
      <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div><h1 class="mb-1">إدارة المعتمدين</h1><div class="text-muted">الملف الشخصي، الوصول، الربط، والحد المالي</div></div>
        <a class="btn btn-primary ua-agent-icon-btn" href="agents.php" title="معتمد جديد" aria-label="معتمد جديد"><i class="fa fa-plus"></i></a>
      </div>
      <?php include __DIR__ . '/agents_nav.php'; ?>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
      <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

      <div class="ua-agent-management-stack">
        <div class="card ua-agent-form-card">
            <div class="card-header ua-agent-card-heading">
              <div class="ua-agent-card-title"><i class="fa <?= $editing ? 'fa-pencil' : 'fa-user-plus' ?>"></i><div><strong><?= $editing ? 'تعديل المعتمد' : 'إضافة معتمد' ?></strong><small><?= $editing ? 'تحديث البيانات والوصول والربط المالي' : 'إنشاء ملف معتمد وربطه بالنظام' ?></small></div></div>
              <?php if ($editing): ?><span class="ua-agent-edit-chip"><?= h($editing['code'] ?? '') ?></span><?php endif; ?>
            </div>
            <form method="post" autocomplete="off">
              <div class="card-body">
                <?php ua_csrf_field(); ?>
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= (int)($editing['id'] ?? 0) ?>">
                <div class="ua-agent-editor-grid">
                  <div class="ua-agent-form-section-title"><i class="fa fa-id-card-o"></i><span>البيانات الشخصية والتواصل</span></div>
                  <div class="form-group"><label>الرمز</label><input class="form-control" name="code" value="<?= h($editing['code'] ?? '') ?>" placeholder="AG-001"></div>
                  <div class="form-group ua-span-2"><label>الاسم الكامل *</label><input class="form-control" required name="full_name" value="<?= h($editing['full_name'] ?? $editing['name'] ?? '') ?>"></div>
                  <div class="form-group"><label>الرقم الوطني</label><input class="form-control" name="national_id" value="<?= h($editing['national_id'] ?? '') ?>"></div>
                  <div class="form-group"><label>المنطقة</label><input class="form-control" name="area" value="<?= h($editing['area'] ?? '') ?>"></div>
                  <div class="form-group"><label>الهاتف</label><input class="form-control" name="phone" value="<?= h($editing['phone'] ?? '') ?>"></div>
                  <div class="form-group"><label>هاتف بديل</label><input class="form-control" name="phone_alt" value="<?= h($editing['phone_alt'] ?? '') ?>"></div>
                  <div class="form-group"><label>البريد الإلكتروني</label><input class="form-control" type="email" name="email" value="<?= h($editing['email'] ?? '') ?>"></div>
                  <div class="form-group ua-span-2"><label>العنوان</label><input class="form-control" name="address" value="<?= h($editing['address'] ?? '') ?>"></div>

                  <div class="ua-agent-form-section-title"><i class="fa fa-key"></i><span>الوصول والربط</span></div>
                  <div class="form-group"><label>اسم المستخدم *</label><input class="form-control" required name="username" value="<?= h($editing['username'] ?? '') ?>"></div>
                  <div class="form-group"><label><?= $editing ? 'كلمة مرور جديدة' : 'كلمة المرور' ?></label><input class="form-control" type="password" name="password" <?= $editing ? '' : 'required' ?>></div>
                  <div class="form-group"><label><?= $editing ? 'PIN جديد' : 'PIN' ?></label><input class="form-control" type="password" name="pin" inputmode="numeric"></div>
                  <div class="form-group"><label>نسخة المعتمد المرتبطة</label><select class="form-control" name="linked_instance_id"><option value="">بدون ربط</option><?php foreach ($links as $link): ?><option value="<?= h($link['instance_id']) ?>" <?= (($editing['linked_instance_id'] ?? '') === $link['instance_id']) ? 'selected' : '' ?>><?= h(($link['instance_name'] ?: $link['instance_id']) . ' - ' . $link['instance_id']) ?></option><?php endforeach; ?></select></div>

                  <div class="ua-agent-form-section-title"><i class="fa fa-calculator"></i><span>العمولة والحد المالي</span></div>
                  <div class="form-group"><label>نوع العمولة</label><select class="form-control" name="commission_type"><?php foreach (['none'=>'بدون','fixed'=>'مبلغ ثابت','percent'=>'نسبة'] as $value=>$label): ?><option value="<?= $value ?>" <?= (($editing['commission_type'] ?? 'none') === $value) ? 'selected' : '' ?>><?= $label ?></option><?php endforeach; ?></select></div>
                  <div class="form-group"><label>قيمة العمولة</label><input class="form-control" type="number" step="0.01" min="0" name="commission_value" value="<?= h($editing['commission_value'] ?? '0') ?>"></div>
                  <div class="form-group"><label>حد الائتمان</label><input class="form-control" type="number" step="0.01" min="0" name="credit_limit" value="<?= h($editing['credit_limit'] ?? '') ?>" placeholder="فارغ = بلا حد"></div>
                  <div class="form-group"><label>ملاحظات</label><textarea class="form-control ua-agent-notes-control" name="notes" rows="1"><?= h($editing['notes'] ?? '') ?></textarea></div>
                </div>
              </div>
              <div class="card-footer ua-agent-editor-footer">
                <div class="ua-agent-switches">
                  <?php foreach (['is_active'=>'نشط','portal_enabled'=>'واجهة المعتمد','pos_enabled'=>'نقطة البيع'] as $field=>$label): ?>
                    <label><input type="checkbox" name="<?= $field ?>" value="1" <?= !isset($editing[$field]) || (int)$editing[$field] ? 'checked' : '' ?>> <span><?= $label ?></span></label>
                  <?php endforeach; ?>
                </div>
                <div class="ua-agent-editor-actions">
                  <?php if ($editing): ?><a class="btn btn-outline-secondary ua-agent-icon-btn" href="agents.php" title="إلغاء التعديل" aria-label="إلغاء التعديل"><i class="fa fa-times"></i></a><?php endif; ?>
                  <button class="btn btn-primary ua-agent-icon-btn" type="submit" title="حفظ المعتمد" aria-label="حفظ المعتمد"><i class="fa fa-save"></i></button>
                </div>
              </div>
            </form>
          </div>

          <div class="card ua-agent-list-card">
            <div class="card-header ua-agent-list-header">
              <div class="ua-agent-card-title"><i class="fa fa-users"></i><div><strong>المعتمدون</strong><small><?= count($agents) ?> نتيجة مطابقة</small></div></div>
              <form class="ua-agent-list-filter" method="get">
                <div class="ua-agent-filter-field ua-agent-filter-search"><label>بحث</label><input class="form-control" name="q" value="<?= h($q) ?>" placeholder="الاسم، الرمز، الهاتف، اسم المستخدم"></div>
                <div class="ua-agent-filter-field"><label>الحالة</label><select class="form-control" name="active"><option value="">الكل</option><option value="1" <?= $activeFilter === '1' ? 'selected' : '' ?>>نشط</option><option value="0" <?= $activeFilter === '0' ? 'selected' : '' ?>>موقوف</option></select></div>
                <?php if ($q !== '' || $activeFilter !== ''): ?><a class="btn btn-outline-secondary ua-agent-icon-btn" href="agents.php" title="مسح الفلاتر" aria-label="مسح الفلاتر"><i class="fa fa-times"></i></a><?php endif; ?>
                <button class="btn btn-outline-primary ua-agent-icon-btn" title="تطبيق البحث" aria-label="تطبيق البحث"><i class="fa fa-search"></i></button>
              </form>
            </div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-hover mb-0 ua-agents-table">
                  <thead><tr><th>المعتمد</th><th>التواصل</th><th>الربط</th><th>الرصيد المستحق</th><th>الحالة</th><th></th></tr></thead>
                  <tbody>
                  <?php if (!$agents): ?><tr><td colspan="6" class="text-center text-muted p-5">لا يوجد معتمدون مطابقون.</td></tr><?php endif; ?>
                  <?php foreach ($agents as $agent): ?>
                    <tr>
                      <td><strong><?= h($agent['full_name'] ?: $agent['name']) ?></strong><div class="small text-muted"><?= h($agent['code']) ?> · <?= h($agent['username']) ?></div></td>
                      <td><?= h($agent['phone'] ?: '-') ?><div class="small text-muted"><?= h($agent['area'] ?: $agent['email']) ?></div></td>
                      <td><?= $agent['linked_instance_id'] ? '<span class="badge badge-info">'.h($agent['linked_instance_id']).'</span>' : '<span class="text-muted">غير مرتبط</span>' ?></td>
                      <td class="ua-agent-balance"><?= number_format((float)$agent['balance_cached'], 2) ?></td>
                      <td><span class="badge <?= (int)$agent['is_active'] ? 'badge-success' : 'badge-secondary' ?>"><?= (int)$agent['is_active'] ? 'نشط' : 'موقوف' ?></span></td>
                      <td class="text-nowrap">
                        <a class="btn btn-sm btn-outline-primary" href="agents.php?edit=<?= (int)$agent['id'] ?>" title="تعديل"><i class="fa fa-pencil"></i></a>
                        <a class="btn btn-sm btn-outline-secondary" href="agents_portal_preview.php" title="معاينة واجهة المعتمد"><i class="fa fa-eye"></i></a>
                        <form method="post" class="d-inline" onsubmit="return confirm('أرشفة المعتمد وتعطيل دخوله؟');"><?php ua_csrf_field(); ?><input type="hidden" name="action" value="archive"><input type="hidden" name="id" value="<?= (int)$agent['id'] ?>"><button class="btn btn-sm btn-outline-danger" title="أرشفة"><i class="fa fa-archive"></i></button></form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
      </div>
    </div>
  </section>
</div>
<?php include __DIR__ . '/footer.php'; ?>

