<?php
/**
 * /api/get_trades.php (PDO)
 * ✅ يجلب الصفقات (Trades) للمستخدم
 * ✅ يدعم user_token (وأيضاً user_id + user_token) أو session user_id
 * ✅ يعتمد على trade_orders كمرجع أساسي للصفقات المكتملة/المنفذة
 * ✅ يدعم فلترة symbol أو symbols
 * ✅ يعيد: success + items[] + count
 *
 * ملاحظة:
 * - لأننا لا نعرف عندك إن كان يوجد جدول trades مستقل، هذا الملف يعمل على trade_orders
 *   ويعتبر "الصفقة" = أمر تم تنفيذه/إغلاقه (filled/closed/completed/settled...).
 * - إذا عندك جدول trades منفصل، قلّي اسمه وأعمدته وسأحوّل الكود عليه مباشرة.
 */

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");
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }

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

/* ================= 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 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 ?? [];
}

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

function safe_lower_token($s): string {
  $s = strtolower(trim((string)$s));
  $s = preg_replace('/[^a-z0-9_]/', '', $s);
  return $s;
}

function table_exists(PDO $conn, string $table): bool {
  $st = $conn->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t LIMIT 1");
  $st->execute([':t'=>$table]);
  return (bool)$st->fetchColumn();
}

function column_exists(PDO $conn, string $table, string $col): bool {
  $st = $conn->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t AND COLUMN_NAME=:c LIMIT 1");
  $st->execute([':t'=>$table, ':c'=>$col]);
  return (bool)$st->fetchColumn();
}

/**
 * ✅ يدعم:
 * - session user_id
 * - (user_id + user_token)
 * - user_token فقط
 */
function resolveUserId(PDO $conn, array $in): int {
  $sid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
  if ($sid > 0) return $sid;

  $tok = trim((string)($in['user_token'] ?? ''));
  if ($tok === '') return 0;

  $uid = isset($in['user_id']) ? (int)$in['user_id'] : 0;

  if ($uid > 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;
  }

  $st = $conn->prepare("
    SELECT user_id
    FROM user_sessions
    WHERE user_token=:tok AND is_online=1
    ORDER BY id DESC
    LIMIT 1
  ");
  $st->execute([':tok'=>$tok]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  return $row ? (int)$row['user_id'] : 0;
}

function parse_int($v, int $def=0): int {
  $n = (int)($v ?? $def);
  return $n;
}

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

try {
  $in = read_input();

  foreach (['users','trade_orders','user_sessions'] as $t) {
    if (!table_exists($conn, $t)) respond(false, "جدول {$t} غير موجود.", [], 500);
  }

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

  // فلترة symbol اختياري
  $symbol = safe_upper($in['symbol'] ?? '');

  // أو symbols كـ JSON array أو CSV
  $symbols = [];
  if (!empty($in['symbols'])) {
    if (is_array($in['symbols'])) {
      $symbols = $in['symbols'];
    } else {
      $raw = trim((string)$in['symbols']);
      $try = json_decode($raw, true);
      if (is_array($try)) $symbols = $try;
      else $symbols = preg_split('/\s*,\s*/', $raw) ?: [];
    }
  }
  $symbols = array_values(array_filter(array_map('safe_upper', $symbols)));

  // حد أعلى للنتائج
  $limit = parse_int($in['limit'] ?? 100, 100);
  if ($limit < 1) $limit = 1;
  if ($limit > 200) $limit = 200;

  // حالات "صفقات" افتراضياً (مكتملة/مغلقة/منفذة)
  $defaultTrade = ['filled','closed','completed','done','settled','executed','canceled_filled'];

  // إن أحببت تمرير statuses من الخارج
  $statuses = [];
  if (!empty($in['statuses'])) {
    if (is_array($in['statuses'])) {
      $statuses = $in['statuses'];
    } else {
      $raw = trim((string)$in['statuses']);
      $try = json_decode($raw, true);
      if (is_array($try)) $statuses = $try;
      else $statuses = preg_split('/\s*,\s*/', $raw) ?: [];
    }
  }
  $statuses = array_values(array_filter(array_map('safe_lower_token', $statuses)));
  if (empty($statuses)) $statuses = $defaultTrade;

  if (!column_exists($conn, 'trade_orders', 'status')) {
    respond(false, 'عمود status غير موجود في trade_orders.', [], 500);
  }

  /* ================= Build SELECT (dynamic columns) ================= */
  $selectCols = [];
  $selectCols[] = "t.id";

  $wanted = [
    'pair_id','symbol','side','order_type','ui_order_mode',
    'price','client_price','avg_price','fill_price','executed_price',
    'qty_base','qty_quote',
    'filled_qty_base','filled_qty_quote',
    'executed_qty_base','executed_qty_quote',
    'fee_rate','fee_amount','fee_asset_code',
    'provider_id','provider_order_id',
    'status','status_reason',
    'created_at','updated_at','filled_at','closed_at','completed_at'
  ];

  foreach ($wanted as $c) {
    if (column_exists($conn, 'trade_orders', $c)) {
      $selectCols[] = "t.`{$c}`";
    }
  }

  $orderBy = null;
  if (column_exists($conn, 'trade_orders', 'filled_at')) $orderBy = "t.filled_at DESC";
  elseif (column_exists($conn, 'trade_orders', 'updated_at')) $orderBy = "t.updated_at DESC";
  elseif (column_exists($conn, 'trade_orders', 'created_at')) $orderBy = "t.created_at DESC";
  else $orderBy = "t.id DESC";

  /* ================= WHERE ================= */
  $where = ["t.user_id = :uid"];
  $params = [':uid'=>$userId, ':limit'=>$limit];

  $ph = [];
  foreach ($statuses as $i => $st) {
    $k = ":st{$i}";
    $ph[] = $k;
    $params[$k] = $st;
  }
  $where[] = "LOWER(t.status) IN (".implode(',', $ph).")";

  if ($symbol !== '') {
    $where[] = "t.symbol = :sym";
    $params[':sym'] = $symbol;
  } elseif (!empty($symbols)) {
    $sph = [];
    foreach ($symbols as $i => $s) {
      $k = ":sym{$i}";
      $sph[] = $k;
      $params[$k] = $s;
    }
    $where[] = "t.symbol IN (".implode(',', $sph).")";
  }

  $sql = "
    SELECT ".implode(',', $selectCols)."
    FROM trade_orders t
    WHERE ".implode(' AND ', $where)."
    ORDER BY {$orderBy}
    LIMIT :limit
  ";

  $st = $conn->prepare($sql);
  foreach ($params as $k=>$v) {
    if ($k === ':limit') $st->bindValue($k, (int)$v, PDO::PARAM_INT);
    else $st->bindValue($k, $v);
  }
  $st->execute();

  $items = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  // لتوافق trade.php: بعض الواجهات تتوقع trade_order_id أو order_id
  foreach ($items as &$it) {
    if (!isset($it['trade_order_id'])) $it['trade_order_id'] = $it['id'] ?? null;
    if (!isset($it['order_id']))       $it['order_id']       = $it['id'] ?? null;

    // توحيد سعر الصفقة للواجهة (اختياري)
    if (!isset($it['price']) || $it['price'] === null || $it['price'] === '') {
      if (isset($it['avg_price']) && $it['avg_price'] !== null && $it['avg_price'] !== '') $it['price'] = $it['avg_price'];
      elseif (isset($it['fill_price']) && $it['fill_price'] !== null && $it['fill_price'] !== '') $it['price'] = $it['fill_price'];
      elseif (isset($it['executed_price']) && $it['executed_price'] !== null && $it['executed_price'] !== '') $it['price'] = $it['executed_price'];
      elseif (isset($it['client_price']) && $it['client_price'] !== null && $it['client_price'] !== '') $it['price'] = $it['client_price'];
    }
  }
  unset($it);

  respond(true, 'ok', [
    'count' => count($items),
    'items' => $items
  ], 200);

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