<?php
// Set the page title for the header
$page_title = "প্যাকেজ অর্ডার";

// 1. Include the authentication check file for security
// It also provides the DB connection ($conn) and helper functions like create_notification()
require_once 'includes/auth_check.php';

// 2. Handle status update actions submitted from the form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $order_id = (int)$_POST['order_id'];
    $new_status = $_POST['status'];

    // Update the status in the database
    $stmt = $conn->prepare("UPDATE package_orders SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $new_status, $order_id);
    $stmt->execute();
    $stmt->close();

    // 3. Send a notification to the user if the order is marked as Completed
    if ($new_status === 'Completed') {
        // Get order details to create a meaningful notification
        $order_details_stmt = $conn->prepare("SELECT user_id, offer_name, target_mobile FROM package_orders WHERE id = ?");
        $order_details_stmt->bind_param("i", $order_id);
        $order_details_stmt->execute();
        $order_details = $order_details_stmt->get_result()->fetch_assoc();
        $order_details_stmt->close();

        if ($order_details) {
            $notification_title = "প্যাকেজ অর্ডার সম্পন্ন";
            $notification_message = "আপনার '" . htmlspecialchars($order_details['offer_name']) . "' প্যাকেজটি " . htmlspecialchars($order_details['target_mobile']) . " নম্বরে সফলভাবে পাঠানো হয়েছে।";
            create_notification($conn, $order_details['user_id'], $notification_title, $notification_message);
        }
    }
    // Note: You could also send a notification for 'Failed' status if you want.

    // Redirect to the same page to prevent form resubmission on refresh
    header("Location: package_orders.php");
    exit;
}

// 4. Fetch all package orders to display
// We join with the 'users' table to get the customer's name.
// We sort by 'Pending' status first, then by the newest date.
$orders_result = $conn->query(
    "SELECT po.id, po.offer_name, po.target_mobile, po.price_paid, po.status, po.created_at, u.full_name 
     FROM package_orders po 
     JOIN users u ON po.user_id = u.id 
     ORDER BY FIELD(po.status, 'Pending') DESC, po.created_at DESC"
);

// 5. Include the admin panel header and sidebar
include 'includes/header.php';
?>

<div class="container-fluid">
    <h2 class="mb-4">প্যাকেজ অর্ডারসমূহ</h2>
    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>অর্ডার ID</th>
                            <th>ব্যবহারকারীর নাম</th>
                            <th>অফারের নাম</th>
                            <th>মোবাইল নম্বর</th>
                            <th>মূল্য (৳)</th>
                            <th>অর্ডারের সময়</th>
                            <th>স্ট্যাটাস</th>
                            <th>একশন</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($orders_result && $orders_result->num_rows > 0): ?>
                            <?php while($order = $orders_result->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo $order['id']; ?></td>
                                    <td><?php echo htmlspecialchars($order['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['offer_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['target_mobile']); ?></td>
                                    <td><?php echo number_format($order['price_paid'], 2); ?></td>
                                    <td><?php echo date("d M, Y, h:i A", strtotime($order['created_at'])); ?></td>
                                    <td>
                                        <?php
                                            $status_color = 'secondary';
                                            if ($order['status'] == 'Pending') $status_color = 'warning text-dark';
                                            elseif ($order['status'] == 'Completed') $status_color = 'success';
                                            elseif ($order['status'] == 'Failed') $status_color = 'danger';
                                        ?>
                                        <span class="badge bg-<?php echo $status_color; ?>"><?php echo $order['status']; ?></span>
                                    </td>
                                    <td>
                                        <?php if ($order['status'] == 'Pending'): ?>
                                            <form method="POST" style="min-width: 120px;">
                                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                                <select name="status" onchange="this.form.submit()" class="form-select form-select-sm">
                                                    <option value="Pending" selected>Pending</option>
                                                    <option value="Completed">Completed</option>
                                                    <option value="Failed">Failed</option>
                                                </select>
                                                <input type="hidden" name="update_status" value="1">
                                            </form>
                                        <?php else: ?>
                                            <span>সম্পন্ন</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="text-center">এখনো কোনো প্যাকেজ অর্ডার নেই।</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
// 6. Include the admin panel footer
include 'includes/footer.php';
$conn->close();
?>