<?php
// 1. To display all PHP errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// 2. Database connection path
require_once __DIR__ . '/../config.php'; 

// To keep the current filter query in the URL
$query_string = !empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '';

// Handle order status or payment status update request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $order_id = intval($_POST['order_id']);
    
    if ($_POST['action'] === 'update_order_status') {
        $new_status = trim($_POST['order_status']);
        try {
            $stmt = $pdo->prepare("UPDATE orders SET order_status = ? WHERE id = ?");
            $stmt->execute([$new_status, $order_id]);
            $_SESSION['success_msg'] = "Order status updated successfully.";
        } catch (PDOException $e) {
            $_SESSION['error_msg'] = "Status update error: " . $e->getMessage();
        }
    }
    
    if ($_POST['action'] === 'update_payment_status') {
        $new_pay_status = trim($_POST['payment_status']);
        try {
            $stmt = $pdo->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
            $stmt->execute([$new_pay_status, $order_id]);
            $_SESSION['success_msg'] = "Payment status updated successfully.";
        } catch (PDOException $e) {
            $_SESSION['error_msg'] = "Payment update error: " . $e->getMessage();
        }
    }
    
    // Filter query remains even when redirecting to orders_manager2.php
    header("Location: orders_manager2.php" . $query_string);
    exit();
}

// Filtering logic (Search & Filter)
$where_clauses = [];
$params = [];

if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = trim($_GET['search']);
    $clean_search = ltrim($search, '#'); 
    
    $where_clauses[] = "(customer_name LIKE ? OR customer_phone LIKE ? OR id = ? OR transaction_id = ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = is_numeric($clean_search) ? intval($clean_search) : 0;
    $params[] = $search;
}

if (isset($_GET['order_status']) && !empty($_GET['order_status'])) {
    $where_clauses[] = "order_status = ?";
    $params[] = trim($_GET['order_status']);
}

if (isset($_GET['payment_method']) && !empty($_GET['payment_method'])) {
    $where_clauses[] = "payment_method = ?";
    $params[] = trim($_GET['payment_method']);
}

$where_sql = "";
if (count($where_clauses) > 0) {
    $where_sql = "WHERE " . implode(" AND ", $where_clauses);
}

// Handle AJAX request (for additional load more)
if (isset($_GET['ajax_load']) && $_GET['ajax_load'] == 1) {
    $offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0;
    $limit = 10;
    
    try {
        $query = "SELECT * FROM orders $where_sql ORDER BY id DESC LIMIT $limit OFFSET $offset";
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (count($orders) > 0) {
            foreach ($orders as $order) {
                $items_stmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
                $items_stmt->execute([$order['id']]);
                $items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);
                ?>
                <tr>
                    <td class="text-center">
                        <span class="order-id">#<?php echo intval($order['id']); ?></span>
                        <span class="order-date"><?php echo date('d M, Y', strtotime($order['created_at'])); ?></span>
                    </td>
                    
                    <td>
                        <div class="cust-info">
                            <strong><i class="fa-solid fa-user"></i> <?php echo htmlspecialchars($order['customer_name']); ?></strong><br>
                            <span class="phone"><i class="fa-solid fa-phone"></i> <?php echo htmlspecialchars($order['customer_phone']); ?></span><br>
                            <span class="address-full">
                                <i class="fa-solid fa-location-dot"></i> <?php echo nl2br(htmlspecialchars($order['shipping_address'])); ?>
                            </span>
                        </div>
                    </td>

                    <td>
                        <div class="order-items-list">
                            <?php foreach ($items as $item): 
                                $prod_stmt = $pdo->prepare("SELECT image FROM products WHERE id = ? LIMIT 1");
                                $prod_stmt->execute([$item['product_id']]);
                                $product = $prod_stmt->fetch(PDO::FETCH_ASSOC);

                                $image_filename = '';
                                if (!empty($product) && !empty($product['image'])) {
                                    $image_filename = basename($product['image']);
                                }

                                $server_image_path = __DIR__ . "/../uploads/products/" . $image_filename;
                                $browser_image_src = "../uploads/products/" . $image_filename;

                                if (!empty($image_filename) && file_exists($server_image_path)) {
                                    $final_img_src = $browser_image_src;
                                } else {
                                    $final_img_src = "https://placehold.co/60x60/f1f3f9/a3a3a3?text=No+Image";
                                }
                            ?>
                                <div class="single-item-box">
                                    <img src="<?php echo htmlspecialchars($final_img_src); ?>" class="product-thumb" alt="Product" style="width: 50px; height: 50px; object-fit: cover; border-radius: 6px;">
                                    <div class="item-desc">
                                        <span class="product-name"><?php echo htmlspecialchars($item['product_name']); ?></span>
                                        <div class="product-meta">
                                            <?php if(!empty($item['size'])): ?>
                                                <span class="badge badge-outline">S: <?php echo htmlspecialchars($item['size']); ?></span>
                                            <?php endif; ?>
                                            
                                            <?php if(!empty($item['color'])): ?>
                                                <span class="badge badge-outline">C: <?php echo htmlspecialchars($item['color']); ?></span>
                                            <?php endif; ?>
                                            
                                            <span class="qty">x<?php echo intval($item['qty']); ?></span>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </td>

                    <td>
                        <div class="billing-info">
                            <span>Subtotal: BDT <?php echo number_format($order['total_amount']); ?></span><br>
                            <span>Delivery: BDT <?php echo number_format($order['delivery_charge']); ?></span><br>
                            <strong class="total-price">Total: BDT <?php echo number_format($order['grand_total']); ?></strong>
                        </div>
                    </td>

                    <td>
                        <div class="payment-col">
                            <span class="badge method-badge <?php echo htmlspecialchars($order['payment_method']); ?>">
                                <?php 
                                if ($order['payment_method'] === 'cod') echo 'Cash On Delivery';
                                elseif ($order['payment_method'] === 'manual') echo 'Bkash/Nagad';
                                elseif ($order['payment_method'] === 'sslcommerz') echo 'SSLCommerz';
                                ?>
                            </span>

                            <?php if (!empty($order['transaction_id'])): ?>
                                <div class="txn-box">
                                    TxnID: <code><?php echo htmlspecialchars($order['transaction_id']); ?></code>
                                </div>
                            <?php endif; ?>

                            <form action="orders_manager2.php<?php echo htmlspecialchars($query_string); ?>" method="POST">
                                <input type="hidden" name="order_id" value="<?php echo intval($order['id']); ?>">
                                <input type="hidden" name="action" value="update_payment_status">
                                <select name="payment_status" onchange="this.form.submit()" class="select-status pay-<?php echo htmlspecialchars(strtolower($order['payment_status'])); ?>">
                                    <option value="Pending" <?php echo ($order['payment_status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                    <option value="Pending-Verification" <?php echo ($order['payment_status'] === 'Pending-Verification') ? 'selected' : ''; ?>>Verification Pending</option>
                                    <option value="Completed" <?php echo ($order['payment_status'] === 'Completed') ? 'selected' : ''; ?>>Completed</option>
                                    <option value="Failed" <?php echo ($order['payment_status'] === 'Failed') ? 'selected' : ''; ?>>Failed</option>
                                </select>
                            </form>
                        </div>
                    </td>

                    <td>
                        <form action="orders_manager2.php<?php echo htmlspecialchars($query_string); ?>" method="POST">
                            <input type="hidden" name="order_id" value="<?php echo intval($order['id']); ?>">
                            <input type="hidden" name="action" value="update_order_status">
                            <select name="order_status" onchange="this.form.submit()" class="select-status order-<?php echo htmlspecialchars(strtolower($order['order_status'])); ?>">
                                <option value="Pending" <?php echo ($order['order_status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                <option value="Processing" <?php echo ($order['order_status'] === 'Processing') ? 'selected' : ''; ?>>Processing</option>
                                <option value="Shipped" <?php echo ($order['order_status'] === 'Shipped') ? 'selected' : ''; ?>>Shipped</option>
                                <option value="Delivered" <?php echo ($order['order_status'] === 'Delivered') ? 'selected' : ''; ?>>Delivered</option>
                                <option value="Cancelled" <?php echo ($order['order_status'] === 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </form>
                    </td>

                    <td>
                        <div class="action-buttons">
                            <!-- Target blank ensures it opens in a new tab/window for clean printing -->
                            <a href="print_invoice.php?order_id=<?php echo intval($order['id']); ?>" target="_blank" class="btn-action btn-print">
                                <i class="fa-solid fa-print"></i>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php
            }
        }
    } catch (PDOException $e) {
        echo "Error";
    }
    exit;
}

// Fetch first 10 orders
try {
    $query = "SELECT * FROM orders $where_sql ORDER BY id DESC LIMIT 10";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $count_query = "SELECT COUNT(*) FROM orders $where_sql";
    $count_stmt = $pdo->prepare($count_query);
    $count_stmt->execute($params);
    $total_orders = $count_stmt->fetchColumn();
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Management Dashboard | ShopVista</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/orders_manager.css?v=1.4">
    <style>
        .load-more-container { text-align: center; margin: 25px 0; }
        .btn-load-more {
            background-color: #4f46e5; color: #ffffff; border: none; padding: 12px 24px;
            font-size: 16px; font-family: 'Inter', sans-serif; font-weight: 600;
            border-radius: 6px; cursor: pointer; transition: all 0.3s ease;
            box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.1); display: inline-flex; align-items: center; gap: 8px;
        }
        .btn-load-more:hover { background-color: #4338ca; transform: translateY(-1px); }
        .btn-load-more:disabled { background-color: #a5b4fc; cursor: not-allowed; }
        /* Style adjustments to make the anchor look exactly like the previous action button */
        a.btn-print {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
        }
    </style>
</head>
<body>

    <div class="admin-container">
        <header class="admin-header">
            <div class="header-title">
                <h1><i class="fa-solid fa-boxes-packing"></i> Order Management Dashboard (V2)</h1>
                <p>Process customer orders, track payments and update status</p>
            </div>
            <a href="dashboard.php" class="back-btn"><i class="fa-solid fa-house"></i> Home Page</a>
        </header>

        <?php if (isset($_SESSION['success_msg'])): ?>
            <div class="alert alert-success">
                <i class="fa-solid fa-circle-check"></i> <?php echo htmlspecialchars($_SESSION['success_msg']); unset($_SESSION['success_msg']); ?>
            </div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error_msg'])): ?>
            <div class="alert alert-danger">
                <i class="fa-solid fa-circle-exclamation"></i> <?php echo htmlspecialchars($_SESSION['error_msg']); unset($_SESSION['error_msg']); ?>
            </div>
        <?php endif; ?>

        <div class="filter-card">
            <form action="orders_manager2.php" method="GET" class="filter-form">
                <div class="input-group">
                    <label>Search (Name, Phone, Order ID, TxnID)</label>
                    <input type="text" name="search" value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>" placeholder="e.g. 017XXXXXXXX or #12">
                </div>
                
                <div class="input-group">
                    <label>Order Status</label>
                    <select name="order_status">
                        <option value="">All</option>
                        <option value="Pending" <?php echo (($_GET['order_status'] ?? '') === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                        <option value="Processing" <?php echo (($_GET['order_status'] ?? '') === 'Processing') ? 'selected' : ''; ?>>Processing</option>
                        <option value="Shipped" <?php echo (($_GET['order_status'] ?? '') === 'Shipped') ? 'selected' : ''; ?>>Shipped</option>
                        <option value="Delivered" <?php echo (($_GET['order_status'] ?? '') === 'Delivered') ? 'selected' : ''; ?>>Delivered</option>
                        <option value="Cancelled" <?php echo (($_GET['order_status'] ?? '') === 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                </div>

                <div class="input-group">
                    <label>Payment Method</label>
                    <select name="payment_method">
                        <option value="">All</option>
                        <option value="cod" <?php echo (($_GET['payment_method'] ?? '') === 'cod') ? 'selected' : ''; ?>>Cash on Delivery</option>
                        <option value="manual" <?php echo (($_GET['payment_method'] ?? '') === 'manual') ? 'selected' : ''; ?>>Manual Bkash/Nagad</option>
                        <option value="sslcommerz" <?php echo (($_GET['payment_method'] ?? '') === 'sslcommerz') ? 'selected' : ''; ?>>SSLCommerz</option>
                    </select>
                </div>

                <div class="filter-buttons">
                    <button type="submit" class="btn btn-filter"><i class="fa-solid fa-magnifying-glass"></i> Filter</button>
                    <a href="orders_manager2.php" class="btn btn-reset">Reset</a>
                </div>
            </form>
        </div>

        <div class="table-card">
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer Info</th>
                            <th>Product Details</th>
                            <th>Total Bill</th>
                            <th>Payment Info</th>
                            <th>Order Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="orders-tbody">
                        <?php if (count($orders) > 0): ?>
                            <?php foreach ($orders as $order): 
                                $items_stmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
                                $items_stmt->execute([$order['id']]);
                                $items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);
                            ?>
                                <tr>
                                    <td class="text-center">
                                        <span class="order-id">#<?php echo intval($order['id']); ?></span>
                                        <span class="order-date"><?php echo date('d M, Y', strtotime($order['created_at'])); ?></span>
                                    </td>
                                    
                                    <td>
                                        <div class="cust-info">
                                            <strong><i class="fa-solid fa-user"></i> <?php echo htmlspecialchars($order['customer_name']); ?></strong><br>
                                            <span class="phone"><i class="fa-solid fa-phone"></i> <?php echo htmlspecialchars($order['customer_phone']); ?></span><br>
                                            <span class="address-full">
                                                <i class="fa-solid fa-location-dot"></i> <?php echo nl2br(htmlspecialchars($order['shipping_address'])); ?>
                                            </span>
                                        </div>
                                    </td>

                                    <td>
                                        <div class="order-items-list">
                                            <?php foreach ($items as $item): 
                                                $prod_stmt = $pdo->prepare("SELECT image FROM products WHERE id = ? LIMIT 1");
                                                $prod_stmt->execute([$item['product_id']]);
                                                $product = $prod_stmt->fetch(PDO::FETCH_ASSOC);

                                                $image_filename = '';
                                                if (!empty($product) && !empty($product['image'])) {
                                                    $image_filename = basename($product['image']);
                                                }

                                                $server_image_path = __DIR__ . "/../uploads/products/" . $image_filename;
                                                $browser_image_src = "../uploads/products/" . $image_filename;

                                                if (!empty($image_filename) && file_exists($server_image_path)) {
                                                    $final_img_src = $browser_image_src;
                                                } else {
                                                    $final_img_src = "https://placehold.co/60x60/f1f3f9/a3a3a3?text=No+Image";
                                                }
                                            ?>
                                                <div class="single-item-box">
                                                    <img src="<?php echo htmlspecialchars($final_img_src); ?>" class="product-thumb" alt="Product" style="width: 50px; height: 50px; object-fit: cover; border-radius: 6px;">
                                                    
                                                    <div class="item-desc">
                                                        <span class="product-name"><?php echo htmlspecialchars($item['product_name']); ?></span>
                                                        <div class="product-meta">
                                                            <?php if(!empty($item['size'])): ?>
                                                                <span class="badge badge-outline">S: <?php echo htmlspecialchars($item['size']); ?></span>
                                                            <?php endif; ?>
                                                            
                                                            <?php if(!empty($item['color'])): ?>
                                                                <span class="badge badge-outline">C: <?php echo htmlspecialchars($item['color']); ?></span>
                                                            <?php endif; ?>
                                                            
                                                            <span class="qty">x<?php echo intval($item['qty']); ?></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </td>

                                    <td>
                                        <div class="billing-info">
                                            <span>Subtotal: BDT <?php echo number_format($order['total_amount']); ?></span><br>
                                            <span>Delivery: BDT <?php echo number_format($order['delivery_charge']); ?></span><br>
                                            <strong class="total-price">Total: BDT <?php echo number_format($order['grand_total']); ?></strong>
                                        </div>
                                    </td>

                                    <td>
                                        <div class="payment-col">
                                            <span class="badge method-badge <?php echo htmlspecialchars($order['payment_method']); ?>">
                                                <?php 
                                                if ($order['payment_method'] === 'cod') echo 'Cash On Delivery';
                                                elseif ($order['payment_method'] === 'manual') echo 'Bkash/Nagad';
                                                elseif ($order['payment_method'] === 'sslcommerz') echo 'SSLCommerz';
                                                ?>
                                            </span>

                                            <?php if (!empty($order['transaction_id'])): ?>
                                                <div class="txn-box">
                                                    TxnID: <code><?php echo htmlspecialchars($order['transaction_id']); ?></code>
                                                </div>
                                            <?php endif; ?>

                                            <form action="orders_manager2.php<?php echo htmlspecialchars($query_string); ?>" method="POST">
                                                <input type="hidden" name="order_id" value="<?php echo intval($order['id']); ?>">
                                                <input type="hidden" name="action" value="update_payment_status">
                                                <select name="payment_status" onchange="this.form.submit()" class="select-status pay-<?php echo htmlspecialchars(strtolower($order['payment_status'])); ?>">
                                                    <option value="Pending" <?php echo ($order['payment_status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="Pending-Verification" <?php echo ($order['payment_status'] === 'Pending-Verification') ? 'selected' : ''; ?>>Verification Pending</option>
                                                    <option value="Completed" <?php echo ($order['payment_status'] === 'Completed') ? 'selected' : ''; ?>>Completed</option>
                                                    <option value="Failed" <?php echo ($order['payment_status'] === 'Failed') ? 'selected' : ''; ?>>Failed</option>
                                                </select>
                                            </form>
                                        </div>
                                    </td>

                                    <td>
                                        <form action="orders_manager2.php<?php echo htmlspecialchars($query_string); ?>" method="POST">
                                            <input type="hidden" name="order_id" value="<?php echo intval($order['id']); ?>">
                                            <input type="hidden" name="action" value="update_order_status">
                                            <select name="order_status" onchange="this.form.submit()" class="select-status order-<?php echo htmlspecialchars(strtolower($order['order_status'])); ?>">
                                                <option value="Pending" <?php echo ($order['order_status'] === 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                                <option value="Processing" <?php echo ($order['order_status'] === 'Processing') ? 'selected' : ''; ?>>Processing</option>
                                                <option value="Shipped" <?php echo ($order['order_status'] === 'Shipped') ? 'selected' : ''; ?>>Shipped</option>
                                                <option value="Delivered" <?php echo ($order['order_status'] === 'Delivered') ? 'selected' : ''; ?>>Delivered</option>
                                                <option value="Cancelled" <?php echo ($order['order_status'] === 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                                            </select>
                                        </form>
                                    </td>

                                    <td>
                                        <div class="action-buttons">
                                            <!-- Target blank ensures it opens in a new tab/window for clean printing -->
                                            <a href="print_invoice.php?order_id=<?php echo intval($order['id']); ?>" target="_blank" class="btn-action btn-print">
                                                <i class="fa-solid fa-print"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>