<?php
if (session_status() === PHP_SESSION_NONE) session_start();

/**
 * get_assets.php (PDO) — GET
 * ✅ يرجّع العملات/الأصول المفعلة من جدول assets
 * ✅ لا يستخدم client_id
 */

$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, OPTIONS");
header("Access-Control-Max-Age: 600");
header("Content-Type: application/json; charset=UTF-8");

$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; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'طريقة الطلب غير مسموحة. استخدم GET فقط.'], JSON_UNESCAPED_UNICODE);
  exit;
}

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;
}

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

try {
  $q = trim((string)($_GET['q'] ?? ''));

  $where = "WHERE is_active = 1";
  $params = [];

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

  $stmt = $conn->prepare("
    SELECT
      id,
      code,
      name_ar,
      type,
      decimals,
      icon_url,
      is_active,
      sort_order
    FROM assets
    {$where}
    ORDER BY sort_order DESC, id ASC
  ");
  $stmt->execute($params);
  $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

  respond(true, 'تم جلب العملات بنجاح.', [
    'count' => count($items),
    'items' => $items
  ]);

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