<?php
// send_tracking.php - Admin adds tracking links
ob_start();
session_start();
require_once 'config.php';

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

// Update tracking link
if (isset($_POST['update_tracking'])) {
    $order_id = (int)$_POST['order_id'];
    $tracking_link = trim($_POST['tracking_link']);
    
    if ($order_id > 0) {
        $tracking_link = $conn->real_escape_string($tracking_link);
        $conn->query("UPDATE orders SET tracking_link = '$tracking_link' WHERE id = $order_id");
        $_SESSION['msg'] = "✅ Tracking link saved for Order ID: $order_id";
    }
    header('Location: send_tracking.php');
    exit;
}

// Get all orders
$orders = $conn->query("SELECT * FROM orders ORDER BY id DESC LIMIT 100");
$msg = $_SESSION['msg'] ?? '';
unset($_SESSION['msg']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Tracking Link - 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;margin-bottom:20px}
        .card-header{background:#2d6a4f;color:#fff;border-radius:15px 15px 0 0}
        .table td{vertical-align:middle}
        .tracking-input{font-family:monospace;font-size:13px}
        .btn-wa{background:#25D366;color:#fff}
        .btn-wa:hover{background:#128C7E;color:#fff}
        .alert-fixed{position:fixed;top:20px;right:20px;z-index:9999;min-width:300px}
        .link-saved{color:#28a745;font-size:12px}
    </style>
</head>
<body>

<div class="container-fluid">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3><i class="fas fa-link"></i> Tracking Link Manager</h3>
        <div>
            <a href="orders_final.php" class="btn btn-outline-secondary btn-sm">
                <i class="fas fa-shopping-cart"></i> Orders
            </a>
            <a href="admin.php" class="btn btn-secondary btn-sm">
                <i class="fas fa-arrow-left"></i> Admin Panel
            </a>
        </div>
    </div>

    <!-- Message -->
    <?php if($msg): ?>
    <div class="alert alert-success alert-fixed alert-dismissible fade show">
        <i class="fas fa-check-circle"></i> <?php echo $msg; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- Orders Table -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-edit"></i> Add Tracking Links to Orders
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Order #</th>
                            <th>Customer</th>
                            <th>Phone</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th width="400">Tracking Link</th>
                            <th width="200">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($orders->num_rows > 0): ?>
                        <?php while($order = $orders->fetch_assoc()): ?>
                        <tr>
                            <td>
                                <strong><?php echo $order['order_number']; ?></strong><br>
                                <small class="text-muted"><?php echo date('d M Y', strtotime($order['created_at'])); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                            <td><?php echo $order['customer_phone']; ?></td>
                            <td><strong>৳<?php echo number_format($order['total_amount']); ?></strong></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo $order['status']=='delivered'?'success':
                                        ($order['status']=='shipped'?'primary':
                                        ($order['status']=='cancelled'?'danger':'warning')); 
                                ?>">
                                    <?php echo ucfirst($order['status']); ?>
                                </span>
                            </td>
                            <tr>
                                <form method="POST" onsubmit="return confirm('Save tracking link?')">
                                    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                    <div class="input-group input-group-sm">
                                        <input type="text" name="tracking_link" class="form-control tracking-input" 
                                               value="<?php echo htmlspecialchars($order['tracking_link'] ?? ''); ?>" 
                                               placeholder="https://steadfast.com.bd/tl/XXXXXX">
                                        <button type="submit" name="update_tracking" class="btn btn-primary">
                                            <i class="fas fa-save"></i> Save
                                        </button>
                                    </div>
                                </form>
                                <?php if(!empty($order['tracking_link'])): ?>
                                    <small class="link-saved mt-1 d-block">
                                        <i class="fas fa-check-circle"></i> Link saved
                                    </small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if(!empty($order['tracking_link'])): ?>
                                    <div class="btn-group btn-group-sm">
                                        <a href="<?php echo $order['tracking_link']; ?>" target="_blank" class="btn btn-info">
                                            <i class="fas fa-external-link-alt"></i> Test
                                        </a>
                                        <a href="https://wa.me/88<?php echo $order['customer_phone']; ?>?text=📦 আপনার অর্ডার ট্র্যাক লিংক: <?php echo urlencode($order['tracking_link']); ?>" 
                                           target="_blank" class="btn btn-wa">
                                            <i class="fab fa-whatsapp"></i> Send
                                        </a>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">No link</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">
                                <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                                No orders found
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-hide alert after 3 seconds
setTimeout(function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        alert.style.opacity = '0';
        setTimeout(function() {
            alert.remove();
        }, 500);
    });
}, 3000);
</script>
</body>
</html>