<?php
session_start();

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sale_id = $_POST['sale_id']; // ID of the sale being refunded
    $refundDetails = $_POST['refund']; // Array of drug_id => quantity to refund

    try {
        $pdo->beginTransaction();

        foreach ($refundDetails as $drug_id => $refund_quantity) {
            // Validate refund quantity
            if ($refund_quantity <= 0) {
                throw new Exception("Invalid refund quantity for drug ID: $drug_id");
            }

            // Fetch sale record for validation
            $stmt = $pdo->prepare("SELECT id, drug_name, quantity FROM sales WHERE id = :sale_id AND drug_name = (SELECT drug_name FROM drugs WHERE id = :drug_id)");
            $stmt->execute(['sale_id' => $sale_id, 'drug_id' => $drug_id]);
            $sale = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$sale) {
                throw new Exception("Sale record not found for sale ID: $sale_id and drug ID: $drug_id");
            }

            if ($refund_quantity > $sale['quantity']) {
                throw new Exception("Refund quantity exceeds sold quantity for drug ID: $drug_id");
            }

            $newQuantity = $sale['quantity'] - $refund_quantity;

            if ($newQuantity > 0) {
                // Update the sales table to reduce the sold quantity
                $updateSale = $pdo->prepare("UPDATE sales SET quantity = :new_quantity WHERE id = :sale_id");
                $updateSale->execute(['new_quantity' => $newQuantity, 'sale_id' => $sale_id]);
            } else {
                // Delete the sale record if fully refunded
                $deleteSale = $pdo->prepare("DELETE FROM sales WHERE id = :sale_id");
                $deleteSale->execute(['sale_id' => $sale_id]);
            }

            // Update the store inventory
            $updateStore = $pdo->prepare("UPDATE drugs SET quantity = quantity + :refund_quantity WHERE id = :drug_id");
            $updateStore->execute(['refund_quantity' => $refund_quantity, 'drug_id' => $drug_id]);

            // Log the refund
            $logRefund = $pdo->prepare("INSERT INTO refunds (sale_id, drug_id, drug_name, quantity, returned_by, return_date) 
                VALUES (:sale_id, :drug_id, :drug_name, :quantity, :returned_by, NOW())");
            $logRefund->execute([
                'sale_id' => $sale['id'],
                'drug_id' => $drug_id,
                'drug_name' => $sale['drug_name'],
                'quantity' => $refund_quantity,
                'returned_by' => $_SESSION['username']
            ]);
        }

        $pdo->commit();
        $_SESSION['success'] = "Refund processed successfully!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Failed to process refund: " . $e->getMessage();
    }

    header("Location: sales.php");
    exit();
}
?>
