<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Returns';
$db = db();

$returnId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($returnId) {
    $stmt = $db->prepare("SELECT r.*, o.order_number, o.total as order_total, u.name as customer_name, u.email as customer_email FROM returns r JOIN orders o ON r.order_id = o.id LEFT JOIN users u ON r.user_id = u.id WHERE r.id = ?");
    $stmt->execute([$returnId]);
    $ret = $stmt->fetch();
    if (!$ret) { header('Location: returns.php'); exit; }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_return'])) {
        $status = $_POST['status'] ?? $ret['status'];
        $adminNotes = $_POST['admin_notes'] ?? '';
        $resolvedAt = in_array($status, ['rejected', 'refunded']) ? date('Y-m-d H:i:s') : null;
        $db->prepare("UPDATE returns SET status=?, admin_notes=?, resolved_at=COALESCE(?, resolved_at) WHERE id=?")
            ->execute([$status, $adminNotes, $resolvedAt, $returnId]);
        if ($status === 'refunded') {
            $db->prepare("UPDATE orders SET payment_status='refunded' WHERE id=?")->execute([$ret['order_id']]);
        }
        flash('success', 'Return updated.');
        header('Location: returns.php?id=' . $returnId);
        exit;
    }

    $stmt = $db->prepare("SELECT ri.*, oi.product_name, oi.unit_price, oi.quantity as ordered_qty FROM return_items ri JOIN order_items oi ON ri.order_item_id = oi.id WHERE ri.return_id = ?");
    $stmt->execute([$returnId]);
    $returnItems = $stmt->fetchAll();

    require_once __DIR__ . '/../includes/admin-header.php';
    ?>
    <a href="returns.php" class="text-sm text-primary-600 hover:underline mb-4 inline-block"><i class="fas fa-arrow-left mr-1"></i> Back to Returns</a>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 space-y-6">
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="font-semibold text-gray-800">Return #<?= $ret['id'] ?> - Order <?= h($ret['order_number']) ?></h2>
                    <?= getStatusBadge($ret['status']) ?>
                </div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div><span class="text-gray-500">Customer</span><p class="font-medium"><?= h($ret['customer_name']) ?> (<?= h($ret['customer_email']) ?>)</p></div>
                    <div><span class="text-gray-500">Order Total</span><p class="font-medium"><?= formatPrice($ret['order_total']) ?></p></div>
                    <div><span class="text-gray-500">Reason</span><p class="font-medium"><?= h($ret['reason']) ?></p></div>
                    <div><span class="text-gray-500">Requested</span><p class="font-medium"><?= date('d M Y, h:i A', strtotime($ret['requested_at'])) ?></p></div>
                    <?php if ($ret['detail']): ?>
                    <div class="col-span-2"><span class="text-gray-500">Details</span><p class="font-medium"><?= h($ret['detail']) ?></p></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="space-y-6">
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h3 class="font-semibold text-gray-800 mb-4">Update Return</h3>
                <form method="POST" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <?php foreach (['pending','approved','rejected','picked_up','refunded'] as $s): ?>
                            <option value="<?= $s ?>" <?= $ret['status'] === $s ? 'selected' : '' ?>><?= ucfirst(str_replace('_', ' ', $s)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Admin Notes</label>
                        <textarea name="admin_notes" rows="3" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"><?= h($ret['admin_notes'] ?? '') ?></textarea>
                    </div>
                    <button type="submit" name="update_return" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700">Update</button>
                </form>
            </div>
        </div>
    </div>
    <?php
    require_once __DIR__ . '/../includes/admin-footer.php';
    exit;
}

// List all returns
$returns = $db->query("SELECT r.*, o.order_number, u.name as customer_name FROM returns r JOIN orders o ON r.order_id = o.id LEFT JOIN users u ON r.user_id = u.id ORDER BY r.requested_at DESC")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">ID</th><th class="px-4 py-3 font-medium">Order</th><th class="px-4 py-3 font-medium">Customer</th><th class="px-4 py-3 font-medium">Reason</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium">Date</th><th class="px-4 py-3 font-medium"></th></tr></thead>
        <tbody>
            <?php foreach ($returns as $r): ?>
            <tr class="border-t hover:bg-gray-50">
                <td class="px-4 py-3 font-medium">#<?= $r['id'] ?></td>
                <td class="px-4 py-3"><?= h($r['order_number']) ?></td>
                <td class="px-4 py-3"><?= h($r['customer_name'] ?? 'N/A') ?></td>
                <td class="px-4 py-3 text-gray-600"><?= h($r['reason']) ?></td>
                <td class="px-4 py-3"><?= getStatusBadge($r['status']) ?></td>
                <td class="px-4 py-3 text-gray-500"><?= date('d M Y', strtotime($r['requested_at'])) ?></td>
                <td class="px-4 py-3"><a href="returns.php?id=<?= $r['id'] ?>" class="text-primary-600 hover:underline">View</a></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
