<?php
$page_title = 'السرعات والباقات';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/mikrotik_lib.php';
require_once __DIR__ . '/subscriber_plan_schema.php';

require_login();
if (function_exists('require_perm')) @require_perm('can_manage_settings');
if (function_exists('ensure_db')) ensure_db(true);
$conn = $GLOBALS['conn'] ?? null;
if (!($conn instanceof mysqli)) {
  http_response_code(500);
  die('Database connection error');
}
mysqli_report(MYSQLI_REPORT_OFF);
subscriber_plan_ensure_schema($conn);

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

function pp_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function pp_fetch_speed(mysqli $conn, int $id): ?array {
  $stmt = $conn->prepare("SELECT * FROM speeds WHERE id=? LIMIT 1");
  if (!$stmt) return null;
  $stmt->bind_param('i', $id);
  if (!$stmt->execute()) { $stmt->close(); return null; }
  $res = $stmt->get_result();
  $row = $res ? $res->fetch_assoc() : null;
  $stmt->close();
  return $row ?: null;
}

function pp_fetch_package(mysqli $conn, int $id): ?array {
  $stmt = $conn->prepare("SELECT * FROM packages WHERE id=? LIMIT 1");
  if (!$stmt) return null;
  $stmt->bind_param('i', $id);
  if (!$stmt->execute()) { $stmt->close(); return null; }
  $res = $stmt->get_result();
  $row = $res ? $res->fetch_assoc() : null;
  $stmt->close();
  return $row ?: null;
}

$editSpeedId = (int)($_GET['edit_speed'] ?? 0);
$editPackageId = (int)($_GET['edit_package'] ?? 0);
$editingSpeed = $editSpeedId > 0 ? pp_fetch_speed($conn, $editSpeedId) : null;
$editingPackage = $editPackageId > 0 ? pp_fetch_package($conn, $editPackageId) : null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = trim((string)($_POST['action'] ?? ''));

  if ($action === 'save_speed') {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim((string)($_POST['speed_name'] ?? ''));
    $upload = (float)($_POST['upload_rate'] ?? 0);
    $download = (float)($_POST['download_rate'] ?? 0);
    $unit = sp_normalize_unit((string)($_POST['rate_unit'] ?? 'M'));
    $price = (float)($_POST['price'] ?? 0);
    $profile = trim((string)($_POST['mikrotik_profile'] ?? ''));

    if ($upload <= 0 || $download <= 0) {
      $err = 'الرجاء إدخال سرعة رفع وتحميل أكبر من صفر.';
    } else {
      if ($name === '') $name = sp_default_speed_name($upload, $download, $unit);
      $rateLimit = sp_format_rate_limit($upload, $download, $unit);
      if ($profile === '') $profile = sp_default_profile_name($upload, $download, $unit);

      if ($id > 0) {
        $stmt = $conn->prepare("UPDATE speeds SET speed_name=?, upload_rate=?, download_rate=?, rate_unit=?, price=?, mikrotik_profile=?, rate_limit=? WHERE id=? LIMIT 1");
        if (!$stmt) {
          $err = 'فشل تجهيز تعديل السرعة: ' . $conn->error;
        } else {
          $stmt->bind_param('sddsdssi', $name, $upload, $download, $unit, $price, $profile, $rateLimit, $id);
          $ok = $stmt->execute();
          $stmt->close();
          if (!$ok) $err = 'فشل تعديل السرعة: ' . $conn->error;
          else $msg = 'تم تعديل السرعة بنجاح.';
        }
      } else {
        $stmt = $conn->prepare("INSERT INTO speeds (speed_name, upload_rate, download_rate, rate_unit, price, mikrotik_profile, rate_limit) VALUES (?,?,?,?,?,?,?)");
        if (!$stmt) {
          $err = 'فشل تجهيز إضافة السرعة: ' . $conn->error;
        } else {
          $stmt->bind_param('sddsdss', $name, $upload, $download, $unit, $price, $profile, $rateLimit);
          $ok = $stmt->execute();
          $stmt->close();
          if (!$ok) $err = 'فشل إضافة السرعة: ' . $conn->error;
          else $msg = 'تمت إضافة السرعة بنجاح.';
        }
      }
      if (!$err) {
        $mtOk = mt_ppp_profile_ensure($conn, $profile, $rateLimit);
        if (!$mtOk) {
          $warn = 'تم حفظ السرعة في البرنامج لكن لم يتم إنشاء/تحديث بروفايل MikroTik: ' . (string)($GLOBALS['mt_last_error'] ?? '');
        }
      }
    }
  }

  if ($action === 'delete_speed') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $row = pp_fetch_speed($conn, $id);
      if (!$row) {
        $err = 'السرعة غير موجودة.';
      } else {
        $nameEsc = $conn->real_escape_string((string)($row['speed_name'] ?? ''));
        $used = false;
        $r1 = $conn->query("SELECT id FROM subscribers WHERE (speed_name='$nameEsc' OR speed='$nameEsc') AND COALESCE(is_deleted,0)=0 LIMIT 1");
        if ($r1 && $r1->num_rows > 0) $used = true;
        if ($used) {
          $err = 'لا يمكن حذف السرعة لأنها مستخدمة من مشتركين.';
        } else {
          @ $conn->query("DELETE FROM speeds WHERE id=".(int)$id." LIMIT 1");
          $msg = 'تم حذف السرعة.';
        }
      }
    }
  }

  if ($action === 'save_package') {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim((string)($_POST['package_name'] ?? ''));
    $quotaGb = trim((string)($_POST['quota_gb'] ?? ''));
    $quotaVal = ($quotaGb === '') ? null : (int)$quotaGb;
    $price = (float)($_POST['price'] ?? 0);
    $subscriptionFee = (float)($_POST['subscription_fee'] ?? 0);
    $validity = max(1, (int)($_POST['validity_days'] ?? 30));

    if ($name === '') {
      $err = 'اسم الباقة مطلوب.';
    } else {
      if ($id > 0) {
        $stmt = $conn->prepare("UPDATE packages SET package_name=?, price=?, subscription_fee=?, quota_gb=?, validity_days=?, speed_id=NULL WHERE id=? LIMIT 1");
        if (!$stmt) {
          $err = 'فشل تجهيز تعديل الباقة: ' . $conn->error;
        } else {
          $stmt->bind_param('sddiii', $name, $price, $subscriptionFee, $quotaVal, $validity, $id);
          $ok = $stmt->execute();
          $stmt->close();
          if (!$ok) $err = 'فشل تعديل الباقة: ' . $conn->error;
          else $msg = 'تم تعديل الباقة بنجاح.';
        }
      } else {
        $stmt = $conn->prepare("INSERT INTO packages (package_name, price, subscription_fee, quota_gb, validity_days, speed_id) VALUES (?,?,?,?,?,NULL)");
        if (!$stmt) {
          $err = 'فشل تجهيز إضافة الباقة: ' . $conn->error;
        } else {
          $stmt->bind_param('sddii', $name, $price, $subscriptionFee, $quotaVal, $validity);
          $ok = $stmt->execute();
          $stmt->close();
          if (!$ok) $err = 'فشل إضافة الباقة: ' . $conn->error;
          else $msg = 'تمت إضافة الباقة بنجاح.';
        }
      }
    }
  }

  if ($action === 'delete_package') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
      $row = pp_fetch_package($conn, $id);
      if (!$row) {
        $err = 'الباقة غير موجودة.';
      } else {
        $nameEsc = $conn->real_escape_string((string)($row['package_name'] ?? ''));
        $used = false;
        $r1 = $conn->query("SELECT id FROM subscribers WHERE (package_name='$nameEsc' OR package='$nameEsc') AND COALESCE(is_deleted,0)=0 LIMIT 1");
        if ($r1 && $r1->num_rows > 0) $used = true;
        if ($used) {
          $err = 'لا يمكن حذف الباقة لأنها مستخدمة من مشتركين.';
        } else {
          @ $conn->query("DELETE FROM packages WHERE id=".(int)$id." LIMIT 1");
          $msg = 'تم حذف الباقة.';
        }
      }
    }
  }

  $editSpeedId = 0;
  $editPackageId = 0;
  $editingSpeed = null;
  $editingPackage = null;
}

if ($editSpeedId > 0) $editingSpeed = pp_fetch_speed($conn, $editSpeedId);
if ($editPackageId > 0) $editingPackage = pp_fetch_package($conn, $editPackageId);

$speeds = [];
$rs = $conn->query("SELECT id, speed_name, upload_rate, download_rate, rate_unit, price, mikrotik_profile, rate_limit FROM speeds ORDER BY id DESC");
if ($rs) while ($r = $rs->fetch_assoc()) $speeds[] = $r;

$packages = [];
$rp = $conn->query("SELECT id, package_name, price, subscription_fee, quota_gb, validity_days FROM packages ORDER BY id DESC");
if ($rp) while ($r = $rp->fetch_assoc()) $packages[] = $r;

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidPackagesPrices = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidPackagesPrices) $UA_PAGE_CSS = ['assets/css/android_packages_prices.css'];
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
if ($uaAndroidPackagesPrices) { require __DIR__ . '/android_packages_prices.php'; require_once __DIR__ . '/footer.php'; return; }
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content">
    <div class="container-fluid sp-wrap">
      <div class="sp-head">
        <div>
          <h1>السرعات والباقات</h1>
          <p>السرعة = رفع/تحميل وتُنشئ بروفايل MikroTik تلقائيًا. الباقة = حجم الاستهلاك ورسوم الاشتراك لأول مرة.</p>
        </div>
        <div class="d-flex gap-2 flex-wrap">
          <a href="subscribers_add.php" class="btn btn-success btn-sm"><i class="fa fa-user-plus"></i> إضافة مشترك</a>
          <a href="invoices_generate_month.php" class="btn btn-outline-secondary btn-sm"><i class="fa fa-refresh"></i> توليد فواتير الشهر</a>
        </div>
      </div>

      <?php if($msg): ?><div class="alert alert-success"><?= pp_h($msg) ?></div><?php endif; ?>
      <?php if($warn): ?><div class="alert alert-warning"><?= pp_h($warn) ?></div><?php endif; ?>
      <?php if($err): ?><div class="alert alert-danger"><?= pp_h($err) ?></div><?php endif; ?>

      <div class="sp-grid">
        <div class="sp-card card">
          <div class="card-header">
            <h3 class="mb-1"><?= $editingSpeed ? 'تعديل سرعة' : 'إضافة سرعة جديدة' ?></h3>
            <div class="sp-mini">التقيد يُبنى تلقائيًا مثل 2M/4M، وإذا كان البروفايل موجودًا على MikroTik يتم تحديثه.</div>
          </div>
          <div class="card-body">
            <form method="post" class="sp-form">
              <input type="hidden" name="action" value="save_speed">
              <input type="hidden" name="id" value="<?= (int)($editingSpeed['id'] ?? 0) ?>">
              <div>
                <label>اسم السرعة</label>
                <input class="form-control" name="speed_name" value="<?= pp_h($editingSpeed['speed_name'] ?? '') ?>" placeholder="مثال: 2M أو 2M / 4M">
              </div>
              <div>
                <label>رفع</label>
                <input class="form-control" type="number" step="0.01" min="0.01" name="upload_rate" value="<?= pp_h($editingSpeed['upload_rate'] ?? '') ?>" required>
              </div>
              <div>
                <label>تحميل</label>
                <input class="form-control" type="number" step="0.01" min="0.01" name="download_rate" value="<?= pp_h($editingSpeed['download_rate'] ?? '') ?>" required>
              </div>
              <div>
                <label>الوحدة</label>
                <?php $u = sp_normalize_unit((string)($editingSpeed['rate_unit'] ?? 'M')); ?>
                <select class="form-control" name="rate_unit">
                  <option value="K" <?= $u==='K'?'selected':'' ?>>K</option>
                  <option value="M" <?= $u==='M'?'selected':'' ?>>M</option>
                  <option value="G" <?= $u==='G'?'selected':'' ?>>G</option>
                </select>
              </div>
              <div>
                <label>السعر الشهري</label>
                <input class="form-control" type="number" step="0.01" min="0" name="price" value="<?= pp_h($editingSpeed['price'] ?? '0') ?>">
              </div>
              <div>
                <label>اسم بروفايل MikroTik</label>
                <input class="form-control" name="mikrotik_profile" value="<?= pp_h($editingSpeed['mikrotik_profile'] ?? '') ?>" placeholder="فارغ = توليد تلقائي">
              </div>
              <div class="full d-flex gap-2 flex-wrap">
                <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> <?= $editingSpeed ? 'حفظ التعديل' : 'إضافة السرعة' ?></button>
                <?php if($editingSpeed): ?><a class="btn btn-outline-secondary" href="packages_prices.php">إلغاء التعديل</a><?php endif; ?>
              </div>
            </form>
          </div>
        </div>

        <div class="sp-card card">
          <div class="card-header">
            <h3 class="mb-1"><?= $editingPackage ? 'تعديل باقة' : 'إضافة باقة جديدة' ?></h3>
            <div class="sp-mini">الباقة = حجم الاستهلاك فقط، ويمكن للمشترك شراء باقة إضافية لاحقًا عند انتهاء الاستهلاك.</div>
          </div>
          <div class="card-body">
            <form method="post" class="sp-form">
              <input type="hidden" name="action" value="save_package">
              <input type="hidden" name="id" value="<?= (int)($editingPackage['id'] ?? 0) ?>">
              <div>
                <label>اسم الباقة</label>
                <input class="form-control" name="package_name" value="<?= pp_h($editingPackage['package_name'] ?? '') ?>" placeholder="مثال: 50 GB" required>
              </div>
              <div>
                <label>الحجم GB</label>
                <input class="form-control" type="number" min="0" name="quota_gb" value="<?= pp_h($editingPackage['quota_gb'] ?? '') ?>" placeholder="فارغ = مفتوح">
              </div>
              <div>
                <label>السعر</label>
                <input class="form-control" type="number" step="0.01" min="0" name="price" value="<?= pp_h($editingPackage['price'] ?? '0') ?>" required>
              </div>
              <div>
                <label>رسوم الاشتراك</label>
                <input class="form-control" type="number" step="0.01" min="0" name="subscription_fee" value="<?= pp_h($editingPackage['subscription_fee'] ?? '0') ?>">
              </div>
              <div>
                <label>مدة الفاتورة / يوم</label>
                <input class="form-control" type="number" min="1" name="validity_days" value="<?= pp_h($editingPackage['validity_days'] ?? '30') ?>">
              </div>
              <div class="full d-flex gap-2 flex-wrap">
                <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> <?= $editingPackage ? 'حفظ التعديل' : 'إضافة الباقة' ?></button>
                <?php if($editingPackage): ?><a class="btn btn-outline-secondary" href="packages_prices.php">إلغاء التعديل</a><?php endif; ?>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div class="sp-grid mt-3">
        <div class="sp-card card">
          <div class="card-header"><h3 class="mb-0">السرعات الحالية</h3></div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-sm table-bordered mb-0 sp-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>الاسم</th>
                    <th>رفع</th>
                    <th>تحميل</th>
                    <th>التقيد</th>
                    <th>البروفايل</th>
                    <th>السعر</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <?php if(empty($speeds)): ?><tr><td colspan="8" class="text-center text-muted py-3">لا توجد سرعات بعد.</td></tr><?php endif; ?>
                  <?php foreach($speeds as $s): ?>
                    <tr>
                      <td><?= (int)$s['id'] ?></td>
                      <td><?= pp_h($s['speed_name']) ?></td>
                      <td><?= pp_h(sp_format_rate_value($s['upload_rate'] ?? 0, (string)($s['rate_unit'] ?? 'M'))) ?></td>
                      <td><?= pp_h(sp_format_rate_value($s['download_rate'] ?? 0, (string)($s['rate_unit'] ?? 'M'))) ?></td>
                      <td><?= pp_h($s['rate_limit']) ?></td>
                      <td><?= pp_h($s['mikrotik_profile']) ?></td>
                      <td><?= number_format((float)($s['price'] ?? 0), 2) ?></td>
                      <td class="text-nowrap">
                        <a class="btn btn-sm btn-outline-primary" href="packages_prices.php?edit_speed=<?= (int)$s['id'] ?>">تعديل</a>
                        <form method="post" class="ua-u-inline" onsubmit="return confirm('حذف السرعة؟')">
                          <input type="hidden" name="action" value="delete_speed">
                          <input type="hidden" name="id" value="<?= (int)$s['id'] ?>">
                          <button class="btn btn-sm btn-outline-danger">حذف</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="sp-card card">
          <div class="card-header"><h3 class="mb-0">الباقات الحالية</h3></div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-sm table-bordered mb-0 sp-table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>اسم الباقة</th>
                    <th>الحجم</th>
                    <th>السعر</th>
                    <th>رسوم الاشتراك</th>
                    <th>المدة</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <?php if(empty($packages)): ?><tr><td colspan="7" class="text-center text-muted py-3">لا توجد باقات بعد.</td></tr><?php endif; ?>
                  <?php foreach($packages as $p): ?>
                    <tr>
                      <td><?= (int)$p['id'] ?></td>
                      <td><?= pp_h($p['package_name']) ?></td>
                      <td><?= ($p['quota_gb'] === null || $p['quota_gb'] === '') ? 'مفتوح' : ((int)$p['quota_gb'] . ' GB') ?></td>
                      <td><?= number_format((float)($p['price'] ?? 0), 2) ?></td>
                      <td><?= number_format((float)($p['subscription_fee'] ?? 0), 2) ?></td>
                      <td><?= (int)($p['validity_days'] ?? 0) ?> يوم</td>
                      <td class="text-nowrap">
                        <a class="btn btn-sm btn-outline-primary" href="packages_prices.php?edit_package=<?= (int)$p['id'] ?>">تعديل</a>
                        <form method="post" class="ua-u-inline" onsubmit="return confirm('حذف الباقة؟')">
                          <input type="hidden" name="action" value="delete_package">
                          <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                          <button class="btn btn-sm btn-outline-danger">حذف</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
