<?php
// orders.php - Working version without API
ob_start();
session_start();
require_once 'config.php';
require_once 'includes/tracking_fallback.php';

if (!isset($_SESSION['admin'])) {
    header('Location: admin.php');
    exit;
}

// Handle actions (simplified without API)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];
    $tracking = isset($_GET['tracking']) ? trim($_GET['tracking']) : '';

    if ($action == 'approve') {
        $conn->query("UPDATE orders SET status='approved' WHERE id=$id");
        $_SESSION['order_msg'] = "✅ Order approved";
    }
    elseif ($action == 'process') {
        $conn->query("UPDATE orders SET status='processing' WHERE id=$id");
        $_SESSION['order_msg'] = "⚡ Order processing started";
    }
    elseif ($action == 'ship') {
        if ($tracking == '') {
            // Generate manual tracking ID
            $tracking = 'STF-' . strtoupper(substr(md5($id . time()), 0, 8));
        }
        $conn->query("UPDATE orders SET status='shipped', tracking_id='$tracking', courier='steadfast', shipped_at=NOW() WHERE id=$id");
        $_SESSION['order_msg'] = "✅ Order shipped! Tracking: $tracking";
    }
    elseif ($action == 'deliver') {
        $conn->query("UPDATE orders SET status='delivered', delivered_at=NOW() WHERE id=$id");
        $_SESSION['order_msg'] = "✅ Order marked as delivered";
    }
    elseif ($action == 'cancel') {
        $conn->query("UPDATE orders SET status='cancelled' WHERE id=$id");
        $_SESSION['order_msg'] = "❌ Order cancelled";
    }

    header('Location: orders.php');
    exit;
}

$filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$where = "WHERE 1=1";
if ($filter != 'all') {
    $where .= " AND status='$filter'";
}
$orders = $conn->query("SELECT * FROM orders $where ORDER BY created_at DESC");

$statuses = ['pending','approved','processing','shipped','delivered','cancelled'];
$counts = [];
foreach ($statuses as $s) {
    $r = $conn->query("SELECT COUNT(*) as c FROM orders WHERE status='$s'")->fetch_assoc();
    $counts[$s] = $r['c'];
}
$allCount = array_sum($counts);
$order_msg = $_SESSION['order_msg'] ?? '';
unset($_SESSION['order_msg']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Orders | Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body{background:#f0f2f5;padding:20px}
        .card{border-radius:15px;box-shadow:0 2px 10px rgba(0,0,0,.05);margin-bottom:20px}
        .card-header{background:#2d6a4f;color:#fff;border-radius:15px 15px 0 0;padding:15px 20px}
        .btn-action{padding:5px 12px;border-radius:5px;font-size:.75rem;margin:2px;display:inline-block;text-decoration:none;color:#fff}
        .btn-approve{background:#17a2b8}.btn-process{background:#0d6efd}.btn-ship{background:#6f42c1}
        .btn-deliver{background:#28a745}.btn-cancel{background:#dc3545}.btn-wa{background:#25D366}
        .status-badge{padding:4px 12px;border-radius:20px;font-size:.7rem;color:#fff;display:inline-block}
        .tracking-code{font-family:monospace;background:#f8f9fa;padding:3px 8px;border-radius:5px;font-size:.75rem}
        .stat-box{background:#6c757d;padding:10px 15px;border-radius:10px;color:#fff;text-align:center;text-decoration:none;display:inline-block;margin:3px;min-width:70px}
        .stat-box .count{font-size:1.3rem;font-weight:800;display:block}
        table th{background:#f8f9fa}
    </style>
</head>
<body>
<div class="container-fluid">

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4><i class="fas fa-shopping-cart"></i> Orders (<?php echo $allCount; ?>)</h4>
    <a href="admin.php" class="btn btn-secondary btn-sm">← Admin Panel</a>
</div>

<?php if($order_msg): ?>
<div class="alert alert-info alert-dismissible fade show">
    <?php echo $order_msg; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Status Filters -->
<div class="mb-3">
    <a href="orders.php" class="stat-box"><span class="count"><?php echo $allCount; ?></span>All</a>
    <?php 
    $colors = ['pending'=>'#ffc107','approved'=>'#17a2b8','processing'=>'#0d6efd','shipped'=>'#6f42c1','delivered'=>'#28a745','cancelled'=>'#dc3545'];
    foreach($statuses as $s): 
    ?>
    <a href="?status=<?php echo $s; ?>" class="stat-box" style="background:<?php echo $colors[$s]; ?>">
        <span class="count"><?php echo $counts[$s]; ?></span><?php echo ucfirst($s); ?>
    </a>
    <?php endforeach; ?>
</div>

<!-- Orders Table -->
<div class="card">
    <div class="card-header">📋 Order List</div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>Order #</th><th>Customer</th><th>Amount</th><th>Status</th><th>Tracking ID</th><th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php while($o = $orders->fetch_assoc()): 
                    $status_colors = ['pending'=>'#ffc107','approved'=>'#17a2b8','processing'=>'#0d6efd','shipped'=>'#6f42c1','delivered'=>'#28a745','cancelled'=>'#dc3545'];
                ?>
                    <tr>
                        <td>
                            <strong><?php echo $o['order_number']; ?></strong><br>
                            <small><?php echo date('d/m/y',strtotime($o['created_at'])); ?></small>
                        </td>
                        <td>
                            <?php echo htmlspecialchars(substr($o['customer_name'], 0, 35)); ?><br>
                            <small><a href="tel:<?php echo $o['customer_phone']; ?>"><?php echo $o['customer_phone']; ?></a></small>
                        </td>
                        <td><strong>৳<?php echo number_format($o['total_amount']); ?></strong></td>
                        <td><span class="status-badge" style="background:<?php echo $status_colors[$o['status']]; ?>"><?php echo ucfirst($o['status']); ?></span></td>
                        <td>
                            <?php if($o['tracking_id']): ?>
                                <code class="tracking-code"><?php echo $o['tracking_id']; ?></code>
                                <?php if($o['status'] == 'shipped' || $o['status'] == 'delivered'): ?>
                                    <br><a href="https://steadfast.com.bd/tl/<?php echo urlencode($o['tracking_id']); ?>" target="_blank" class="small">Track →</a>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="d-flex flex-wrap gap-1">
                                <?php if($o['status']=='pending'): ?>
                                    <a href="?action=approve&id=<?php echo $o['id']; ?>" class="btn-action btn-approve">Approve</a>
                                    <a href="#" onclick="manualShip(<?php echo $o['id']; ?>)" class="btn-action btn-ship">Ship</a>
                                    <a href="?action=cancel&id=<?php echo $o['id']; ?>" class="btn-action btn-cancel">Cancel</a>
                                <?php elseif($o['status']=='approved'): ?>
                                    <a href="?action=process&id=<?php echo $o['id']; ?>" class="btn-action btn-process">Process</a>
                                    <a href="#" onclick="manualShip(<?php echo $o['id']; ?>)" class="btn-action btn-ship">Ship</a>
                                <?php elseif($o['status']=='processing'): ?>
                                    <a href="#" onclick="manualShip(<?php echo $o['id']; ?>)" class="btn-action btn-ship">Ship Now</a>
                                <?php elseif($o['status']=='shipped'): ?>
                                    <a href="?action=deliver&id=<?php echo $o['id']; ?>" class="btn-action btn-deliver">Deliver</a>
                                <?php endif; ?>
                                <a href="https://wa.me/88<?php echo $o['customer_phone']; ?>" target="_blank" class="btn-action btn-wa">WhatsApp</a>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function manualShip(orderId) {
    let tracking = prompt("Enter Tracking ID (or leave empty for auto-generate):", "");
    if (tracking === null) return;
    if (tracking === "") {
        window.location.href = "?action=ship&id=" + orderId;
    } else {
        window.location.href = "?action=ship&id=" + orderId + "&tracking=" + encodeURIComponent(tracking);
    }
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>