<?php
/**
 * Admin orders management
 */
require_once 'config.php';

try {
$userId = miniapp_require_admin();
try { if (function_exists('gemaccStarsAutoCancelExpired')) gemaccStarsAutoCancelExpired($pdo, 50); } catch (Throwable $e) { error_log('[stars_auto_cancel_admin_orders] '.$e->getMessage()); }
$status = $_GET['status'] ?? null;

$where = "1=1 AND NOT EXISTS (SELECT 1 FROM crypto_payments cp WHERE cp.order_id=o.id AND cp.provider='Plisio' AND cp.payment_type='order' AND cp.status NOT IN ('PAID','FAILED','REJECTED','CANCELLED')) AND NOT (UPPER(COALESCE(o.payment_method,''))='STARS' AND LOWER(COALESCE(o.payment_status,''))<>'paid')";
$params = [];

if ($status) {
    if ($status === 'WAITING' || $status === 'PENDING_OR_QUEUED') {
        $where .= " AND o.status IN ('PENDING','QUEUED')";
    } else {
        $where .= " AND o.status = ?";
        $params[] = $status;
    }
}

$stmt = $pdo->prepare("
    SELECT o.*, u.first_name, u.username
    FROM orders o
    LEFT JOIN users u ON o.user_id = u.id
    WHERE {$where}
    ORDER BY o.created_at DESC
    LIMIT 50
");
$stmt->execute($params);
$orders = $stmt->fetchAll();

$formatted = [];
$statusLabels = [
    'PENDING'   => '⏳ در انتظار',
    'APPROVED'  => '✅ تأیید شده',
    'REJECTED'  => '❌ رد شده',
    'QUEUED'    => '⏳ در صف',
    'DELIVERED' => '✅ تحویل شده',
    'CANCELLED' => '🚫 کنسل شده',
    'FAKE_RECEIPT' => '⚠️ فیش فیک',
];

foreach ($orders as $o) {
    $meta = [];
    if (!empty($o['receipt_text'])) {
        $decoded = json_decode((string)$o['receipt_text'], true);
        if (is_array($decoded)) $meta = $decoded;
    }
    $displayPrice = (int)($meta['payable_price'] ?? $meta['payable_amount'] ?? $o['price']);
    $receiptUrl = null;
    if (!empty($o['receipt_file_id']) && preg_match('/^(receipt|deposit)_\\d+_\\d+\\.(jpg|jpeg|png|gif|webp)$/i', $o['receipt_file_id'])) {
        // فایل‌های آپلود شده در mini_app/uploads
        $receiptUrl = 'uploads/' . $o['receipt_file_id'];
    }
    $formatted[] = [
        'id'             => (int)$o['id'],
        'user_id'        => (int)$o['user_id'],
        'first_name'     => $o['first_name'],
        'username'       => $o['username'],
        'duration'       => $o['duration'],
        'duration_label' => getDurationLabel($o['duration']),
        'seats'          => (int)$o['requested_seats'],
        'price'          => $displayPrice,
        'price_formatted'=> money($displayPrice),
        'original_price' => (int)($meta['final_price'] ?? $meta['original_final_price'] ?? $o['price']),
        'payable_rial' => (int)($meta['payable_rial'] ?? ($displayPrice * 10)),
        'payment_method' => $o['payment_method'],
        'status'         => $o['status'],
        'status_label'   => $statusLabels[$o['status']] ?? $o['status'],
        'receipt_file'   => $o['receipt_file_id'],
        'receipt_url'    => $receiptUrl,
        'receipt_text'   => $o['receipt_text'],
        'created_at'     => $o['created_at'],
        'fake_receipt_warning_no' => (int)($o['fake_receipt_warning_no'] ?? 0),
        'fake_receipt_warning_at' => $o['fake_receipt_warning_at'] ?? null,
    ];
}

echo json_encode([
    'ok'   => true,
    'data' => [
        'orders' => $formatted,
    ],
], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) { error_log('[admin_orders] '.$e->getMessage()); echo json_encode(['ok'=>false,'error'=>'خطای API سفارش‌ها: '.$e->getMessage()], JSON_UNESCAPED_UNICODE); }
