<?php
/*
 * سجل المشترك - نفس منطق النسخة admin1 التي كان السجل يعمل عليها.
 * لا يقرأ من action_log ولا من Queue display layer، ولا يصالح مع MikroTik عند فتح السجل.
 * التسجيل يتم حصراً عبر subscriber_activity_log بنفس الدوال القديمة.
 */
if (!function_exists('sh_col_exists')) {
  function sh_col_exists(mysqli $conn, string $table, string $col): bool {
    static $cache = [];
    $key = $table.'|'.$col;
    if (array_key_exists($key, $cache)) return $cache[$key];
    $t = $conn->real_escape_string($table);
    $c = $conn->real_escape_string($col);
    $sql = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1";
    $rs = @$conn->query($sql);
    return $cache[$key] = ($rs && $rs->num_rows > 0);
  }
}

if (!function_exists('sh_table_exists')) {
  function sh_table_exists(mysqli $conn, string $table): bool {
    static $cache = [];
    if (array_key_exists($table, $cache)) return $cache[$table];
    $t = $conn->real_escape_string($table);
    $rs = @$conn->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1");
    return $cache[$table] = ($rs && $rs->num_rows > 0);
  }
}

if (!function_exists('sh_add_missing_col')) {
  function sh_add_missing_col(mysqli $conn, string $table, string $col, string $ddl): void {
    if (!sh_table_exists($conn, $table)) return;
    if (!sh_col_exists($conn, $table, $col)) {
      @mysqli_report(MYSQLI_REPORT_OFF);
      @$conn->query("ALTER TABLE `$table` ADD COLUMN $ddl");
    }
  }
}

if (!function_exists('sh_ensure_schema')) {
  function sh_ensure_schema(mysqli $conn): void {
    static $done = false;
    if ($done) return;
    $done = true;
    @mysqli_report(MYSQLI_REPORT_OFF);

    if (sh_table_exists($conn, 'subscribers')) {
      if (!sh_col_exists($conn, 'subscribers', 'registered_at')) {
        @$conn->query("ALTER TABLE subscribers ADD COLUMN registered_at DATETIME NULL DEFAULT NULL");
      }
      if (!sh_col_exists($conn, 'subscribers', 'first_activated_at')) {
        @$conn->query("ALTER TABLE subscribers ADD COLUMN first_activated_at DATETIME NULL DEFAULT NULL");
      }
    }

    @$conn->query("CREATE TABLE IF NOT EXISTS subscriber_activity_log (
      id INT UNSIGNED NOT NULL AUTO_INCREMENT,
      subscriber_id INT NOT NULL,
      username VARCHAR(191) NULL,
      action_key VARCHAR(64) NOT NULL,
      action_label VARCHAR(191) NOT NULL,
      details TEXT NULL,
      event_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (id),
      KEY idx_subscriber_event (subscriber_id, event_at),
      KEY idx_action_key (action_key)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    // توافق آمن فقط مع الجداول القديمة: نفس جدول admin1 لكن نضيف الناقص إن كان الجدول منشأ سابقاً ناقصاً.
    sh_add_missing_col($conn, 'subscriber_activity_log', 'subscriber_id', '`subscriber_id` INT NOT NULL DEFAULT 0');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'username', '`username` VARCHAR(191) NULL');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'action_key', '`action_key` VARCHAR(64) NOT NULL DEFAULT \'EVENT\'');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'action_label', '`action_label` VARCHAR(191) NOT NULL DEFAULT \'حركة\'');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'details', '`details` TEXT NULL');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'event_at', '`event_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP');
    sh_add_missing_col($conn, 'subscriber_activity_log', 'created_at', '`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP');

    if (sh_table_exists($conn, 'subscribers') && sh_col_exists($conn, 'subscribers', 'registered_at')) {
      if (sh_col_exists($conn, 'subscribers', 'created_at')) {
        @$conn->query("UPDATE subscribers SET registered_at = created_at WHERE registered_at IS NULL AND created_at IS NOT NULL AND created_at <> '0000-00-00 00:00:00'");
      }
      @$conn->query("UPDATE subscribers SET registered_at = NOW() WHERE registered_at IS NULL");
    }
  }
}

if (!function_exists('sh_get_subscriber')) {
  function sh_get_subscriber(mysqli $conn, int $subscriberId): ?array {
    $rs = @$conn->query("SELECT * FROM subscribers WHERE id=".(int)$subscriberId." LIMIT 1");
    if (!$rs || !$rs->num_rows) return null;
    return $rs->fetch_assoc();
  }
}

if (!function_exists('sh_subscriber_username')) {
  function sh_subscriber_username(array $sub): string {
    $u = trim((string)($sub['ppp_username'] ?? ''));
    if ($u === '') $u = trim((string)($sub['username'] ?? ''));
    return preg_replace('/@.*/', '', $u);
  }
}

if (!function_exists('sh_log_event')) {
  function sh_log_event(mysqli $conn, int $subscriberId, string $actionKey, string $actionLabel, string $details = '', ?string $eventAt = null, ?string $username = null): bool {
    sh_ensure_schema($conn);
    $eventAt = $eventAt ?: date('Y-m-d H:i:s');
    if ($username === null || $username === '') {
      $sub = sh_get_subscriber($conn, $subscriberId);
      $username = $sub ? sh_subscriber_username($sub) : '';
    } else {
      $username = preg_replace('/@.*/', '', trim((string)$username));
    }
    $stmt = @$conn->prepare("INSERT INTO subscriber_activity_log (subscriber_id, username, action_key, action_label, details, event_at, created_at) VALUES (?,?,?,?,?,?,NOW())");
    if (!$stmt) return false;
    $stmt->bind_param('isssss', $subscriberId, $username, $actionKey, $actionLabel, $details, $eventAt);
    $ok = $stmt->execute();
    $stmt->close();
    return (bool)$ok;
  }
}

if (!function_exists('sh_mark_registered')) {
  function sh_mark_registered(mysqli $conn, int $subscriberId, ?string $eventAt = null, string $details = 'تسجيل المشترك في النظام'): void {
    sh_ensure_schema($conn);
    $eventAt = $eventAt ?: date('Y-m-d H:i:s');
    if (sh_col_exists($conn, 'subscribers', 'registered_at')) {
      @$conn->query("UPDATE subscribers SET registered_at='".$conn->real_escape_string($eventAt)."' WHERE id=".(int)$subscriberId." AND (registered_at IS NULL OR registered_at='0000-00-00 00:00:00') LIMIT 1");
    }
    $chk = @$conn->query("SELECT id FROM subscriber_activity_log WHERE subscriber_id=".(int)$subscriberId." AND action_key='REGISTERED' LIMIT 1");
    if (!$chk || !$chk->num_rows) {
      sh_log_event($conn, $subscriberId, 'REGISTERED', 'تسجيل المشترك', $details, $eventAt);
    }
  }
}

if (!function_exists('sh_ensure_registered')) {
  function sh_ensure_registered(mysqli $conn, int $subscriberId, ?string $eventAt = null, string $details = 'تسجيل المشترك في النظام'): void {
    sh_mark_registered($conn, $subscriberId, $eventAt, $details);
  }
}

if (!function_exists('sh_mark_first_activation')) {
  function sh_mark_first_activation(mysqli $conn, int $subscriberId, ?string $eventAt = null, string $details = 'أول ظهور للمشترك أونلاين'): void {
    sh_ensure_schema($conn);
    $eventAt = $eventAt ?: date('Y-m-d H:i:s');
    $eventAtEsc = $conn->real_escape_string($eventAt);
    if (sh_col_exists($conn, 'subscribers', 'first_activated_at')) {
      @$conn->query("UPDATE subscribers SET first_activated_at='$eventAtEsc' WHERE id=".(int)$subscriberId." AND (first_activated_at IS NULL OR first_activated_at='0000-00-00 00:00:00') LIMIT 1");
    }
    $chk = @$conn->query("SELECT id FROM subscriber_activity_log WHERE subscriber_id=".(int)$subscriberId." AND action_key='FIRST_ACTIVATED' LIMIT 1");
    if (!$chk || !$chk->num_rows) {
      sh_log_event($conn, $subscriberId, 'FIRST_ACTIVATED', 'أول تفعيل', $details, $eventAt);
    }
  }
}

if (!function_exists('sh_log_online_state')) {
  function sh_log_online_state(mysqli $conn, int $subscriberId, bool $isOnline, ?string $eventAt = null, string $details = ''): void {
    $eventAt = $eventAt ?: date('Y-m-d H:i:s');
    $key = $isOnline ? 'CONNECTED' : 'DISCONNECTED';
    $label = $isOnline ? 'اتصال' : 'انقطاع';
    if ($details === '') {
      $details = $isOnline ? 'تم رصد المشترك أونلاين' : 'تم رصد فصل/انقطاع المشترك';
    }
    sh_log_event($conn, $subscriberId, $key, $label, $details, $eventAt);
    if ($isOnline) {
      sh_mark_first_activation($conn, $subscriberId, $eventAt, 'أول ظهور للمشترك أونلاين');
    }
  }
}
