<?php
/**
 * SMM Paket Satış Scripti - Admin Siparişler
 * Kupon/İndirim, KDV ve iyzico Desteği
 * @version 1.3.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

function generateInvoiceNumber() {
    return 'MKB' . date('Ymd') . strtoupper(substr(uniqid(), -6));
}

// Tamamlanmış, iptal veya iade edilmiş ama makbuzu olmayan siparişlere makbuz ata
$db->query("UPDATE orders SET invoice_number = CONCAT('MKB', DATE_FORMAT(COALESCE(completed_at, created_at), '%Y%m%d'), UPPER(SUBSTRING(MD5(RAND()), 1, 6))) WHERE status IN ('completed', 'cancelled', 'refunded') AND (invoice_number IS NULL OR invoice_number = '')");

function checkApiOrderStatus($db, $orderId) {
    $stmt = $db->prepare("SELECT o.api_order_id, o.status, o.invoice_number, ap.api_url, ap.api_key FROM orders o JOIN packages p ON o.package_id = p.id JOIN api_providers ap ON p.api_provider_id = ap.id WHERE o.id = ? AND o.api_order_id IS NOT NULL AND o.status NOT IN ('completed','cancelled','refunded')");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$order) return null;
    
    $ch = curl_init();
    curl_setopt_array($ch, [CURLOPT_URL => $order['api_url'], CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(['key' => $order['api_key'], 'action' => 'status', 'order' => $order['api_order_id']]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => false]);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    if (!$data || !isset($data['status'])) return null;
    
    $apiStatus = strtolower(trim($data['status']));
    $sql = "UPDATE orders SET api_status = ?";
    $params = [$data['status']];
    
    if (isset($data['charge']) && is_numeric($data['charge'])) { $sql .= ", api_charge = ?"; $params[] = (float)$data['charge']; }
    if (isset($data['start_count']) && is_numeric($data['start_count'])) { $sql .= ", api_start_count = ?"; $params[] = (int)$data['start_count']; }
    if (isset($data['remains']) && is_numeric($data['remains'])) { $sql .= ", api_remains = ?"; $params[] = (int)$data['remains']; }
    
    $completedStatuses = ['completed', 'complete', 'done', 'finished', 'partial', 'partially_completed', 'partially completed'];
    $processingStatuses = ['pending', 'in progress', 'inprogress', 'processing', 'running', 'active', 'started', 'in_progress'];
    $cancelledStatuses = ['canceled', 'cancelled', 'fail', 'failed', 'error', 'rejected'];
    $refundedStatuses = ['refunded', 'refund'];
    
    $newLocalStatus = null;
    
    if (in_array($apiStatus, $completedStatuses)) {
        $newLocalStatus = 'completed';
    } elseif (in_array($apiStatus, $processingStatuses)) {
        $newLocalStatus = 'processing';
    } elseif (in_array($apiStatus, $cancelledStatuses)) {
        $newLocalStatus = 'cancelled';
    } elseif (in_array($apiStatus, $refundedStatuses)) {
        $newLocalStatus = 'refunded';
    }
    
    if ($newLocalStatus) {
        $sql .= ", status = ?";
        $params[] = $newLocalStatus;
        
        if (in_array($newLocalStatus, ['completed', 'cancelled', 'refunded'])) {
            $invNo = empty($order['invoice_number']) ? generateInvoiceNumber() : $order['invoice_number'];
            $sql .= ", completed_at = COALESCE(completed_at, NOW()), invoice_number = ?";
            $params[] = $invNo;
        }
    }
    
    $sql .= ", updated_at = NOW() WHERE id = ?";
    $params[] = $orderId;
    $db->prepare($sql)->execute($params);
    
    return $data['status'];
}

function sendOrderToApi($db, $orderId) {
    $stmt = $db->prepare("SELECT o.*, p.api_provider_id, p.api_service_id, p.quantity as package_quantity, ap.api_url, ap.api_key FROM orders o JOIN packages p ON o.package_id = p.id LEFT JOIN api_providers ap ON p.api_provider_id = ap.id WHERE o.id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order) return ['success' => false, 'error' => 'Sipariş bulunamadı'];
    if (empty($order['api_provider_id']) || empty($order['api_service_id'])) return ['success' => false, 'is_manual' => true];
    if (empty($order['api_url']) || empty($order['api_key'])) return ['success' => false, 'error' => 'API pasif'];
    
    $ch = curl_init();
    curl_setopt_array($ch, [CURLOPT_URL => $order['api_url'], CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(['key' => $order['api_key'], 'action' => 'add', 'service' => $order['api_service_id'], 'link' => $order['social_media_link'], 'quantity' => $order['package_quantity']]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_SSL_VERIFYPEER => false]);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    
    if ($err) { $db->prepare("UPDATE orders SET api_error = ? WHERE id = ?")->execute([$err, $orderId]); return ['success' => false, 'error' => $err]; }
    $data = json_decode($response, true);
    if (isset($data['error'])) { $db->prepare("UPDATE orders SET api_error = ? WHERE id = ?")->execute([$data['error'], $orderId]); return ['success' => false, 'error' => $data['error']]; }
    if (isset($data['order'])) { $db->prepare("UPDATE orders SET api_order_id = ?, api_status = 'Pending', api_sent_at = NOW(), api_error = NULL WHERE id = ?")->execute([$data['order'], $orderId]); return ['success' => true, 'api_order_id' => $data['order']]; }
    return ['success' => false, 'error' => 'Geçersiz yanıt'];
}

if (!isset($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
$csrfToken = $_SESSION['csrf_token'];

// POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) { setFlash('error', 'Güvenlik hatası'); redirect(SITE_URL . '/admin/siparisler.php'); exit; }
    $orderId = (int)($_POST['order_id'] ?? 0);
    
    if ($orderId > 0) {
        try {
            switch ($_POST['action']) {
                case 'update_status':
                    $newStatus = $_POST['status'] ?? '';
                    if (!in_array($newStatus, ['pending','paid','processing','completed','cancelled','refunded'])) throw new Exception('Geçersiz');
                    $stmt = $db->prepare("SELECT o.*, p.api_provider_id, p.api_service_id FROM orders o JOIN packages p ON o.package_id = p.id WHERE o.id = ?");
                    $stmt->execute([$orderId]);
                    $order = $stmt->fetch(PDO::FETCH_ASSOC);
                    if (!$order) throw new Exception('Bulunamadı');
                    
                    $isAuto = !empty($order['api_provider_id']) && !empty($order['api_service_id']);
                    $sql = "UPDATE orders SET status = ?"; $params = [$newStatus];
                    if ($newStatus === 'paid' && empty($order['paid_at'])) $sql .= ", paid_at = NOW()";
                    if (in_array($newStatus, ['completed', 'cancelled', 'refunded'])) { 
                        $sql .= ", completed_at = COALESCE(completed_at, NOW())"; 
                        if (empty($order['invoice_number'])) { 
                            $sql .= ", invoice_number = ?"; 
                            $params[] = generateInvoiceNumber(); 
                        } 
                    }
                    $sql .= ", updated_at = NOW() WHERE id = ?"; $params[] = $orderId;
                    $db->prepare($sql)->execute($params);
                    
                    if ($newStatus === 'processing' && $isAuto && empty($order['api_order_id'])) {
                        $r = sendOrderToApi($db, $orderId);
                        setFlash($r['success'] ? 'success' : 'warning', $r['success'] ? 'API: #'.$r['api_order_id'] : 'Durum güncellendi. API: '.($r['error'] ?? 'Hata'));
                    } else { setFlash('success', 'Güncellendi'); }
                    break;
                case 'send_to_api':
                    $r = sendOrderToApi($db, $orderId);
                    if ($r['success']) { $db->prepare("UPDATE orders SET status = 'processing' WHERE id = ? AND status IN ('pending','paid')")->execute([$orderId]); setFlash('success', 'API: #'.$r['api_order_id']); }
                    else setFlash('error', $r['error'] ?? 'Hata');
                    break;
                case 'check_api':
                    $s = checkApiOrderStatus($db, $orderId);
                    setFlash($s ? 'success' : 'error', $s ? 'API Durumu: '.$s : 'Durum alınamadı');
                    break;
                case 'delete':
                    $proof = $db->prepare("SELECT payment_proof FROM orders WHERE id = ?"); $proof->execute([$orderId]); $p = $proof->fetchColumn();
                    if ($p && file_exists(__DIR__.'/../'.$p)) @unlink(__DIR__.'/../'.$p);
                    $db->prepare("DELETE FROM orders WHERE id = ?")->execute([$orderId]);
                    setFlash('success', 'Silindi');
                    break;
            }
        } catch (Exception $e) { setFlash('error', $e->getMessage()); }
    }
    redirect(SITE_URL . '/admin/siparisler.php' . (!empty($_GET['status']) ? '?status='.$_GET['status'] : ''));
    exit;
}

// Filtreler
$statusFilter = $_GET['status'] ?? '';
$typeFilter = $_GET['type'] ?? '';
$paymentFilter = $_GET['payment_method'] ?? '';
$search = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

$where = "1=1"; $params = [];
if (in_array($statusFilter, ['pending','paid','processing','completed','cancelled','refunded'])) { $where .= " AND o.status = ?"; $params[] = $statusFilter; }
if ($typeFilter === 'auto') $where .= " AND p.api_provider_id IS NOT NULL AND p.api_service_id IS NOT NULL";
elseif ($typeFilter === 'manual') $where .= " AND (p.api_provider_id IS NULL OR p.api_service_id IS NULL)";
if ($paymentFilter) { $where .= " AND o.payment_method = ?"; $params[] = $paymentFilter; }
if ($search) { $where .= " AND (o.order_number LIKE ? OR o.customer_name LIKE ? OR o.customer_email LIKE ? OR o.invoice_number LIKE ?)"; $params = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%"]); }

$total = $db->prepare("SELECT COUNT(*) FROM orders o JOIN packages p ON o.package_id = p.id WHERE $where"); $total->execute($params); $totalOrders = $total->fetchColumn();
$totalPages = ceil($totalOrders / $limit);

$sql = "SELECT o.*, p.name as package_name, p.quantity as pkg_qty, p.api_provider_id as pkg_api, p.api_service_id as pkg_svc, p.price as original_price, c.name as cat_name, c.icon as cat_icon, c.color as cat_color, ap.name as api_name
FROM orders o JOIN packages p ON o.package_id = p.id JOIN categories c ON p.category_id = c.id LEFT JOIN api_providers ap ON p.api_provider_id = ap.id WHERE $where ORDER BY o.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($sql); $stmt->execute($params); $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$statusCounts = $db->query("SELECT status, COUNT(*) FROM orders GROUP BY status")->fetchAll(PDO::FETCH_KEY_PAIR);
$typeCounts = $db->query("SELECT SUM(IF(p.api_provider_id IS NOT NULL AND p.api_service_id IS NOT NULL,1,0)) as auto_count, SUM(IF(p.api_provider_id IS NULL OR p.api_service_id IS NULL,1,0)) as manual_count FROM orders o JOIN packages p ON o.package_id = p.id")->fetch(PDO::FETCH_ASSOC);
$paymentCounts = $db->query("SELECT payment_method, COUNT(*) FROM orders WHERE payment_method IS NOT NULL AND payment_method != '' GROUP BY payment_method")->fetchAll(PDO::FETCH_KEY_PAIR);

// API kontrol (ilk 5 işleniyor durumundaki)
foreach (array_slice(array_filter($orders, fn($o) => !empty($o['api_order_id']) && !in_array($o['status'], ['completed','cancelled','refunded'])), 0, 5) as $o) {
    checkApiOrderStatus($db, $o['id']);
}
// Yeniden çek
$stmt = $db->prepare($sql); $stmt->execute($params); $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$statusCfg = [
    'pending' => ['label' => 'Bekliyor', 'color' => '#f59e0b', 'icon' => 'fa-clock'],
    'paid' => ['label' => 'Ödendi', 'color' => '#3b82f6', 'icon' => 'fa-credit-card'],
    'processing' => ['label' => 'İşleniyor', 'color' => '#8b5cf6', 'icon' => 'fa-spinner fa-spin'],
    'completed' => ['label' => 'Tamamlandı', 'color' => '#10b981', 'icon' => 'fa-check-circle'],
    'cancelled' => ['label' => 'İptal', 'color' => '#ef4444', 'icon' => 'fa-times-circle'],
    'refunded' => ['label' => 'İade', 'color' => '#6b7280', 'icon' => 'fa-undo']
];

// Ödeme yöntemleri konfigürasyonu
$paymentMethodCfg = [
    'bank_transfer' => ['label' => 'Havale/EFT', 'icon' => 'fa-university', 'color' => '#3b82f6'],
    'iyzico' => ['label' => 'Kredi Kartı', 'icon' => 'fa-credit-card', 'color' => '#8b5cf6'],
    'papara' => ['label' => 'Papara', 'icon' => 'fa-wallet', 'color' => '#7c3aed'],
    'crypto' => ['label' => 'Kripto', 'icon' => 'fa-bitcoin', 'color' => '#f59e0b'],
];

$adminPageTitle = 'Siparişler';
require_once __DIR__ . '/header.php';
?>

<style>
:root{--card-bg:var(--bg-card);--hover-bg:var(--bg-hover);--border:var(--border-color);--text1:var(--text-primary);--text2:var(--text-secondary)}
.stats{display:grid;grid-template-columns:repeat(5,1fr);gap:12px;margin-bottom:20px}
.stat-box{background:var(--card-bg);border:1px solid var(--border);border-radius:12px;padding:16px;text-align:center}
.stat-box h3{font-size:24px;font-weight:700;margin:0 0 4px}
.stat-box span{font-size:11px;color:var(--text2)}
.filters{background:var(--card-bg);border:1px solid var(--border);border-radius:12px;padding:16px;margin-bottom:20px}
.filters-top{display:flex;gap:10px;flex-wrap:wrap}
.search-wrap{flex:1;min-width:200px;position:relative}
.search-wrap input{width:100%;padding:10px 12px 10px 38px;background:var(--hover-bg);border:1px solid var(--border);border-radius:8px;color:var(--text1);font-size:13px}
.search-wrap input::placeholder{color:var(--text2)}
.search-wrap i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--text2);font-size:14px}
.tabs{display:flex;gap:6px;flex-wrap:wrap;margin-top:14px}
.tab{display:inline-flex;align-items:center;gap:5px;padding:7px 12px;background:var(--hover-bg);border-radius:6px;font-size:12px;color:var(--text2);text-decoration:none;transition:.2s}
.tab:hover{color:var(--text1)}
.tab.on{background:rgba(139,92,246,.15);color:#8b5cf6}
.tab .n{background:rgba(255,255,255,.1);padding:2px 6px;border-radius:6px;font-size:10px;margin-left:2px}
.types{display:flex;gap:6px;margin-left:auto}
.type{padding:6px 10px;border-radius:6px;font-size:11px;font-weight:500;text-decoration:none}
.type.auto{background:rgba(139,92,246,.12);color:#8b5cf6}
.type.manual{background:rgba(16,185,129,.12);color:#10b981}
.type.iyzico{background:rgba(139,92,246,.12);color:#8b5cf6}
.type.bank{background:rgba(59,130,246,.12);color:#3b82f6}
.type.on.auto{background:#8b5cf6;color:#fff}
.type.on.manual{background:#10b981;color:#fff}
.type.on.iyzico{background:#8b5cf6;color:#fff}
.type.on.bank{background:#3b82f6;color:#fff}
.card{background:var(--card-bg);border:1px solid var(--border);border-radius:12px;overflow:hidden}
.tbl{width:100%;border-collapse:collapse}
.tbl th{background:var(--hover-bg);padding:12px;font-size:10px;font-weight:600;color:var(--text2);text-transform:uppercase;text-align:left;border-bottom:1px solid var(--border)}
.tbl td{padding:12px;font-size:13px;color:var(--text1);border-bottom:1px solid var(--border);vertical-align:middle}
.tbl tr:last-child td{border-bottom:none}
.tbl tr:hover td{background:var(--hover-bg)}
.ono{font-family:monospace;font-size:10px;color:#8b5cf6;font-weight:600}
.cust{display:flex;flex-direction:column;gap:1px}
.cust b{font-size:12px;font-weight:600}
.cust span{font-size:10px;color:var(--text2)}
.pkg{display:flex;align-items:center;gap:8px}
.pkg-icon{width:32px;height:32px;border-radius:6px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;flex-shrink:0}
.pkg-info{min-width:0}
.pkg-name{font-size:11px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:120px;display:block}
.pkg-meta{display:flex;align-items:center;gap:4px;margin-top:2px}
.pkg-cat{font-size:9px;color:var(--text2)}
.badge{padding:2px 5px;border-radius:3px;font-size:8px;font-weight:700}
.badge.auto{background:rgba(139,92,246,.15);color:#8b5cf6}
.badge.manual{background:rgba(16,185,129,.15);color:#10b981}
.link{max-width:80px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:10px;color:var(--text2);display:block}
.amt{font-weight:700;color:#10b981;font-size:13px}
.amt-discount{display:flex;flex-direction:column;gap:2px}
.amt-discount .original{font-size:10px;color:var(--text2);text-decoration:line-through}
.amt-discount .final{font-weight:700;color:#10b981;font-size:13px}
.amt-discount .coupon{font-size:8px;color:#8b5cf6;background:rgba(139,92,246,.15);padding:1px 4px;border-radius:3px;margin-top:1px;display:inline-block}
.amt-discount .kdv-badge{font-size:8px;color:#f59e0b;background:rgba(245,158,11,.15);padding:1px 4px;border-radius:3px;margin-top:1px;display:inline-block}
.status{display:inline-flex;align-items:center;gap:4px;padding:4px 8px;border-radius:12px;font-size:9px;font-weight:600;white-space:nowrap}
.api-col{font-size:9px;color:var(--text2)}
.api-col .aid{color:#8b5cf6;font-family:monospace;display:block}
.date{font-size:10px;color:var(--text2);white-space:nowrap}
.acts{display:flex;gap:3px}
.act{width:26px;height:26px;border-radius:5px;border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:10px;transition:.2s}
.act:hover{transform:scale(1.1)}
.act.v{background:rgba(59,130,246,.15);color:#3b82f6}
.act.a{background:rgba(139,92,246,.15);color:#8b5cf6}
.act.e{background:rgba(245,158,11,.15);color:#f59e0b}
.act.d{background:rgba(239,68,68,.15);color:#ef4444}
.act.inv{background:rgba(16,185,129,.15);color:#10b981}

/* Ödeme yöntemi badge */
.payment-badge{display:inline-flex;align-items:center;gap:4px;padding:4px 8px;border-radius:6px;font-size:9px;font-weight:600;white-space:nowrap}
.payment-badge.iyzico{background:rgba(139,92,246,.15);color:#8b5cf6}
.payment-badge.iyzico.paid{background:rgba(16,185,129,.15);color:#10b981}
.payment-badge.iyzico.unpaid{background:rgba(239,68,68,.15);color:#f87171}
.payment-badge.bank{background:rgba(59,130,246,.15);color:#3b82f6}
.payment-badge.papara{background:rgba(124,58,237,.15);color:#a78bfa}
.payment-badge.crypto{background:rgba(245,158,11,.15);color:#fbbf24}
.payment-badge.unknown{background:rgba(100,116,139,.15);color:#94a3b8}

/* iyzico durumu */
.iyzico-status{display:flex;flex-direction:column;gap:2px}
.iyzico-status .method{display:inline-flex;align-items:center;gap:4px;padding:3px 6px;border-radius:4px;font-size:8px;font-weight:600;background:rgba(139,92,246,.15);color:#8b5cf6}
.iyzico-status .pay-status{display:inline-flex;align-items:center;gap:3px;padding:2px 5px;border-radius:3px;font-size:7px;font-weight:700;margin-top:2px}
.iyzico-status .pay-status.success{background:rgba(16,185,129,.2);color:#10b981}
.iyzico-status .pay-status.pending{background:rgba(245,158,11,.2);color:#f59e0b}
.iyzico-status .pay-status.failed{background:rgba(239,68,68,.2);color:#ef4444}

.pagi{display:flex;align-items:center;justify-content:space-between;padding:14px;border-top:1px solid var(--border);flex-wrap:wrap;gap:10px}
.pagi-info{font-size:11px;color:var(--text2)}
.pagi-links{display:flex;gap:4px}
.pagi-links a{background:var(--hover-bg);border:1px solid var(--border);color:var(--text2);padding:6px 10px;border-radius:5px;font-size:11px;text-decoration:none}
.pagi-links a.on{background:#8b5cf6;border-color:#8b5cf6;color:#fff}
.empty{text-align:center;padding:50px;color:var(--text2)}
.empty i{font-size:40px;opacity:.3;display:block;margin-bottom:10px}

/* MODAL */
.modal-content{background:var(--card-bg);border:1px solid var(--border);border-radius:14px;color:var(--text1)}
.modal-header{border-bottom:1px solid var(--border);padding:16px 20px}
.modal-header .modal-title{font-size:16px;font-weight:700}
.modal-header .btn-close{filter:invert(1);opacity:.6}
.modal-body{padding:20px;max-height:70vh;overflow-y:auto}
.modal-footer{border-top:1px solid var(--border);padding:12px 20px}
.sec{margin-bottom:20px}
.sec:last-child{margin-bottom:0}
.sec-title{font-size:12px;font-weight:600;color:#8b5cf6;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:6px}
.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
.item{background:var(--hover-bg);padding:10px 12px;border-radius:6px}
.item.full{grid-column:span 2}
.item label{display:block;font-size:9px;color:var(--text2);text-transform:uppercase;margin-bottom:3px}
.item p{margin:0;font-size:12px;font-weight:500;word-break:break-all}
.item p a{color:#8b5cf6}
.item p.ok{color:#10b981}
.item p.err{color:#ef4444}
.api-box{background:rgba(139,92,246,.08);border:1px solid rgba(139,92,246,.2);border-radius:8px;padding:14px;margin-top:12px}
.api-box h5{font-size:11px;font-weight:600;color:#8b5cf6;margin:0 0 10px;display:flex;align-items:center;gap:5px}
.coupon-box{background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.2);border-radius:8px;padding:14px;margin-top:12px}
.coupon-box h5{font-size:11px;font-weight:600;color:#10b981;margin:0 0 10px;display:flex;align-items:center;gap:5px}
.kdv-box{background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.2);border-radius:8px;padding:14px;margin-top:12px}
.kdv-box h5{font-size:11px;font-weight:600;color:#f59e0b;margin:0 0 10px;display:flex;align-items:center;gap:5px}
.payment-box{background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.2);border-radius:8px;padding:14px;margin-top:12px}
.payment-box h5{font-size:11px;font-weight:600;color:#3b82f6;margin:0 0 10px;display:flex;align-items:center;gap:5px}
.payment-box.iyzico{background:rgba(139,92,246,.08);border:1px solid rgba(139,92,246,.2)}
.payment-box.iyzico h5{color:#8b5cf6}
.inv-box{background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.2);border-radius:8px;padding:14px;margin-top:12px}
.inv-box h5{font-size:11px;font-weight:600;color:#3b82f6;margin:0 0 10px;display:flex;align-items:center;gap:5px}
.inv-box .inv-actions{display:flex;gap:8px;margin-top:10px}
.inv-box .inv-btn{display:inline-flex;align-items:center;gap:5px;padding:8px 14px;border-radius:6px;font-size:11px;font-weight:500;text-decoration:none;transition:.2s}
.inv-box .inv-btn.view{background:#3b82f6;color:#fff}
.inv-box .inv-btn.pdf{background:#10b981;color:#fff}
.inv-box .inv-btn:hover{opacity:.9;transform:translateY(-1px)}
.proof{max-width:100%;max-height:200px;border-radius:6px;margin-top:8px;border:1px solid var(--border)}
.proof-link{display:inline-flex;align-items:center;gap:5px;padding:8px 14px;background:#3b82f6;color:#fff;border-radius:6px;font-size:11px;text-decoration:none;margin-top:8px}

/* Fiyat özeti tablosu */
.price-summary{background:var(--hover-bg);border-radius:8px;padding:12px;margin-top:10px}
.price-row{display:flex;justify-content:space-between;padding:6px 0;font-size:12px;border-bottom:1px dashed rgba(255,255,255,.1)}
.price-row:last-child{border-bottom:none}
.price-row.total{font-weight:700;font-size:14px;padding-top:10px;margin-top:6px;border-top:1px solid rgba(255,255,255,.15);border-bottom:none}
.price-row .label{color:var(--text2)}
.price-row .value{font-weight:500}
.price-row .value.discount{color:#10b981}
.price-row .value.kdv{color:#f59e0b}
.price-row.total .value{color:#10b981;font-size:16px}

/* RESPONSIVE */
@media(max-width:1200px){
    .stats{grid-template-columns:repeat(3,1fr)}
    .tbl th:nth-child(4),.tbl td:nth-child(4){display:none}
}
@media(max-width:992px){
    .stats{grid-template-columns:repeat(5,1fr)}
    .stat-box{padding:12px}
    .stat-box h3{font-size:20px}
    .tbl th:nth-child(8),.tbl td:nth-child(8){display:none}
}
@media(max-width:768px){
    .stats{grid-template-columns:repeat(3,1fr)}
    .filters-top{flex-direction:column}
    .search-wrap{width:100%}
    .types{margin-left:0;margin-top:10px;width:100%;justify-content:flex-start;flex-wrap:wrap}
    .tbl th:nth-child(3),.tbl td:nth-child(3),
    .tbl th:nth-child(5),.tbl td:nth-child(5){display:none}
    .grid{grid-template-columns:1fr}
    .item.full{grid-column:span 1}
    .pkg-name{max-width:100px}
}
@media(max-width:576px){
    .stats{grid-template-columns:repeat(2,1fr)}
    .stat-box:last-child{grid-column:span 2}
    .tabs{overflow-x:auto;flex-wrap:nowrap;padding-bottom:5px}
    .tab{white-space:nowrap;flex-shrink:0}
    .tbl th:nth-child(6),.tbl td:nth-child(6),
    .tbl th:nth-child(9),.tbl td:nth-child(9){display:none}
    .acts{flex-wrap:wrap}
    .ono{font-size:9px}
}
</style>

<div class="stats">
    <div class="stat-box"><h3 style="color:#f59e0b"><?php echo $statusCounts['pending'] ?? 0; ?></h3><span>Bekleyen</span></div>
    <div class="stat-box"><h3 style="color:#3b82f6"><?php echo $statusCounts['paid'] ?? 0; ?></h3><span>Ödendi</span></div>
    <div class="stat-box"><h3 style="color:#8b5cf6"><?php echo $statusCounts['processing'] ?? 0; ?></h3><span>İşleniyor</span></div>
    <div class="stat-box"><h3 style="color:#10b981"><?php echo $statusCounts['completed'] ?? 0; ?></h3><span>Tamamlandı</span></div>
    <div class="stat-box"><h3 style="color:#ef4444"><?php echo ($statusCounts['cancelled'] ?? 0) + ($statusCounts['refunded'] ?? 0); ?></h3><span>İptal/İade</span></div>
</div>

<div class="filters">
    <form class="filters-top" method="GET">
        <div class="search-wrap">
            <i class="fas fa-search"></i>
            <input type="text" name="q" placeholder="Sipariş no, müşteri, e-posta, makbuz no..." value="<?php echo clean($search); ?>">
        </div>
        <?php if ($statusFilter): ?><input type="hidden" name="status" value="<?php echo clean($statusFilter); ?>"><?php endif; ?>
        <?php if ($typeFilter): ?><input type="hidden" name="type" value="<?php echo clean($typeFilter); ?>"><?php endif; ?>
        <?php if ($paymentFilter): ?><input type="hidden" name="payment_method" value="<?php echo clean($paymentFilter); ?>"><?php endif; ?>
        <button type="submit" class="btn-primary-custom" style="padding:10px 16px"><i class="fas fa-search"></i></button>
        <?php if ($search || $statusFilter || $typeFilter || $paymentFilter): ?><a href="<?php echo SITE_URL; ?>/admin/siparisler.php" class="btn-secondary-custom" style="padding:10px 16px"><i class="fas fa-times"></i></a><?php endif; ?>
    </form>
    <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:10px;margin-top:14px">
        <div class="tabs">
            <a href="?<?php echo $typeFilter ? 'type='.$typeFilter : ''; ?><?php echo $paymentFilter ? ($typeFilter ? '&' : '').'payment_method='.$paymentFilter : ''; ?>" class="tab <?php echo !$statusFilter ? 'on' : ''; ?>">Tümü<span class="n"><?php echo array_sum($statusCounts); ?></span></a>
            <?php foreach ($statusCfg as $k => $v): ?>
            <a href="?status=<?php echo $k; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>" class="tab <?php echo $statusFilter === $k ? 'on' : ''; ?>"><i class="fas <?php echo $v['icon']; ?>"></i><?php echo $v['label']; ?><span class="n"><?php echo $statusCounts[$k] ?? 0; ?></span></a>
            <?php endforeach; ?>
        </div>
        <div class="types">
            <a href="?type=auto<?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>" class="type auto <?php echo $typeFilter === 'auto' ? 'on' : ''; ?>"><i class="fas fa-robot"></i> Oto(<?php echo $typeCounts['auto_count'] ?? 0; ?>)</a>
            <a href="?type=manual<?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>" class="type manual <?php echo $typeFilter === 'manual' ? 'on' : ''; ?>"><i class="fas fa-hand-paper"></i> Man(<?php echo $typeCounts['manual_count'] ?? 0; ?>)</a>
            <a href="?payment_method=iyzico<?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?>" class="type iyzico <?php echo $paymentFilter === 'iyzico' ? 'on' : ''; ?>"><i class="fas fa-credit-card"></i> iyzico(<?php echo $paymentCounts['iyzico'] ?? 0; ?>)</a>
            <a href="?payment_method=bank_transfer<?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?>" class="type bank <?php echo $paymentFilter === 'bank_transfer' ? 'on' : ''; ?>"><i class="fas fa-university"></i> Havale(<?php echo $paymentCounts['bank_transfer'] ?? 0; ?>)</a>
        </div>
    </div>
</div>

<div class="card">
<?php if (empty($orders)): ?>
<div class="empty"><i class="fas fa-inbox"></i><p>Sipariş bulunamadı</p></div>
<?php else: ?>
<div style="overflow-x:auto">
<table class="tbl">
    <thead><tr><th>Sipariş</th><th>Müşteri</th><th>Paket</th><th>Link</th><th>Tutar</th><th>Ödeme</th><th>Durum</th><th>API</th><th>Tarih</th><th>İşlem</th></tr></thead>
    <tbody>
    <?php foreach ($orders as $o): 
        $st = $statusCfg[$o['status']] ?? $statusCfg['pending']; 
        $isAuto = !empty($o['pkg_api']) && !empty($o['pkg_svc']); 
        $hasDiscount = floatval($o['discount_amount'] ?? 0) > 0;
        $hasKdv = floatval($o['kdv_amount'] ?? 0) > 0;
        $discountAmount = floatval($o['discount_amount'] ?? 0);
        $kdvAmount = floatval($o['kdv_amount'] ?? 0);
        
        // Orijinal paket fiyatını hesapla
        $basePrice = floatval($o['original_price']);
        $subtotalWithKdv = $basePrice + $kdvAmount;
        $finalAmount = $subtotalWithKdv - $discountAmount;
        
        // Ödeme yöntemi
        $paymentMethod = $o['payment_method'] ?? '';
        $pmCfg = $paymentMethodCfg[$paymentMethod] ?? ['label' => $paymentMethod ?: '-', 'icon' => 'fa-question', 'color' => '#64748b'];
        
        // iyzico ödeme durumu
        $iyzicoPaymentId = $o['iyzico_payment_id'] ?? '';
        $isIyzicoPaid = !empty($iyzicoPaymentId);
    ?>
    <tr>
        <td><span class="ono"><?php echo clean($o['order_number']); ?></span></td>
        <td><div class="cust"><b><?php echo clean($o['customer_name']); ?></b><span><?php echo clean($o['customer_email']); ?></span></div></td>
        <td><div class="pkg"><div class="pkg-icon" style="background:<?php echo $o['cat_color']; ?>"><i class="<?php echo $o['cat_icon']; ?>"></i></div><div class="pkg-info"><span class="pkg-name" title="<?php echo clean($o['package_name']); ?>"><?php echo clean($o['package_name']); ?></span><div class="pkg-meta"><span class="pkg-cat"><?php echo clean($o['cat_name']); ?></span><span class="badge <?php echo $isAuto ? 'auto' : 'manual'; ?>"><?php echo $isAuto ? 'OTO' : 'MAN'; ?></span></div></div></div></td>
        <td><span class="link" title="<?php echo clean($o['social_media_link']); ?>"><?php echo clean($o['social_media_link']); ?></span></td>
        <td>
            <?php if ($hasDiscount || $hasKdv): ?>
            <div class="amt-discount">
                <?php if ($hasDiscount): ?>
                <span class="original"><?php echo formatMoney($subtotalWithKdv); ?></span>
                <?php endif; ?>
                <span class="final"><?php echo formatMoney($o['amount']); ?></span>
                <?php if ($hasKdv): ?>
                <span class="kdv-badge"><i class="fas fa-percent"></i> KDV</span>
                <?php endif; ?>
                <?php if (!empty($o['coupon_code'])): ?>
                <span class="coupon"><i class="fas fa-tag"></i> <?php echo clean($o['coupon_code']); ?></span>
                <?php endif; ?>
            </div>
            <?php else: ?>
            <span class="amt"><?php echo formatMoney($o['amount']); ?></span>
            <?php endif; ?>
        </td>
        <td>
            <?php if ($paymentMethod === 'iyzico'): ?>
            <div class="iyzico-status">
                <span class="method"><i class="fas fa-credit-card"></i> Kart</span>
                <?php if ($isIyzicoPaid): ?>
                <span class="pay-status success"><i class="fas fa-check"></i> Ödendi</span>
                <?php elseif ($o['status'] === 'pending'): ?>
                <span class="pay-status pending"><i class="fas fa-clock"></i> Bekliyor</span>
                <?php elseif ($o['status'] === 'cancelled'): ?>
                <span class="pay-status failed"><i class="fas fa-times"></i> İptal</span>
                <?php else: ?>
                <span class="pay-status pending"><i class="fas fa-hourglass-half"></i> -</span>
                <?php endif; ?>
            </div>
            <?php elseif ($paymentMethod): ?>
            <span class="payment-badge <?php echo $paymentMethod === 'bank_transfer' ? 'bank' : clean($paymentMethod); ?>">
                <i class="fas <?php echo $pmCfg['icon']; ?>"></i>
                <?php echo $pmCfg['label']; ?>
            </span>
            <?php else: ?>
            <span class="payment-badge unknown"><i class="fas fa-question"></i> -</span>
            <?php endif; ?>
        </td>
        <td><span class="status" style="background:<?php echo $st['color']; ?>20;color:<?php echo $st['color']; ?>"><i class="fas <?php echo $st['icon']; ?>"></i><?php echo $st['label']; ?></span></td>
        <td><?php if ($isAuto): ?><?php if ($o['api_order_id']): ?><div class="api-col"><span class="aid">#<?php echo clean($o['api_order_id']); ?></span><?php echo clean($o['api_status'] ?? '-'); ?></div><?php else: ?><span style="font-size:9px;color:var(--text2)">-</span><?php endif; ?><?php else: ?><span style="font-size:9px;color:var(--text2)">-</span><?php endif; ?></td>
        <td><span class="date"><?php echo date('d.m.y H:i', strtotime($o['created_at'])); ?></span></td>
        <td><div class="acts">
            <button type="button" class="act v" onclick="viewOrder(<?php echo $o['id']; ?>)" title="Detay"><i class="fas fa-eye"></i></button>
            <?php if (!empty($o['invoice_number'])): ?>
            <a href="<?php echo SITE_URL; ?>/admin/makbuz.php?id=<?php echo $o['id']; ?>" class="act inv" target="_blank" title="Makbuz"><i class="fas fa-file-invoice"></i></a>
            <?php endif; ?>
            <?php if ($isAuto && $o['api_order_id']): ?><form method="POST" style="display:inline"><input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="check_api"><button class="act a" title="API Kontrol"><i class="fas fa-sync-alt"></i></button></form>
            <?php elseif ($isAuto && in_array($o['status'], ['paid','processing'])): ?><form method="POST" style="display:inline"><input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="send_to_api"><button class="act a" title="API Gönder"><i class="fas fa-paper-plane"></i></button></form><?php endif; ?>
            <button type="button" class="act e" onclick="editOrder(<?php echo $o['id']; ?>,'<?php echo $o['status']; ?>')" title="Düzenle"><i class="fas fa-edit"></i></button>
            <button type="button" class="act d" onclick="delOrder(<?php echo $o['id']; ?>)" title="Sil"><i class="fas fa-trash"></i></button>
        </div></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php if ($totalPages > 1): ?>
<div class="pagi">
    <span class="pagi-info"><?php echo number_format($totalOrders); ?> sipariş</span>
    <div class="pagi-links">
        <?php if ($page > 1): ?><a href="?page=<?php echo $page-1; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
        <?php for ($i = max(1,$page-2); $i <= min($totalPages,$page+2); $i++): ?><a href="?page=<?php echo $i; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>" class="<?php echo $i === $page ? 'on' : ''; ?>"><?php echo $i; ?></a><?php endfor; ?>
        <?php if ($page < $totalPages): ?><a href="<?php echo SITE_URL; ?>/admin/siparisler.php?page=<?php echo $page+1; ?><?php echo $statusFilter ? '&status='.$statusFilter : ''; ?><?php echo $typeFilter ? '&type='.$typeFilter : ''; ?><?php echo $paymentFilter ? '&payment_method='.$paymentFilter : ''; ?>"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
    </div>
</div>
<?php endif; ?>
<?php endif; ?>
</div>

<!-- View Modal -->
<div class="modal fade" id="viewModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content">
<div class="modal-header"><h5 class="modal-title"><i class="fas fa-receipt me-2"></i>Sipariş Detayı</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body" id="modalBody"></div>
<div class="modal-footer"><button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">Kapat</button></div>
</div></div></div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form method="POST"><input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>"><input type="hidden" name="order_id" id="eId"><input type="hidden" name="action" value="update_status">
<div class="modal-header"><h5 class="modal-title"><i class="fas fa-edit me-2"></i>Durum Güncelle</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">
<div class="mb-3"><label class="form-label">Durum</label><select name="status" id="eSt" class="form-select"><?php foreach ($statusCfg as $k => $v): ?><option value="<?php echo $k; ?>"><?php echo $v['label']; ?></option><?php endforeach; ?></select></div>
<div style="background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.2);border-radius:6px;padding:10px;font-size:11px;color:#3b82f6"><i class="fas fa-info-circle me-1"></i>Otomatik paketler "İşleniyor" durumunda API'ye gönderilir.</div>
</div>
<div class="modal-footer"><button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button><button type="submit" class="btn-primary-custom"><i class="fas fa-save me-1"></i>Kaydet</button></div>
</form></div></div></div>

<script>
var U='<?php echo SITE_URL; ?>',T='<?php echo $csrfToken; ?>';
var D=<?php
$arr = [];
foreach ($orders as $o) {
    $isAuto = !empty($o['pkg_api']) && !empty($o['pkg_svc']);
    $st = $statusCfg[$o['status']] ?? $statusCfg['pending'];
    $hasDiscount = floatval($o['discount_amount'] ?? 0) > 0;
    $hasKdv = floatval($o['kdv_amount'] ?? 0) > 0;
    $discountAmount = floatval($o['discount_amount'] ?? 0);
    $kdvAmount = floatval($o['kdv_amount'] ?? 0);
    $kdvRate = floatval($o['kdv_rate'] ?? 0);
    
    // Fiyat hesaplamaları
    $basePrice = floatval($o['original_price']);
    $subtotalWithKdv = $basePrice + $kdvAmount;
    
    // Ödeme yöntemi
    $paymentMethod = $o['payment_method'] ?? '';
    $pmCfg = $paymentMethodCfg[$paymentMethod] ?? ['label' => $paymentMethod ?: '-', 'icon' => 'fa-question', 'color' => '#64748b'];
    
    // iyzico bilgileri
    $iyzicoPaymentId = $o['iyzico_payment_id'] ?? '';
    $iyzicoInstallment = $o['iyzico_installment'] ?? '';
    $iyzicoCardFamily = $o['iyzico_card_family'] ?? '';
    $iyzicoCardType = $o['iyzico_card_type'] ?? '';
    $iyzicoCardAssociation = $o['iyzico_card_association'] ?? '';
    $iyzicoBinNumber = $o['iyzico_bin_number'] ?? '';
    $iyzicoLastFour = $o['iyzico_last_four'] ?? '';
    $isIyzicoPaid = !empty($iyzicoPaymentId);
    
    $arr[] = [
        'id' => (int)$o['id'],
        'no' => $o['order_number'],
        'name' => $o['customer_name'],
        'email' => $o['customer_email'],
        'phone' => $o['customer_phone'] ?? '',
        'pkg' => $o['package_name'],
        'qty' => $o['pkg_qty'],
        'cat' => $o['cat_name'],
        'link' => $o['social_media_link'],
        'amt' => formatMoney($o['amount']),
        'basePrice' => formatMoney($basePrice),
        'basePriceRaw' => $basePrice,
        'subtotalWithKdv' => formatMoney($subtotalWithKdv),
        'subtotalWithKdvRaw' => $subtotalWithKdv,
        'discount' => $discountAmount,
        'discountFmt' => $hasDiscount ? formatMoney($discountAmount) : '',
        'coupon' => $o['coupon_code'] ?? '',
        'hasDiscount' => $hasDiscount,
        'hasKdv' => $hasKdv,
        'kdvRate' => $kdvRate,
        'kdvAmount' => $kdvAmount,
        'kdvAmountFmt' => $hasKdv ? formatMoney($kdvAmount) : '',
        'st' => $o['status'],
        'stL' => $st['label'],
        'stC' => $st['color'],
        'auto' => $isAuto,
        'apiN' => $o['api_name'] ?? '',
        'apiO' => $o['api_order_id'] ?? '',
        'apiS' => $o['api_status'] ?? '',
        'apiE' => $o['api_error'] ?? '',
        'apiAt' => $o['api_sent_at'] ? date('d.m.Y H:i', strtotime($o['api_sent_at'])) : '',
        'apiSt' => $o['api_start_count'] ?? '',
        'apiRm' => $o['api_remains'] ?? '',
        'proof' => $o['payment_proof'] ?? '',
        'noteC' => $o['customer_note'] ?? '',
        'noteA' => $o['admin_note'] ?? '',
        'inv' => $o['invoice_number'] ?? '',
        'at' => date('d.m.Y H:i', strtotime($o['created_at'])),
        'pAt' => $o['paid_at'] ? date('d.m.Y H:i', strtotime($o['paid_at'])) : '',
        'cAt' => $o['completed_at'] ? date('d.m.Y H:i', strtotime($o['completed_at'])) : '',
        // Ödeme yöntemi bilgileri
        'pm' => $paymentMethod,
        'pmLabel' => $pmCfg['label'],
        'pmIcon' => $pmCfg['icon'],
        'pmColor' => $pmCfg['color'],
        // iyzico bilgileri
        'iyzicoPaymentId' => $iyzicoPaymentId,
        'iyzicoInstallment' => $iyzicoInstallment,
        'iyzicoCardFamily' => $iyzicoCardFamily,
        'iyzicoCardType' => $iyzicoCardType,
        'iyzicoCardAssociation' => $iyzicoCardAssociation,
        'iyzicoBinNumber' => $iyzicoBinNumber,
        'iyzicoLastFour' => $iyzicoLastFour,
        'isIyzicoPaid' => $isIyzicoPaid
    ];
}
echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_HEX_APOS | JSON_HEX_QUOT);
?>;

function viewOrder(id){
    var o=D.find(function(x){return x.id===id});
    if(!o){alert('Bulunamadı');return;}
    
    var proof='';
    if(o.proof){
        var ext=o.proof.split('.').pop().toLowerCase();
        if(['jpg','jpeg','png','gif','webp'].indexOf(ext)!==-1) proof='<img src="'+U+'/'+o.proof+'" class="proof">';
        else proof='<a href="'+U+'/'+o.proof+'" target="_blank" class="proof-link"><i class="fas fa-download"></i> Dekont İndir</a>';
    }
    
    var api='';
    if(o.auto){
        api='<div class="api-box"><h5><i class="fas fa-robot"></i> API Bilgileri</h5><div class="grid">';
        api+='<div class="item"><label>Sağlayıcı</label><p>'+(o.apiN||'-')+'</p></div>';
        api+='<div class="item"><label>API Order ID</label><p style="color:#8b5cf6;font-family:monospace">'+(o.apiO?'#'+o.apiO:'Gönderilmedi')+'</p></div>';
        api+='<div class="item"><label>API Durumu</label><p>'+(o.apiS||'-')+'</p></div>';
        api+='<div class="item"><label>Gönderim</label><p>'+(o.apiAt||'-')+'</p></div>';
        if(o.apiSt) api+='<div class="item"><label>Başlangıç</label><p>'+Number(o.apiSt).toLocaleString('tr-TR')+'</p></div>';
        if(o.apiRm!=='') api+='<div class="item"><label>Kalan</label><p>'+Number(o.apiRm).toLocaleString('tr-TR')+'</p></div>';
        if(o.apiE) api+='<div class="item full"><label>Hata</label><p class="err">'+o.apiE+'</p></div>';
        api+='</div></div>';
    }
    
    // KDV bilgisi
    var kdv='';
    if(o.hasKdv){
        kdv='<div class="kdv-box"><h5><i class="fas fa-percent"></i> KDV Bilgileri</h5><div class="grid">';
        kdv+='<div class="item"><label>KDV Oranı</label><p style="color:#f59e0b;font-weight:700">%'+o.kdvRate+'</p></div>';
        kdv+='<div class="item"><label>KDV Tutarı</label><p style="color:#f59e0b;font-weight:700">+'+o.kdvAmountFmt+'</p></div>';
        kdv+='</div></div>';
    }
    
    // Kupon bilgisi
    var coupon='';
    if(o.hasDiscount){
        coupon='<div class="coupon-box"><h5><i class="fas fa-ticket-alt"></i> Kupon/İndirim Bilgileri</h5><div class="grid">';
        if(o.coupon) coupon+='<div class="item"><label>Kupon Kodu</label><p style="color:#10b981;font-family:monospace;font-size:14px">'+o.coupon+'</p></div>';
        coupon+='<div class="item"><label>İndirim Tutarı</label><p style="color:#10b981;font-weight:700">-'+o.discountFmt+'</p></div>';
        coupon+='</div></div>';
    }
    
    // Ödeme yöntemi bilgisi
    var payment='';
    if(o.pm){
        var pmClass = o.pm === 'iyzico' ? 'iyzico' : '';
        payment='<div class="payment-box '+pmClass+'"><h5><i class="fas '+o.pmIcon+'"></i> Ödeme Bilgileri</h5><div class="grid">';
        payment+='<div class="item"><label>Ödeme Yöntemi</label><p style="color:'+o.pmColor+';font-weight:600"><i class="fas '+o.pmIcon+' me-1"></i>'+o.pmLabel+'</p></div>';
        payment+='<div class="item"><label>Ödeme Durumu</label><p class="'+(o.isIyzicoPaid || o.pAt ? 'ok' : '')+'">'+(o.isIyzicoPaid ? '<i class="fas fa-check-circle me-1"></i>Ödeme Alındı' : (o.pAt ? '<i class="fas fa-check-circle me-1"></i>Ödendi' : '<i class="fas fa-clock me-1"></i>Bekliyor'))+'</p></div>';
        
        // iyzico özel bilgileri
        if(o.pm === 'iyzico'){
            if(o.iyzicoPaymentId) payment+='<div class="item"><label>iyzico Payment ID</label><p style="color:#8b5cf6;font-family:monospace;font-size:11px">'+o.iyzicoPaymentId+'</p></div>';
            if(o.iyzicoInstallment && o.iyzicoInstallment > 1) payment+='<div class="item"><label>Taksit</label><p style="color:#8b5cf6;font-weight:600">'+o.iyzicoInstallment+' Taksit</p></div>';
            else if(o.iyzicoInstallment == 1) payment+='<div class="item"><label>Taksit</label><p>Tek Çekim</p></div>';
            if(o.iyzicoCardFamily) payment+='<div class="item"><label>Kart Ailesi</label><p>'+o.iyzicoCardFamily+'</p></div>';
            if(o.iyzicoCardType) payment+='<div class="item"><label>Kart Tipi</label><p>'+o.iyzicoCardType+'</p></div>';
            if(o.iyzicoCardAssociation) payment+='<div class="item"><label>Kart Markası</label><p>'+o.iyzicoCardAssociation+'</p></div>';
            if(o.iyzicoBinNumber && o.iyzicoLastFour) payment+='<div class="item"><label>Kart Numarası</label><p style="font-family:monospace">'+o.iyzicoBinNumber+' **** **** '+o.iyzicoLastFour+'</p></div>';
        }
        
        payment+='</div></div>';
    }
    
    // Fiyat özeti
    var priceSum='<div class="price-summary">';
    priceSum+='<div class="price-row"><span class="label">Paket Fiyatı</span><span class="value">'+o.basePrice+'</span></div>';
    if(o.hasKdv){
        priceSum+='<div class="price-row"><span class="label">KDV (%'+o.kdvRate+')</span><span class="value kdv">+'+o.kdvAmountFmt+'</span></div>';
        priceSum+='<div class="price-row"><span class="label">Ara Toplam</span><span class="value">'+o.subtotalWithKdv+'</span></div>';
    }
    if(o.hasDiscount){
        priceSum+='<div class="price-row"><span class="label">Kupon İndirimi</span><span class="value discount">-'+o.discountFmt+'</span></div>';
    }
    priceSum+='<div class="price-row total"><span class="label">Ödenen Tutar</span><span class="value">'+o.amt+'</span></div>';
    priceSum+='</div>';
    
    var inv='';
    if(o.inv){
        inv='<div class="inv-box"><h5><i class="fas fa-file-invoice"></i> Makbuz Bilgileri</h5><div class="grid">';
        inv+='<div class="item"><label>Makbuz No</label><p class="ok" style="font-size:15px;font-family:monospace">'+o.inv+'</p></div>';
        inv+='<div class="item"><label>Tarih</label><p>'+(o.cAt||o.at)+'</p></div>';
        inv+='</div>';
        inv+='<div class="inv-actions">';
        inv+='<a href="'+U+'/admin/makbuz.php?id='+o.id+'" target="_blank" class="inv-btn view"><i class="fas fa-eye"></i> Görüntüle</a>';
        inv+='<a href="'+U+'/admin/makbuz.php?id='+o.id+'&action=pdf" target="_blank" class="inv-btn pdf"><i class="fas fa-file-pdf"></i> PDF İndir</a>';
        inv+='</div></div>';
    }
    
    var h='<div class="sec"><div class="sec-title"><i class="fas fa-info-circle"></i> Sipariş</div><div class="grid">';
    h+='<div class="item"><label>Sipariş No</label><p style="color:#8b5cf6;font-family:monospace">'+o.no+'</p></div>';
    h+='<div class="item"><label>Durum</label><p><span class="status" style="background:'+o.stC+'20;color:'+o.stC+'">'+o.stL+'</span> <span class="badge '+(o.auto?'auto':'manual')+'">'+(o.auto?'Otomatik':'Manuel')+'</span></p></div>';
    h+='<div class="item"><label>Tarih</label><p>'+o.at+'</p></div>';
    h+='<div class="item"><label>Ödeme</label><p>'+(o.pAt||'-')+'</p></div>';
    h+='<div class="item"><label>Tamamlanma</label><p>'+(o.cAt||'-')+'</p></div>';
    h+='</div>';
    h+=priceSum;
    h+='</div>';
    
    h+='<div class="sec"><div class="sec-title"><i class="fas fa-user"></i> Müşteri</div><div class="grid">';
    h+='<div class="item"><label>Ad Soyad</label><p>'+o.name+'</p></div>';
    h+='<div class="item"><label>E-posta</label><p><a href="mailto:'+o.email+'">'+o.email+'</a></p></div>';
    h+='<div class="item"><label>Telefon</label><p>'+(o.phone||'-')+'</p></div>';
    h+='<div class="item full"><label>Sosyal Medya</label><p><a href="'+o.link+'" target="_blank">'+o.link+'</a></p></div>';
    h+='</div></div>';
    
    h+='<div class="sec"><div class="sec-title"><i class="fas fa-box"></i> Paket</div><div class="grid">';
    h+='<div class="item"><label>Paket</label><p>'+o.pkg+'</p></div>';
    h+='<div class="item"><label>Kategori</label><p>'+o.cat+'</p></div>';
    h+='<div class="item"><label>Miktar</label><p>'+(o.qty?Number(o.qty).toLocaleString('tr-TR'):'-')+'</p></div>';
    h+='<div class="item"><label>Tür</label><p><span class="badge '+(o.auto?'auto':'manual')+'" style="padding:4px 8px;font-size:10px">'+(o.auto?'<i class="fas fa-robot me-1"></i>Otomatik':'<i class="fas fa-hand-paper me-1"></i>Manuel')+'</span></p></div>';
    h+='</div></div>';
    
    h+=payment;
    h+=kdv;
    h+=coupon;
    h+=api;
    
    if(o.noteC) h+='<div class="sec"><div class="sec-title"><i class="fas fa-comment"></i> Müşteri Notu</div><div class="item full"><p>'+o.noteC+'</p></div></div>';
    if(o.noteA) h+='<div class="sec"><div class="sec-title"><i class="fas fa-sticky-note"></i> Admin Notu</div><div class="item full"><p>'+o.noteA+'</p></div></div>';
    if(o.proof) h+='<div class="sec"><div class="sec-title"><i class="fas fa-receipt"></i> Ödeme Dekontu</div>'+proof+'</div>';
    
    h+=inv;
    
    document.getElementById('modalBody').innerHTML=h;
    new bootstrap.Modal(document.getElementById('viewModal')).show();
}

function editOrder(id,st){
    document.getElementById('eId').value=id;
    document.getElementById('eSt').value=st;
    new bootstrap.Modal(document.getElementById('editModal')).show();
}

function delOrder(id){
    var o=D.find(function(x){return x.id===id});
    Swal.fire({
        title:'Siparişi silmek istediğinize emin misiniz?',
        html:o?'<p style="opacity:.7">'+o.no+'</p>':'',
        icon:'warning',
        showCancelButton:true,
        confirmButtonColor:'#ef4444',
        cancelButtonColor:'#64748b',
        confirmButtonText:'<i class="fas fa-trash me-1"></i>Sil',
        cancelButtonText:'İptal',
        background:'#1e293b',
        color:'#f8fafc'
    }).then(function(r){
        if(r.isConfirmed){
            var f=document.createElement('form');
            f.method='POST';
            f.innerHTML='<input name="csrf_token" value="'+T+'"><input name="order_id" value="'+id+'"><input name="action" value="delete">';
            document.body.appendChild(f);
            f.submit();
        }
    });
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>