<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'mark_paid') {
        $o = store_find('orders', (string) ($_POST['id'] ?? ''));
        if ($o) {
            $o['payment_status'] = 'odendi';
            $o['paid_at'] = date('c');
            store_upsert('orders', $o);
            flash('success', 'Sipariş ödendi olarak işaretlendi.');
        }
    }
    redirect(url('admin/siparisler.php'));
}

$orders = store_read('orders');
usort($orders, static fn(array $a, array $b): int => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));

admin_layout_start('Siparişler', 'orders');
?>

<section class="admin-panel">
    <h2>Tüm siparişler (<?= count($orders) ?>)</h2>

    <?php if (!$orders): ?>
        <p class="hint">Henüz sipariş yok.</p>
    <?php endif; ?>

    <?php foreach ($orders as $o):
        $addr = $o['address'] ?? '';
        $status = (string) ($o['payment_status'] ?? 'bekliyor');
        $paid = ($status === 'odendi');
        $statusLabel = match ($status) {
            'odendi' => 'Ödendi',
            'dekont_bekliyor' => 'Dekont var',
            default => 'Bekliyor',
        };
        $img = order_product_image_url($o);
        $title = (string) ($o['items'][0]['title'] ?? 'Ürün');
        $publicNo = order_public_no($o);
        $pendingNoReceipt = order_is_pending_payment($o);
        $deadlineGone = $pendingNoReceipt && order_pay_expired($o);
    ?>
        <div class="admin-order">
            <div class="admin-order-head" style="align-items:center;gap:0.65rem">
                <?php if ($img !== ''): ?>
                    <img src="<?= e($img) ?>" alt="" width="44" height="44" style="border-radius:8px;object-fit:cover">
                <?php endif; ?>
                <strong><?= e($o['customer_name'] ?? 'Misafir') ?></strong>
                <span class="admin-badge <?= $paid ? 'paid' : 'wait' ?>"><?= e($statusLabel) ?></span>
                <?php if ($deadlineGone): ?>
                    <span class="admin-badge wait">Süre doldu</span>
                <?php endif; ?>
                <?php if (!empty($o['receipt']) && empty($o['receipt_verified'])): ?>
                    <span class="admin-badge wait">Manuel kontrol</span>
                <?php elseif (!empty($o['receipt']) && !empty($o['receipt_verified'])): ?>
                    <span class="admin-badge paid">OCR onaylı<?= !empty($o['receipt_method']) && $o['receipt_method'] === 'browser' ? ' · tarayıcı' : '' ?></span>
                <?php endif; ?>
            </div>
            <p><strong><?= e($title) ?></strong> · <?= e(money($o['total'] ?? 0)) ?></p>
            <p><?= e($o['phone'] ?? '') ?> · No: <?= e($publicNo) ?> · <?= e((string) ($o['id'] ?? '')) ?></p>
            <?php if (is_string($addr) && $addr !== ''): ?>
                <p><?= e($addr) ?></p>
            <?php elseif (is_array($addr) && $addr): ?>
                <p>
                    <?= e(trim(($addr['il'] ?? '') . ' / ' . ($addr['ilce'] ?? ''), ' /')) ?>
                    <?php if (!empty($addr['mahalle'])): ?> · <?= e((string) $addr['mahalle']) ?><?php endif; ?>
                </p>
            <?php endif; ?>
            <?php if (!empty($o['note'])): ?>
                <p>Not: <?= e((string) $o['note']) ?></p>
            <?php endif; ?>
            <?php if (!empty($o['receipt'])): ?>
                <p style="margin-top:0.4rem">
                    <a class="admin-btn ghost sm" href="<?= e(receipt_url((string) $o['receipt'])) ?>" target="_blank" rel="noopener">Dekontu Gör</a>
                </p>
            <?php endif; ?>
            <?php if (!$paid): ?>
                <form method="post" style="margin-top:0.55rem">
                    <input type="hidden" name="action" value="mark_paid">
                    <input type="hidden" name="id" value="<?= e((string) ($o['id'] ?? '')) ?>">
                    <button class="admin-btn sm" type="submit">Ödendi İşaretle</button>
                </form>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</section>

<?php admin_layout_end(); ?>
