<?php
require_once __DIR__ . '/../functions.php';
requireAuth();
$db = db();
$user = getCurrentUser();
$orderId = (int)($_GET['id'] ?? 0);
$stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
$stmt->execute([$orderId, $user['id']]);
$order = $stmt->fetch();

if (!$order) { header('Location: orders.php'); exit; }

$cancellable = in_array($order['status'], ['pending', 'confirmed']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_order']) && $cancellable) {
    $db->beginTransaction();
    try {
        $stmt = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
        $stmt->execute([$orderId]);
        foreach ($stmt->fetchAll() as $item) {
            $db->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?")->execute([$item['quantity'], $item['product_id']]);
        }
        $db->prepare("UPDATE orders SET status = 'cancelled' WHERE id = ?")->execute([$orderId]);
        $db->commit();
        flash('success', 'Order cancelled successfully.');
        header('Location: order-detail.php?id=' . $orderId);
        exit;
    } catch (Exception $e) {
        $db->rollBack();
        flash('error', 'Failed to cancel order. Please try again.');
    }
}

// Return eligibility
$returnEligible = false;
$existingReturn = null;
if ($order['status'] === 'delivered' && $order['delivered_at']) {
    $daysSinceDelivery = (time() - strtotime($order['delivered_at'])) / 86400;
    if ($daysSinceDelivery <= 7) {
        $returnEligible = true;
    }
    $stmt = $db->prepare("SELECT * FROM returns WHERE order_id = ?");
    $stmt->execute([$orderId]);
    $existingReturn = $stmt->fetch();
    if ($existingReturn) {
        $returnEligible = false;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_return']) && $returnEligible) {
    $reason = $_POST['return_reason'] ?? '';
    $detail = $_POST['return_detail'] ?? '';
    if ($reason) {
        $db->prepare("INSERT INTO returns (order_id, user_id, reason, detail, status) VALUES (?, ?, ?, ?, 'pending')")
            ->execute([$orderId, $user['id'], $reason, $detail]);
        flash('success', 'Return request submitted successfully.');
        header('Location: order-detail.php?id=' . $orderId);
        exit;
    }
    flash('error', 'Please select a reason for return.');
}

$stmt = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
$stmt->execute([$orderId]);
$items = $stmt->fetchAll();
$page_title = 'Order ' . $order['order_number'];

require_once __DIR__ . '/../includes/header.php';
?>
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <a href="orders.php" class="text-sm text-primary-600 hover:underline mb-4 inline-block"><i class="fas fa-arrow-left mr-1"></i> Back to Orders</a>
    <div class="bg-white rounded-xl border border-gray-200 p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <div><h1 class="text-xl font-bold text-gray-800">Order <?= h($order['order_number']) ?></h1><p class="text-sm text-gray-500">Placed on <?= date('d M Y, h:i A', strtotime($order['created_at'])) ?></p></div>
            <div class="text-right"><?= getStatusBadge($order['status']) ?><?php if ($cancellable): ?><form method="POST" class="mt-2" onsubmit="return confirm('Are you sure you want to cancel this order?')"><button type="submit" name="cancel_order" class="text-sm text-red-600 hover:text-red-800 underline">Cancel Order</button></form><?php endif; ?></div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div><span class="text-gray-500">Payment</span><p class="font-medium"><?= ucfirst($order['payment_method']) ?></p></div>
            <div><span class="text-gray-500">Payment Status</span><p><?= getStatusBadge($order['payment_status']) ?></p></div>
            <?php if ($order['shipping_name']): ?>
            <div class="col-span-2"><span class="text-gray-500">Shipping Address</span><p class="font-medium"><?= h($order['shipping_name']) ?>, <?= h($order['shipping_address']) ?>, <?= h($order['shipping_city']) ?>, <?= h($order['shipping_state']) ?> - <?= h($order['shipping_pincode']) ?></p></div>
            <?php endif; ?>
        </div>
    </div>
    <div class="bg-white rounded-xl border border-gray-200 p-6">
        <h2 class="font-semibold text-gray-800 mb-4">Order Items</h2>
        <div class="space-y-4">
            <?php foreach ($items as $item): ?>
            <div class="flex items-start gap-3 pb-4 border-b last:border-0">
                <div class="w-14 h-14 sm:w-16 sm:h-16 bg-gray-50 rounded-lg overflow-hidden shrink-0 flex items-center justify-center">
                    <?php if ($item['image_url']): ?><img src="<?= strpos($item['image_url'], '://') === false ? BASE_PATH . '/' . h($item['image_url']) : h($item['image_url']) ?>" alt="" class="w-full h-full object-cover"><?php else: ?><i class="fas fa-box text-gray-300 text-2xl"></i><?php endif; ?>
                </div>
                <div class="flex-1 min-w-0"><p class="font-medium text-gray-800 text-sm sm:text-base truncate"><?= h($item['product_name']) ?></p><p class="text-sm text-gray-500">Qty: <?= $item['quantity'] ?> x <?= formatPrice($item['unit_price']) ?></p><?php if ($item['variant_info']): ?><p class="text-xs text-gray-400"><?= h($item['variant_info']) ?></p><?php endif; ?></div>
                <p class="font-bold text-sm sm:text-base shrink-0"><?= formatPrice($item['total']) ?></p>
            </div>
            <?php endforeach; ?>
        </div>
        <hr class="my-4">
        <div class="space-y-1 text-sm text-right">
            <div class="flex justify-end gap-4"><span class="text-gray-500">Subtotal:</span><span><?= formatPrice($order['subtotal']) ?></span></div>
            <?php if ($order['discount_amount'] > 0): ?><div class="flex justify-end gap-4"><span class="text-green-600">Discount:</span><span>-<?= formatPrice($order['discount_amount']) ?></span></div><?php endif; ?>
            <div class="flex justify-end gap-4"><span class="text-gray-500">Tax:</span><span><?= formatPrice($order['tax_amount']) ?></span></div>
            <div class="flex justify-end gap-4"><span class="text-gray-500">Shipping:</span><span><?= $order['shipping_amount'] > 0 ? formatPrice($order['shipping_amount']) : 'Free' ?></span></div>
            <div class="flex justify-end gap-4 text-lg font-bold"><span>Total:</span><span><?= formatPrice($order['total']) ?></span></div>
        </div>
    </div>

    <?php if ($existingReturn): ?>
    <div class="bg-white rounded-xl border border-gray-200 p-6 mt-6">
        <h2 class="font-semibold text-gray-800 mb-2">Return Request</h2>
        <p class="text-sm text-gray-600 mb-2">Reason: <?= h($existingReturn['reason']) ?></p>
        <?php if ($existingReturn['detail']): ?><p class="text-sm text-gray-600 mb-2">Details: <?= h($existingReturn['detail']) ?></p><?php endif; ?>
        <p class="mt-1"><?= getStatusBadge($existingReturn['status']) ?></p>
    </div>
    <?php elseif ($returnEligible): ?>
    <div x-data="{ open: false }" class="mt-6">
        <button @click="open = true" class="bg-orange-500 text-white px-6 py-2 rounded-lg font-semibold hover:bg-orange-600 transition text-sm"><i class="fas fa-undo mr-2"></i>Request Return</button>
        <div x-show="open" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" style="display:none" @click.self="open = false">
            <div class="bg-white rounded-xl p-6 w-full max-w-md mx-4">
                <h3 class="text-lg font-bold text-gray-800 mb-4">Request Return</h3>
                <form method="POST">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Reason *</label>
                        <select name="return_reason" required class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm">
                            <option value="">Select a reason</option>
                            <option value="Defective or damaged">Defective or damaged</option>
                            <option value="Wrong item delivered">Wrong item delivered</option>
                            <option value="Not as described">Not as described</option>
                            <option value="Size or fit issue">Size or fit issue</option>
                            <option value="Quality issue">Quality issue</option>
                            <option value="Changed mind">Changed mind</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Additional Details</label>
                        <textarea name="return_detail" rows="3" placeholder="Tell us more..." class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></textarea>
                    </div>
                    <div class="flex gap-3 justify-end">
                        <button type="button" @click="open = false" class="px-4 py-2 text-sm text-gray-600 hover:text-gray-800">Cancel</button>
                        <button type="submit" name="request_return" class="bg-orange-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-orange-600">Submit Request</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
