<?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Include database connection
require_once '../config/db.php';

if (isset($_GET['sale_id'])) {
    $sale_id = $_GET['sale_id'];

    try {
        // Start a database transaction
        $pdo->beginTransaction();

        // Retrieve the sale record
        $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = :sale_id AND refunded = 0");
        $stmt->execute(['sale_id' => $sale_id]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$sale) {
            throw new Exception("Sale record not found or already refunded.");
        }

        // Retrieve the drug details
        $stmt = $pdo->prepare("SELECT * FROM drugs WHERE drug_name = :drug_name");
        $stmt->execute(['drug_name' => $sale['drug_name']]);
        $drug = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$drug) {
            throw new Exception("Drug not found.");
        }

        // Update the quantity in the drugs table
        $newQuantity = $drug['quantity'] + $sale['quantity'];
        $stmt = $pdo->prepare("UPDATE drugs SET quantity = :quantity WHERE id = :drug_id");
        $stmt->execute([
            'quantity' => $newQuantity,
            'drug_id' => $drug['id']
        ]);

        // Mark the sale record as refunded
        $stmt = $pdo->prepare("UPDATE sales SET refunded = 1 WHERE id = :sale_id");
        $stmt->execute(['sale_id' => $sale_id]);

        // Commit the transaction
        $pdo->commit();

        // Redirect with a success message
        $_SESSION['success'] = "Sale refunded successfully, and stock updated.";
        header("Location: sales.php");
        exit();

    } catch (Exception $e) {
        // Rollback the transaction in case of an error
        $pdo->rollBack();
        $_SESSION['error'] = "Refund failed: " . $e->getMessage();
        header("Location: sales.php");
        exit();
    }
} else {
    $_SESSION['error'] = "Invalid request.";
    header("Location: sales.php");
    exit();
}
?>
