<?php
/**
 * Admin Orders Management
 * View orders, check Transaction IDs, and update order statuses.
 */

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/admin-auth.php';
require_once '../includes/csrf.php';

// Strictly enforce admin access
require_admin($pdo);

// Handle Status Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    enforce_csrf();
    
    $order_id = (int)$_POST['order_id'];
    $new_status = sanitize_input($_POST['status']);
    
    if (in_array($new_status, ['pending', 'approved', 'rejected'])) {
        try {
            // If approved, update the approved_at timestamp so it shows up in user's library
            $sql = "UPDATE orders SET status = :status, updated_at = NOW()";
            if ($new_status === 'approved') {
                $sql .= ", approved_at = NOW()";
            }
            $sql .= " WHERE id = :id";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':status' => $new_status,
                ':id' => $order_id
            ]);
            
            set_flash_message('success', 'Order #' . $order_id . ' status updated to ' . ucfirst($new_status) . '.');
        } catch (PDOException $e) {
            error_log("Order Update Error: " . $e->getMessage());
            set_flash_message('error', 'System error: Could not update order status.');
        }
    } else {
        set_flash_message('error', 'Invalid status selected.');
    }
    
    redirect(SITE_URL . '/admin/orders.php');
    exit;
}

// Fetch All Orders with User and Product details
try {
    $stmt = $pdo->prepare("
        SELECT o.*, u.name as user_name, u.email as user_email, p.title as product_title, p.price 
        FROM orders o 
        JOIN users u ON o.user_id = u.id 
        JOIN products p ON o.product_id = p.id 
        ORDER BY o.created_at DESC
    ");
    $stmt->execute();
    $orders = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Order Fetch Error: " . $e->getMessage());
    $orders = [];
}

$page_title = "Manage Orders";
require_once '../includes/header.php';
?>

<style>
    .admin-nav { background: var(--bg-glass); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 16px 24px; margin-bottom: 32px; display: flex; gap: 24px; flex-wrap: wrap; }
    .admin-nav-link { color: var(--text-secondary); font-weight: 600; transition: color 0.2s; text-decoration: none; }
    .admin-nav-link.active { color: var(--accent-orange); }
    
    .table-container { overflow-x: auto; background: var(--bg-glass); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 24px; }
    .data-table { width: 100%; border-collapse: collapse; text-align: left; }
    .data-table th, .data-table td { padding: 16px; border-bottom: 1px solid var(--border-color); font-size: 0.95rem; }
    .data-table th { color: var(--text-muted); font-weight: 600; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 0.05em; }
    .data-table tr:last-child td { border-bottom: none; }
    
    .status-badge { display: inline-block; padding: 6px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
    .status-pending { background: rgba(245, 158, 11, 0.1); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.3); }
    .status-approved { background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.3); }
    .status-rejected { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3); }
    
    .trx-box { background: rgba(255, 107, 0, 0.1); color: var(--accent-orange); padding: 4px 8px; border-radius: 4px; font-family: monospace; font-size: 0.9rem; border: 1px dashed var(--accent-orange); display: inline-block;}
    
    .action-form { display: flex; gap: 8px; align-items: center; }
    .status-select { padding: 8px 12px; border-radius: 4px; border: 1px solid var(--border-color); background: rgba(0,0,0,0.3); color: var(--text-primary); outline: none; font-size: 0.85rem; }
    .status-select option { background: var(--bg-main); color: var(--text-primary); }
    .btn-update { padding: 8px 16px; font-size: 0.85rem; border: none; cursor: pointer; border-radius: 4px; background: var(--accent-gradient); color: #fff; font-weight: 600; }
</style>

<div class="container" style="padding: 40px 15px;">
    
    <div style="margin-bottom: 32px;">
        <h1 style="font-size: 2rem;">Order Management</h1>
        <p class="text-secondary">Verify payments and approve or reject user orders.</p>
    </div>

    <nav class="admin-nav">
        <a href="dashboard.php" class="admin-nav-link">Dashboard</a>
        <a href="products.php" class="admin-nav-link">Products</a>
        <a href="orders.php" class="admin-nav-link active">Orders</a>
        <a href="users.php" class="admin-nav-link">Users</a>
        <a href="settings.php" class="admin-nav-link">Settings</a>
    </nav>

    <?php if (!empty($orders)): ?>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Order Info</th>
                        <th>Customer</th>
                        <th>Product & Price</th>
                        <th>Transaction ID</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>
                                <strong>#<?php echo $order['id']; ?></strong><br>
                                <span class="text-muted" style="font-size: 0.8rem;"><?php echo format_date($order['created_at']); ?></span>
                            </td>
                            <td>
                                <div style="font-weight: 600;"><?php echo htmlspecialchars($order['user_name']); ?></div>
                                <div class="text-muted" style="font-size: 0.85rem;"><?php echo htmlspecialchars($order['user_email']); ?></div>
                            </td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>/product.php?slug=<?php echo htmlspecialchars($order['product_id']); /* Note: ideally link by slug, but ID is fine for admin */ ?>" style="color: var(--text-primary); text-decoration: none; font-weight: 500;" target="_blank">
                                    <?php echo htmlspecialchars($order['product_title']); ?>
                                </a><br>
                                <span style="color: var(--accent-orange); font-weight: 600;"><?php echo format_price($order['price']); ?></span>
                            </td>
                            <td>
                                <?php if (!empty($order['transaction_id'])): ?>
                                    <span class="trx-box"><?php echo htmlspecialchars($order['transaction_id']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted" style="font-size: 0.85rem;">Not Provided</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo htmlspecialchars($order['status']); ?>">
                                    <?php echo ucfirst(htmlspecialchars($order['status'])); ?>
                                </span>
                            </td>
                            <td>
                                <form action="" method="POST" class="action-form">
                                    <?php echo csrf_field(); ?>
                                    <input type="hidden" name="update_status" value="1">
                                    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                    
                                    <select name="status" class="status-select">
                                        <option value="pending" <?php echo $order['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="approved" <?php echo $order['status'] === 'approved' ? 'selected' : ''; ?>>Approve</option>
                                        <option value="rejected" <?php echo $order['status'] === 'rejected' ? 'selected' : ''; ?>>Reject</option>
                                    </select>
                                    
                                    <button type="submit" class="btn-update">Update</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <div class="glass-card" style="text-align: center; padding: 60px;">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom: 16px;"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
            <h3 style="margin-bottom: 8px;">No Orders Yet</h3>
            <p class="text-secondary">When customers place orders, they will appear here for verification.</p>
        </div>
    <?php endif; ?>

</div>

<?php require_once '../includes/footer.php'; ?>