<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';
$msg = '';

// Update status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $orderId = (int)$_POST['order_id'];
    $status  = $_POST['status'] ?? 'pending';
    $allowed = ['pending','processing','shipped','delivered','cancelled'];
    if (in_array($status, $allowed)) {
        $pdo->prepare("UPDATE orders SET status=? WHERE id=?")->execute([$status, $orderId]);
        $msg = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> অর্ডার স্ট্যাটাস আপডেট হয়েছে।</div>';
    }
}

$viewId = (int)($_GET['view'] ?? 0);
$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['search'] ?? '');

$where = 'WHERE 1=1';
$params = [];
if ($statusFilter) { $where .= ' AND o.status=?'; $params[] = $statusFilter; }
if ($search) { $where .= ' AND (o.customer_name LIKE ? OR o.customer_phone LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }

$stmt = $pdo->prepare("SELECT o.* FROM orders o $where ORDER BY o.created_at DESC");
$stmt->execute($params);
$orders = $stmt->fetchAll();

$viewOrder = null;
$orderItems = [];
if ($viewId) {
    $vs = $pdo->prepare("SELECT * FROM orders WHERE id=?");
    $vs->execute([$viewId]);
    $viewOrder = $vs->fetch();
    if ($viewOrder) {
        $is = $pdo->prepare("SELECT oi.*, p.name as product_name, p.image FROM order_items oi LEFT JOIN products p ON oi.product_id=p.id WHERE oi.order_id=?");
        $is->execute([$viewId]);
        $orderItems = $is->fetchAll();
    }
}

$statusLabels = ['pending'=>'অপেক্ষমান','processing'=>'প্রক্রিয়াধীন','shipped'=>'পাঠানো হয়েছে','delivered'=>'ডেলিভারি হয়েছে','cancelled'=>'বাতিল'];

// ── HTML output starts ──
include __DIR__ . '/includes/admin_header.php';

?>
<h2>অর্ডার ব্যবস্থাপনা</h2>
<?= $msg ?>

<?php if ($viewOrder): ?>
<!-- Order Detail View -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
    <h3 style="color:var(--navy);">অর্ডার #<?= str_pad($viewOrder['id'],6,'0',STR_PAD_LEFT) ?></h3>
    <a href="?action=list" class="topbar-btn btn-gray"><i class="fas fa-arrow-left"></i> সব অর্ডার</a>
</div>
<div style="display:grid;grid-template-columns:1fr 320px;gap:24px;align-items:start;">
    <div>
        <div class="card">
            <div class="card-header"><h3>পণ্যসমূহ</h3></div>
            <div class="table-wrap">
                <table>
                    <thead><tr><th>ছবি</th><th>পণ্য</th><th>ভ্যারিয়েশন</th><th>পরিমাণ</th><th>মূল্য</th><th>মোট</th></tr></thead>
                    <tbody>
                    <?php foreach ($orderItems as $item): ?>
                    <tr>
                        <td><?php if($item['image']): ?><img src="<?=UPLOADS_URL.e($item['image'])?>" class="thumb"><?php else: ?><div class="thumb-placeholder"><i class="fas fa-image"></i></div><?php endif; ?></td>
                        <td><?= e($item['product_name']) ?></td>
                        <td style="font-size:0.82rem;color:var(--gray-600);"><?= e($item['variation_info']) ?></td>
                        <td><?= $item['quantity'] ?></td>
                        <td>৳<?= number_format($item['price'],2) ?></td>
                        <td><strong>৳<?= number_format($item['price']*$item['quantity'],2) ?></strong></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div style="padding:16px 24px;display:flex;justify-content:flex-end;gap:24px;">
                <span>পণ্যের মোট: <strong>৳<?= number_format($viewOrder['total_amount']-$viewOrder['delivery_charge'],2) ?></strong></span>
                <span>ডেলিভারি: <strong>৳<?= number_format($viewOrder['delivery_charge'],2) ?></strong></span>
                <span style="font-size:1.1rem;color:var(--navy);">সর্বমোট: <strong>৳<?= number_format($viewOrder['total_amount'],2) ?></strong></span>
            </div>
        </div>
    </div>
    <div>
        <div class="card">
            <div class="card-header"><h3>গ্রাহকের তথ্য</h3></div>
            <div class="card-body">
                <p><strong>নাম:</strong> <?= e($viewOrder['customer_name']) ?></p>
                <p style="margin-top:8px;"><strong>ফোন:</strong> <?= e($viewOrder['customer_phone']) ?></p>
                <p style="margin-top:8px;"><strong>ঠিকানা:</strong> <?= e($viewOrder['customer_address']) ?></p>
                <p style="margin-top:8px;"><strong>ডেলিভারি:</strong> <?= $viewOrder['inside_dhaka'] ? 'ঢাকার ভিতরে' : 'ঢাকার বাইরে' ?></p>
                <p style="margin-top:8px;"><strong>তারিখ:</strong> <?= date('d/m/Y H:i', strtotime($viewOrder['created_at'])) ?></p>
            </div>
        </div>
        <div class="card" style="margin-top:16px;">
            <div class="card-header"><h3>স্ট্যাটাস পরিবর্তন</h3></div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="order_id" value="<?= $viewOrder['id'] ?>">
                    <div class="form-group">
                        <select class="form-control" name="status">
                            <?php foreach ($statusLabels as $k => $v): ?>
                                <option value="<?=$k?>" <?= $viewOrder['status']==$k?'selected':'' ?>><?=$v?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" name="update_status" class="topbar-btn btn-gold" style="width:100%;justify-content:center;"><i class="fas fa-save"></i> আপডেট করুন</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php else: ?>
<!-- Order List -->
<div class="card">
    <div class="card-header" style="flex-wrap:wrap;gap:10px;">
        <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <input type="text" class="form-control" name="search" placeholder="নাম/ফোন খুঁজুন..." value="<?=e($search)?>" style="max-width:200px;">
            <select class="form-control" name="status" style="max-width:180px;">
                <option value="">সব স্ট্যাটাস</option>
                <?php foreach ($statusLabels as $k=>$v): ?><option value="<?=$k?>" <?=$statusFilter==$k?'selected':''?>><?=$v?></option><?php endforeach; ?>
            </select>
            <button type="submit" class="topbar-btn btn-navy"><i class="fas fa-search"></i> খুঁজুন</button>
        </form>
        <span style="color:var(--gray-600);font-size:0.9rem;">মোট: <?= count($orders) ?> অর্ডার</span>
    </div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>অর্ডার নং</th><th>গ্রাহক</th><th>ফোন</th><th>মোট</th><th>ডেলিভারি</th><th>স্ট্যাটাস</th><th>তারিখ</th><th>অ্যাকশন</th></tr></thead>
            <tbody>
            <?php foreach ($orders as $o): ?>
            <tr>
                <td><strong>#<?= str_pad($o['id'],6,'0',STR_PAD_LEFT) ?></strong></td>
                <td><?= e($o['customer_name']) ?></td>
                <td><?= e($o['customer_phone']) ?></td>
                <td>৳<?= number_format($o['total_amount'],2) ?></td>
                <td><?= $o['inside_dhaka']?'ঢাকার ভিতরে':'ঢাকার বাইরে' ?></td>
                <td><span class="badge badge-<?=$o['status']?>"><?= $statusLabels[$o['status']] ?? $o['status'] ?></span></td>
                <td><?= date('d/m/Y', strtotime($o['created_at'])) ?></td>
                <td>
                    <div class="actions">
                        <a href="?view=<?=$o['id']?>" class="topbar-btn btn-navy"><i class="fas fa-eye"></i> দেখুন</a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
