<?php include __DIR__ . '/../layout/header.php'; ?>

<?php
$ordSearch = $search ?? '';
$ordSort   = $sort   ?? 'created_at';
$ordOrder  = $order  ?? 'desc';

function ordSortUrl($f, $cs, $co, $s) {
    $o = ($cs === $f && $co === 'asc') ? 'desc' : 'asc';
    return '?sort='.$f.'&order='.$o.($s !== '' ? '&search='.urlencode($s) : '');
}
function ordSortIcon($f, $cs, $co) {
    if ($cs !== $f) return '<i class="fa fa-sort" style="opacity:.3;font-size:10px;"></i>';
    return $co === 'asc'
        ? '<i class="fa fa-sort-asc" style="color:var(--primary);font-size:11px;"></i>'
        : '<i class="fa fa-sort-desc" style="color:var(--primary);font-size:11px;"></i>';
}

function ordStatusBadge($status) {
    $map = [
        'pending'          => ['badge-warning', 'Bekliyor'],
        'pending_payment'  => ['badge-warning', 'Ödeme Bekliyor'],
        'payment_uploaded' => ['badge-info',    'Dekont İnceleniyor'],
        'processing'       => ['badge-info',    'Hazırlanıyor'],
        'shipped'          => ['badge-purple',   'Kargoya Verildi'],
        'delivered'        => ['badge-success',  'Teslim Edildi'],
        'completed'        => ['badge-success',  'Tamamlandı'],
        'cancelled'        => ['badge-danger',   'İptal'],
        'returned'         => ['badge-muted',    'İade'],
    ];
    return $map[$status] ?? ['badge-muted', $status ?: 'Bilinmiyor'];
}

$qs = '';
if ($ordSearch !== '') $qs .= '&search='.urlencode($ordSearch);
if ($ordSort   !== '') $qs .= '&sort='.$ordSort.'&order='.$ordOrder;
?>

<div class="page-toolbar">
    <form method="GET" action="<?php echo $baseUrl; ?>/admin/orders" id="order-search-form" class="search-bar" style="max-width:440px;">
        <i class="fa fa-search search-icon"></i>
        <input type="text" name="search" id="order-search-input"
               value="<?php echo htmlspecialchars($ordSearch); ?>"
               placeholder="Sipariş no, müşteri adı veya e-posta ara..."
               autocomplete="off">
        <?php if ($ordSearch !== ''): ?>
        <a href="<?php echo $baseUrl; ?>/admin/orders" class="search-clear-btn"><i class="fa fa-times"></i></a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card" style="padding:0;overflow:hidden;">

    <?php if (!empty($orders)): ?>

    <!-- Desktop Table -->
    <div class="admin-table-wrap desktop-only" style="border:none;border-radius:0;">
        <table class="admin-table">
            <thead>
                <tr>
                    <th><a href="<?php echo ordSortUrl('id', $ordSort, $ordOrder, $ordSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Sipariş <?php echo ordSortIcon('id', $ordSort, $ordOrder); ?></a></th>
                    <th><a href="<?php echo ordSortUrl('customer_name', $ordSort, $ordOrder, $ordSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Müşteri <?php echo ordSortIcon('customer_name', $ordSort, $ordOrder); ?></a></th>
                    <th>Ürünler</th>
                    <th><a href="<?php echo ordSortUrl('total', $ordSort, $ordOrder, $ordSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Toplam <?php echo ordSortIcon('total', $ordSort, $ordOrder); ?></a></th>
                    <th><a href="<?php echo ordSortUrl('created_at', $ordSort, $ordOrder, $ordSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Tarih <?php echo ordSortIcon('created_at', $ordSort, $ordOrder); ?></a></th>
                    <th><a href="<?php echo ordSortUrl('status', $ordSort, $ordOrder, $ordSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Durum <?php echo ordSortIcon('status', $ordSort, $ordOrder); ?></a></th>
                    <th style="text-align:right;width:90px;">İşlem</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $ord): ?>
                <?php [$badgeClass, $statusText] = ordStatusBadge($ord->status ?? ''); ?>
                <tr>
                    <td><code style="background:var(--surface-2);border:1px solid var(--border);padding:3px 8px;border-radius:6px;font-weight:700;color:var(--primary);">#<?php echo htmlspecialchars($ord->id); ?></code></td>
                    <td style="font-size:13px;line-height:1.6;">
                        <strong style="color:var(--text-1);"><?php echo htmlspecialchars($ord->customer_name); ?></strong><br>
                        <span style="color:var(--text-3);font-size:12px;"><i class="fa fa-phone" style="margin-right:3px;"></i><?php echo htmlspecialchars($ord->customer_phone); ?></span><br>
                        <span style="color:var(--text-3);font-size:12px;"><i class="fa fa-envelope" style="margin-right:3px;"></i><?php echo htmlspecialchars($ord->customer_email); ?></span>
                    </td>
                    <td style="font-size:13px;line-height:1.8;max-width:200px;">
                        <ul style="list-style:none;padding:0;margin:0;">
                            <?php foreach ($ord->items as $item): ?>
                            <li style="display:flex;align-items:center;gap:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                <span style="width:5px;height:5px;background:var(--primary);border-radius:50%;flex-shrink:0;display:inline-block;"></span>
                                <span style="color:var(--text-2);overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($item['name']); ?></span>
                                <strong style="color:var(--text-1);background:var(--surface-2);border:1px solid var(--border);padding:0 5px;border-radius:3px;font-size:11px;">×<?php echo $item['quantity']; ?></strong>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </td>
                    <td style="font-weight:800;color:var(--text-1);">
                        <?php echo \App\Services\CurrencyService::format($ord->total, $ord->currency); ?>
                        <?php if (isset($ord->payment_method)): ?>
                        <br><span style="font-size:11px;font-weight:400;color:var(--text-3);">
                            <?php
                            if ($ord->payment_method === 'bank_transfer') echo '<i class="fa fa-university"></i> Havale';
                            elseif ($ord->payment_method === 'cash_on_delivery') echo '<i class="fa fa-truck"></i> Kapıda';
                            else echo '<i class="fa fa-credit-card"></i> Kart';
                            ?>
                        </span>
                        <?php endif; ?>
                    </td>
                    <td style="color:var(--text-3);font-size:12.5px;"><?php echo htmlspecialchars($ord->created_at); ?></td>
                    <td><span class="status-badge <?php echo $badgeClass; ?>"><?php echo $statusText; ?></span></td>
                    <td style="text-align:right;">
                        <div style="display:flex;gap:4px;justify-content:flex-end;">
                            <a href="<?php echo $baseUrl; ?>/admin/orders/edit/<?php echo $ord->id; ?>" class="admin-action-btn edit"><i class="fa fa-eye"></i></a>
                            <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/orders/delete/<?php echo $ord->id; ?>')" class="admin-action-btn delete"><i class="fa fa-trash"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Mobile Cards -->
    <div class="mobile-only" style="padding:12px;">
        <?php foreach ($orders as $ord): ?>
        <?php [$badgeClass, $statusText] = ordStatusBadge($ord->status ?? ''); ?>
        <div class="m-card">
            <div class="m-card-header">
                <div class="m-card-title-wrap">
                    <div class="m-card-icon"><i class="fa fa-shopping-cart"></i></div>
                    <div style="overflow:hidden;">
                        <h3 class="m-card-title"><?php echo htmlspecialchars($ord->customer_name); ?></h3>
                        <p class="m-card-subtitle">Sipariş #<?php echo htmlspecialchars($ord->id); ?> · <?php echo date('d.m.Y', strtotime($ord->created_at)); ?></p>
                    </div>
                </div>
                <div class="m-card-value" style="color:var(--success);"><?php echo \App\Services\CurrencyService::format($ord->total, $ord->currency); ?></div>
            </div>
            <div class="m-card-footer">
                <span class="status-badge <?php echo $badgeClass; ?>"><?php echo $statusText; ?></span>
                <div class="m-card-actions">
                    <a href="<?php echo $baseUrl; ?>/admin/orders/edit/<?php echo $ord->id; ?>" class="m-action-btn edit"><i class="fa fa-eye"></i></a>
                    <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/orders/delete/<?php echo $ord->id; ?>')" class="m-action-btn delete"><i class="fa fa-trash"></i></button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Pagination -->
    <?php if (isset($totalPages) && $totalPages > 1): ?>
    <div class="pagination">
        <?php if ($currentPage > 1): ?>
        <a href="?page=<?php echo $currentPage - 1; ?><?php echo $qs; ?>"><i class="fa fa-chevron-left"></i></a>
        <?php endif; ?>
        <?php
        $start = max(1, $currentPage - 2);
        $end   = min($totalPages, $currentPage + 2);
        if ($start > 1) echo '<a href="?page=1'.$qs.'">1</a>';
        if ($start > 2) echo '<span style="background:none;border:none;color:var(--text-3);">…</span>';
        for ($i = $start; $i <= $end; $i++) {
            echo $i === $currentPage ? '<span>'.$i.'</span>' : '<a href="?page='.$i.$qs.'">'.$i.'</a>';
        }
        if ($end < $totalPages - 1) echo '<span style="background:none;border:none;color:var(--text-3);">…</span>';
        if ($end < $totalPages)     echo '<a href="?page='.$totalPages.$qs.'">'.$totalPages.'</a>';
        ?>
        <?php if ($currentPage < $totalPages): ?>
        <a href="?page=<?php echo $currentPage + 1; ?><?php echo $qs; ?>"><i class="fa fa-chevron-right"></i></a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php else: ?>
    <div style="text-align:center;padding:64px 20px;color:var(--text-3);">
        <i class="fa fa-shopping-cart" style="font-size:56px;opacity:0.15;display:block;margin-bottom:18px;"></i>
        <p style="font-size:15px;"><?php echo $ordSearch ? '"'.htmlspecialchars($ordSearch).'" için sonuç bulunamadı.' : 'Henüz sipariş alınmamış.'; ?></p>
    </div>
    <?php endif; ?>

</div>

<script>
initAutoSearch('order-search-input', 'order-search-form', 400);
function confirmDelete(url) {
    adminConfirm('Bu siparişi silmek istiyor musunuz? Bu işlem geri alınamaz.', function() { window.location.href = url; });
}
</script>

<?php include __DIR__ . '/../layout/footer.php'; ?>