<?php
// get_crypto_asset_networks.php (PDO) — GET/POST
// ✅ لجلب شبكات الإيداع/السحب للعملات المشفّرة من جدول yc_crypto_asset_networks
// ✅ يدعم: asset (مثال USDT), op=deposit|withdraw, q (بحث), include_paused (0/1)
// ✅ التوثيق: Session أو user_id + user_token (user_sessions.user_token)

if (session_status() === PHP_SESSION_NONE) session_start();

/* ================= CORS ================= */
$frontendOrigin = 'https://eazzybit.com';
$reqOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($reqOrigin === $frontendOrigin) {
  header("Access-Control-Allow-Origin: {$frontendOrigin}");
  header("Vary: Origin");
  header("Access-Control-Allow-Credentials: true");
}
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Max-Age: 600");
header("Content-Type: application/json; charset=UTF-8");

/* ================= DEBUG ================= */
$DEBUG_MODE = true;
if ($DEBUG_MODE) { ini_set('display_errors', 1); error_reporting(E_ALL); }
else { ini_set('display_errors', 0); error_reporting(0); }

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }

/* ================= Helpers ================= */
function respond(bool $success, string $message, array $extra = [], int $status = 200): void {
  http_response_code($status);
  echo json_encode(
    array_merge(['success' => $success, 'message' => $message], $extra),
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
  );
  exit;
}

function log_error(Throwable $e): void {
  $dir = __DIR__ . '/../../logs';
  if (!is_dir($dir)) @mkdir($dir, 0755, true);
  $file = $dir . '/api_errors_' . date('Y-m-d') . '.log';
  $line = "[" . date('Y-m-d H:i:s') . "] " . $e->getMessage() . " | " . $e->getFile() . ":" . $e->getLine() . PHP_EOL;
  @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}

function safe_int($v, int $default = 0): int {
  if ($v === null || $v === '') return $default;
  return (int)$v;
}

function safe_str($v): string {
  return trim((string)($v ?? ''));
}

function safe_code($v): string {
  $s = strtoupper(safe_str($v));
  $s = preg_replace('/[^A-Z0-9_]/', '', $s);
  return $s ?: '';
}

function safe_op($v): string {
  $s = strtolower(safe_str($v));
  $s = preg_replace('/[^a-z]/', '', $s);
  // توافق قديم: send => withdraw
  if ($s === 'send') $s = 'withdraw';
  if (!in_array($s, ['deposit','withdraw'], true)) $s = 'withdraw';
  return $s;
}

function read_input(): array {
  $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

  if ($method === 'POST') {
    $raw  = file_get_contents('php://input') ?: '';
    $json = json_decode($raw, true);
    if (is_array($json)) return $json;
    return $_POST ?? [];
  }

  return $_GET ?? [];
}

/* ================= DB ================= */
require_once __DIR__ . '/../config.php';
if (!isset($conn) || !($conn instanceof PDO)) {
  respond(false, 'اتصال قاعدة البيانات غير متوفر.', [], 500);
}

/* ================= AUTH: Session أو user_id+user_token ================= */
function resolveUserId(PDO $conn, array $in): int {
  // 1) Session
  $sid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
  if ($sid > 0) return $sid;

  // 2) user_id + user_token
  $uid = isset($in['user_id']) ? (int)$in['user_id'] : 0;
  $tok = trim((string)($in['user_token'] ?? ''));
  if ($uid <= 0 || $tok === '') return 0;

  $st = $conn->prepare("
    SELECT user_id
    FROM user_sessions
    WHERE user_id = :uid
      AND user_token = :tok
      AND is_online = 1
    LIMIT 1
  ");
  $st->execute([':uid' => $uid, ':tok' => $tok]);
  $row = $st->fetch(PDO::FETCH_ASSOC);

  return $row ? (int)$row['user_id'] : 0;
}

try {
  $in = read_input();

  $userId = resolveUserId($conn, $in);
  if ($userId <= 0) {
    respond(false, 'غير مصرح. الرجاء تسجيل الدخول.', ['unauthorized' => true], 401);
  }

  /* ================= Params ================= */
  // asset_code في جدولك
  $asset = safe_code($in['asset'] ?? ($in['asset_code'] ?? ''));
  if ($asset === '') respond(false, 'الرجاء تحديد asset مثل USDT.', [], 422);

  // op: deposit|withdraw
  $op = safe_op($in['op'] ?? ($in['mode'] ?? 'withdraw'));

  // بحث في اسم الشبكة
  $q = safe_str($in['q'] ?? '');

  // include_paused=1 => يرجّع active + paused
  $includePaused = safe_int($in['include_paused'] ?? 0, 0);

  /* ================= Query ================= */
  $where = "WHERE asset_code = :asset AND op = :op";
  $params = [
    ':asset' => $asset,
    ':op'    => $op,
  ];

  if ($q !== '') {
    $where .= " AND (network_name LIKE :q)";
    $params[':q'] = '%' . $q . '%';
  }

  if (!$includePaused) {
    $where .= " AND status = 'active'";
  } else {
    $where .= " AND status IN ('active','paused')";
  }

  $sql = "
    SELECT
      id,
      asset_code,
      network_name,
      op,
      fee_amount,
      min_amount,
      max_amount,
      status,
      created_at,
      updated_at
    FROM yc_crypto_asset_networks
    {$where}
    ORDER BY id ASC
  ";

  $stmt = $conn->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  /* ================= Build response ================= */
  $items = [];
  foreach ($rows as $r) {
    $items[] = [
      'id'           => (int)($r['id'] ?? 0),
      'asset_code'   => strtoupper((string)($r['asset_code'] ?? '')),
      'network_name' => (string)($r['network_name'] ?? ''),
      'op'           => (string)($r['op'] ?? ''),              // deposit|withdraw
      'status'       => (string)($r['status'] ?? ''),          // active|paused

      // أرقام DECIMAL: نرجّعها كنص للحفاظ على الدقة
      'fee_amount'   => ($r['fee_amount'] === null ? "0" : (string)$r['fee_amount']),
      'min_amount'   => ($r['min_amount'] === null ? "0" : (string)$r['min_amount']),
      'max_amount'   => ($r['max_amount'] === null ? null : (string)$r['max_amount']),

      'created_at'   => $r['created_at'] ?? null,
      'updated_at'   => $r['updated_at'] ?? null,
    ];
  }

  respond(true, 'تم جلب الشبكات بنجاح.', [
    'user_id' => $userId,
    'asset'   => $asset,
    'op'      => $op,
    'count'   => count($items),
    'items'   => $items,
  ]);

} catch (Throwable $e) {
  log_error($e);
  $msg = 'خطأ في الخادم';
  if ($DEBUG_MODE) $msg .= ' - ' . $e->getMessage();
  respond(false, $msg, [], 500);
}
