<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

include("db_connect.php");

if (!isset($_GET['id'])) {
    header("Location: today_transaction_history.php");
    exit();
}

$sale_id = intval($_GET['id']);

// Fetch original sale (including receipt_id if your table has it)
$query  = "SELECT * FROM sales WHERE id = $sale_id";
$result = mysqli_query($conn, $query);
$sale   = mysqli_fetch_assoc($result);

if (!$sale) {
    header("Location: today_transaction_history.php?error=notfound");
    exit();
}

if ($sale['refunded'] == 1) {
    header("Location: today_transaction_history.php?error=already_refunded");
    exit();
}

$product_id  = (int)$sale['product_id'];
$quantity    = (float)$sale['quantity'];
$buy_price   = (float)$sale['buying_price'];
$sell_price  = (float)$sale['selling_price'];
$total_sale  = (float)$sale['total_sale'];
$profit      = (float)$sale['profit'];
$receipt_id  = isset($sale['receipt_id']) ? $sale['receipt_id'] : null;
$cashier     = $_SESSION['username'];
$datetime    = date("Y-m-d H:i:s");

// 1️⃣ Restore stock
mysqli_query($conn, "
    UPDATE products 
    SET quantity = quantity + $quantity 
    WHERE id = $product_id
");

// 2️⃣ Mark original sale as refunded (1 = original refunded)
mysqli_query($conn, "
    UPDATE sales 
    SET refunded = 1 
    WHERE id = $sale_id
");

// 3️⃣ Add a negative sale entry to remove totals
// refunded = 2 => compensating negative entry
// IMPORTANT: use same receipt_id so it appears under the same receipt history
$receipt_sql_part = $receipt_id ? "'" . $conn->real_escape_string($receipt_id) . "'" : "NULL";

mysqli_query($conn, "
    INSERT INTO sales (
        receipt_id,
        sale_datetime,
        cashier,
        product_id,
        quantity,
        buying_price,
        selling_price,
        total_sale,
        profit,
        refunded
    )
    VALUES (
        $receipt_sql_part,
        '$datetime',
        '$cashier',
        $product_id,
        -$quantity,
        $buy_price,
        $sell_price,
        -$total_sale,
        -$profit,
        2
    )
");

// At this point, refund is done. Show a confirmation page with options instead of redirecting.
$page_title = "Refund Complete";

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?> | Cashier POS</title>
    <?php include 'cashier_head.php'; ?>
    <style>
        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        .refund-card {
            max-width: 620px;
            margin: 40px auto;
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.12), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 20px 24px 22px;
            border: 1px solid var(--cash-border-soft);
            box-shadow: 0 18px 40px rgba(0,0,0,0.55);
            color: var(--cash-text-main);
            text-align: left;
        }

        html[data-theme="light"] .refund-card {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.16), transparent 55%),
                #ffffff;
            border-color: #dbeafe;
            box-shadow: 0 12px 26px rgba(15,23,42,0.14);
            color: #0f172a;
        }

        .refund-card h1 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .refund-card p {
            font-size: 13px;
            color: var(--cash-text-muted);
            margin: 4px 0 10px;
        }

        html[data-theme="light"] .refund-card p {
            color: #64748b;
        }

        .refund-details {
            font-size: 13px;
            padding: 10px 12px;
            border-radius: 12px;
            background: rgba(15,23,42,0.7);
            border: 1px solid rgba(148,163,184,0.7);
            margin-bottom: 16px;
        }

        html[data-theme="light"] .refund-details {
            background: #eff6ff;
            border-color: #bfdbfe;
        }

        .refund-details div {
            margin-bottom: 4px;
        }

        .refund-label {
            font-weight: 500;
            margin-right: 4px;
        }

        .refund-actions {
            margin-top: 10px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .btn-primary {
            padding: 9px 16px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            box-shadow: 0 10px 26px rgba(0,0,0,0.45);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .btn-primary:hover {
            filter: brightness(1.06);
        }

        .btn-secondary {
            padding: 9px 16px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.8);
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            background: rgba(15,23,42,0.9);
            color: #E9F5FF;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .btn-secondary:hover {
            background: rgba(15,23,42,1);
        }

        html[data-theme="light"] .btn-secondary {
            background: #f3f4f6;
            border-color: #cbd5f5;
            color: #0f172a;
        }

        html[data-theme="light"] .btn-secondary:hover {
            background: #e5e7eb;
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">
        <section class="refund-card">
            <h1>Refund processed</h1>
            <p>The selected sale has been refunded successfully.</p>

            <div class="refund-details">
                <?php if ($receipt_id): ?>
                    <div>
                        <span class="refund-label">Receipt #:</span>
                        <span><?= htmlspecialchars($receipt_id) ?></span>
                    </div>
                <?php endif; ?>
                <div>
                    <span class="refund-label">Product:</span>
                    <span><?= htmlspecialchars($sale['product_id'] . ' - ' . ($sale['product_name'] ?? '')) ?></span>
                </div>
                <div>
                    <span class="refund-label">Quantity refunded:</span>
                    <span><?= htmlspecialchars($quantity) ?></span>
                </div>
                <div>
                    <span class="refund-label">Amount refunded:</span>
                    <span>KES <?= number_format($total_sale, 2) ?></span>
                </div>
            </div>

            <div class="refund-actions">
                <?php if ($receipt_id): ?>
                    <!-- Open the (refund) receipt in new tab/window -->
                    <a href="receipt.php?id=<?= urlencode($receipt_id) ?>" target="_blank" class="btn-primary">
                        Print refund receipt
                    </a>
                <?php endif; ?>

                <!-- Back to today’s transaction history / sales page -->
                <a href="today_transaction_history.php" class="btn-secondary">
                    ← Back to today’s sales
                </a>
            </div>
        </section>
    </main>
</div>

</body>
</html>
