<?php
/**
 * Admin Order View - COMPLETE FIXED VERSION
 * Digital Product Store
 */

$page_title = 'View Order';
require_once __DIR__ . '/includes/header.php';

// Get order ID
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$order_id) {
    set_flash_message('Order not found.', 'danger');
    header('Location: orders.php');
    exit;
}

// Get order details - FIXED: Use user_id instead of customer_id, join with users table
$stmt = $pdo->prepare("SELECT o.*, u.name as user_name, u.email as user_email 
                       FROM orders o 
                       LEFT JOIN users u ON o.user_id = u.id 
                       WHERE o.id = ?");
$stmt->execute([$order_id]);
$order = $stmt->fetch();

if (!$order) {
    set_flash_message('Order not found.', 'danger');
    header('Location: orders.php');
    exit;
}

// Get order items
$stmt = $pdo->prepare("SELECT oi.*, p.name as product_name, p.slug as product_slug, p.image as product_image, p.file_path 
                       FROM order_items oi 
                       JOIN products p ON oi.product_id = p.id 
                       WHERE oi.order_id = ?");
$stmt->execute([$order_id]);
$items = $stmt->fetchAll();

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = sanitize($_POST['status'] ?? '');
    $allowed_statuses = ['pending', 'paid', 'failed', 'refunded'];
    
    if (in_array($new_status, $allowed_statuses)) {
        $stmt = $pdo->prepare("UPDATE orders SET payment_status = ? WHERE id = ?");
        if ($stmt->execute([$new_status, $order_id])) {
            // Refresh order data
            $stmt = $pdo->prepare("SELECT o.*, u.name as user_name, u.email as user_email 
                                   FROM orders o 
                                   LEFT JOIN users u ON o.user_id = u.id 
                                   WHERE o.id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            set_flash_message('Order status updated successfully.', 'success');
        } else {
            set_flash_message('Failed to update order status.', 'danger');
        }
    }
    header('Location: order-view.php?id=' . $order_id);
    exit;
}

// Handle resend email
if (isset($_GET['resend_email'])) {
    if (send_order_confirmation($order_id)) {
        set_flash_message('Order confirmation email resent.', 'success');
    } else {
        set_flash_message('Failed to resend email.', 'danger');
    }
    header('Location: order-view.php?id=' . $order_id);
    exit;
}
?>

<div class="page-header">
    <div>
        <h1>Order #<?php echo $order['order_number']; ?></h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/orders.php">Orders</a></li>
                <li class="breadcrumb-item active">View Order</li>
            </ol>
        </nav>
    </div>
    <div>
        <a href="?id=<?php echo $order_id; ?>&resend_email=1" class="btn btn-outline-primary" onclick="return confirm('Resend order confirmation email?')">
            <i class="fas fa-envelope"></i> Resend Email
        </a>
        <a href="orders.php" class="btn btn-outline-secondary ms-2">
            <i class="fas fa-arrow-left"></i> Back to Orders
        </a>
    </div>
</div>

<div class="row">
    <!-- Order Details -->
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-shopping-cart me-2"></i>Order Items</h5>
                <span class="badge bg-<?php echo $order['payment_status'] === 'paid' ? 'success' : ($order['payment_status'] === 'failed' ? 'danger' : 'warning'); ?>">
                    <?php echo ucfirst($order['payment_status']); ?>
                </span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Product</th>
                                <th>Price</th>
                                <th>Qty</th>
                                <th>Total</th>
                                <th>Download</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <img src="<?php echo $item['product_image'] ? '../' . $item['product_image'] : 'https://via.placeholder.com/50'; ?>" 
                                             alt="" class="me-2" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                                        <a href="<?php echo BASE_URL; ?>/product.php?slug=<?php echo $item['product_slug']; ?>" target="_blank">
                                            <?php echo sanitize($item['product_name']); ?>
                                        </a>
                                    </div>
                                </td>
                                <td><?php echo format_price($item['price']); ?></td>
                                <td><?php echo $item['quantity']; ?></td>
                                <td><?php echo format_price($item['price'] * $item['quantity']); ?></td>
                                <td>
                                    <?php if ($order['payment_status'] === 'paid' && $item['file_path']): ?>
                                    <span class="badge bg-success">
                                        <i class="fas fa-check"></i> Available
                                    </span>
                                    <?php else: ?>
                                    <span class="badge bg-secondary">
                                        <i class="fas fa-lock"></i> Locked
                                    </span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td colspan="3" class="text-end"><strong>Subtotal:</strong></td>
                                <td><strong><?php echo format_price($order['subtotal']); ?></strong></td>
                                <td></td>
                            </tr>
                            <?php if ($order['discount'] > 0): ?>
                            <tr>
                                <td colspan="3" class="text-end"><strong>Discount:</strong></td>
                                <td class="text-danger">-<?php echo format_price($order['discount']); ?></td>
                                <td></td>
                            </tr>
                            <?php endif; ?>
                            <?php if ($order['tax'] > 0): ?>
                            <tr>
                                <td colspan="3" class="text-end"><strong>Tax:</strong></td>
                                <td><?php echo format_price($order['tax']); ?></td>
                                <td></td>
                            </tr>
                            <?php endif; ?>
                            <?php if ($order['shipping'] > 0): ?>
                            <tr>
                                <td colspan="3" class="text-end"><strong>Shipping:</strong></td>
                                <td><?php echo format_price($order['shipping']); ?></td>
                                <td></td>
                            </tr>
                            <?php endif; ?>
                            <tr>
                                <td colspan="3" class="text-end"><strong>Total:</strong></td>
                                <td><strong class="text-primary"><?php echo format_price($order['total']); ?></strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Payment Information -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-credit-card me-2"></i>Payment Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Payment Method:</strong> <?php echo ucfirst($order['payment_method'] ?? 'N/A'); ?></p>
                        <p><strong>Payment Status:</strong> 
                            <span class="badge bg-<?php echo $order['payment_status'] === 'paid' ? 'success' : ($order['payment_status'] === 'pending' ? 'warning' : 'danger'); ?>">
                                <?php echo ucfirst($order['payment_status']); ?>
                            </span>
                        </p>
                    </div>
                    <div class="col-md-6">
                        <?php if ($order['payment_id']): ?>
                        <p><strong>Transaction ID:</strong> <?php echo $order['payment_id']; ?></p>
                        <?php endif; ?>
                        <?php if ($order['coupon_code']): ?>
                        <p><strong>Coupon Used:</strong> <span class="badge bg-info"><?php echo $order['coupon_code']; ?></span></p>
                        <?php endif; ?>
                        <p><strong>Order Date:</strong> <?php echo format_datetime($order['created_at']); ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Customer Information -->
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-user me-2"></i>Customer Information</h5>
            </div>
            <div class="card-body">
                <p><strong>Name:</strong> <?php echo sanitize($order['customer_name'] ?: ($order['user_name'] ?? 'Guest')); ?></p>
                <p><strong>Email:</strong> <?php echo sanitize($order['customer_email'] ?: ($order['user_email'] ?? 'N/A')); ?></p>
                <?php if ($order['customer_phone']): ?>
                <p><strong>Phone:</strong> <?php echo sanitize($order['customer_phone']); ?></p>
                <?php endif; ?>
                <?php if ($order['user_id']): ?>
                <p><strong>User ID:</strong> #<?php echo $order['user_id']; ?></p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Update Status -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-sync me-2"></i>Update Status</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <?php echo csrf_field(); ?>
                    <div class="mb-3">
                        <label class="form-label">Payment Status</label>
                        <select name="status" class="form-select">
                            <option value="pending" <?php echo $order['payment_status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="paid" <?php echo $order['payment_status'] === 'paid' ? 'selected' : ''; ?>>Paid</option>
                            <option value="failed" <?php echo $order['payment_status'] === 'failed' ? 'selected' : ''; ?>>Failed</option>
                            <option value="refunded" <?php echo $order['payment_status'] === 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                        </select>
                    </div>
                    <button type="submit" name="update_status" class="btn btn-primary w-100">
                        <i class="fas fa-sync"></i> Update Status
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Order Status -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-truck me-2"></i>Order Status</h5>
            </div>
            <div class="card-body">
                <p><strong>Current Status:</strong> 
                    <span class="badge bg-<?php echo $order['order_status'] === 'completed' ? 'success' : ($order['order_status'] === 'cancelled' ? 'danger' : 'info'); ?>">
                        <?php echo ucfirst($order['order_status']); ?>
                    </span>
                </p>
                <?php if ($order['notes']): ?>
                <hr>
                <p><strong>Notes:</strong></p>
                <p class="text-muted"><?php echo nl2br(sanitize($order['notes'])); ?></p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Download Links -->
        <?php if ($order['payment_status'] === 'paid'): ?>
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-download me-2"></i>Download Links</h5>
            </div>
            <div class="card-body">
                <p class="text-muted">Customer can download products using these links:</p>
                <a href="<?php echo BASE_URL; ?>/download.php?order=<?php echo $order['order_number']; ?>" class="btn btn-success w-100" target="_blank">
                    <i class="fas fa-download"></i> Download Page
                </a>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

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