<?php
session_start();
include '../config/db.php';

// Check if user is authorized
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'manager')) {
    header("Location: login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $receipt = $_POST['receipt'];
    $drug_ids = $_POST['drug_id'];
    $refund_quantities = $_POST['refund_quantity'];
    $username = $_SESSION['username'];
    $refund_date = date('Y-m-d H:i:s');
   
    try {
        $pdo->beginTransaction();

        // Check if the sale exists
        $checkSaleStmt = $pdo->prepare("SELECT id FROM sales WHERE receipt = ? LIMIT 1");
        $checkSaleStmt->execute([$receipt]);
        $sale = $checkSaleStmt->fetch(PDO::FETCH_ASSOC);

        if (!$sale) {
            throw new Exception("Sale record not found for receipt: $receipt");
        }

        $sale_id = $sale['id'];

        foreach ($drug_ids as $index => $drug_id) {
            $refund_quantity = (int)$refund_quantities[$index];

            // Skip if refund quantity is 0
            if ($refund_quantity <= 0) {
                continue;
            }

            // Get sale details for this drug
            $getSaleDetailsStmt = $pdo->prepare("
                SELECT total, profit, quantity, discount, 
                       payment_amount1, payment_amount2 
                FROM sales 
                WHERE receipt = ? AND drug_id = ?
            ");
            $getSaleDetailsStmt->execute([$receipt, $drug_id]);
            $saleDetails = $getSaleDetailsStmt->fetch(PDO::FETCH_ASSOC);

            if (!$saleDetails || $saleDetails['quantity'] <= 0) {
                continue;
            }

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

            // Calculate refund amounts
            $unit_price = $saleDetails['total'] / $saleDetails['quantity'];
            $unit_profit = $saleDetails['profit'] / $saleDetails['quantity'];
            $refund_amount = $refund_quantity * $unit_price;
            $refund_profit = $refund_quantity * $unit_profit;
            $discount_refund = ($saleDetails['discount'] / $saleDetails['quantity']) * $refund_quantity;

            // Calculate payment splits
            $total_payment = $saleDetails['payment_amount1'] + $saleDetails['payment_amount2'];
            $refund_from_amount1 = ($saleDetails['payment_amount1'] / $total_payment) * $refund_amount;
            $refund_from_amount2 = ($saleDetails['payment_amount2'] / $total_payment) * $refund_amount;

            // Update sales record - removed the DELETE operation
            $salesUpdateStmt = $pdo->prepare("
                UPDATE sales 
                SET total = CASE 
                        WHEN (total - ?) < 0 THEN 0 
                        ELSE total - ? 
                    END,
                    profit = CASE 
                        WHEN (profit - ?) < 0 THEN 0 
                        ELSE profit - ? 
                    END,
                    quantity = CASE 
                        WHEN (quantity - ?) < 0 THEN 0 
                        ELSE quantity - ? 
                    END,
                    discount = CASE 
                        WHEN (discount - ?) < 0 THEN 0 
                        ELSE discount - ? 
                    END,
                    payment_amount1 = CASE 
                        WHEN (payment_amount1 - ?) < 0 THEN 0 
                        ELSE payment_amount1 - ? 
                    END,
                    payment_amount2 = CASE 
                        WHEN (payment_amount2 - ?) < 0 THEN 0 
                        ELSE payment_amount2 - ? 
                    END
                WHERE receipt = ? AND drug_id = ?
            ");
            $salesUpdateStmt->execute([
                $refund_amount, $refund_amount,
                $refund_profit, $refund_profit,
                $refund_quantity, $refund_quantity,
                $discount_refund, $discount_refund,
                $refund_from_amount1, $refund_from_amount1,
                $refund_from_amount2, $refund_from_amount2,
                $receipt, 
                $drug_id
            ]);

            // Get drug name and update stock
            $getDrugStmt = $pdo->prepare("
                SELECT id, drug_name, quantity 
                FROM drugs 
                WHERE id = ?
            ");
            $getDrugStmt->execute([$drug_id]);
            $drug = $getDrugStmt->fetch(PDO::FETCH_ASSOC);

            // Only process refund records and history for items with actual refunds
            if ($drug && $refund_quantity > 0) {
                // Update drug quantity
                $new_quantity = $drug['quantity'] + $refund_quantity;
                $drugsUpdateStmt = $pdo->prepare("UPDATE drugs SET quantity = ? WHERE id = ?");
                $drugsUpdateStmt->execute([$new_quantity, $drug_id]);

                // Insert refund record only for refunded items
                $refundStmt = $pdo->prepare("
                    INSERT INTO refund (
                        sale_id, drug_id, drug_name, quantity, 
                        refunded_by, refund_date
                    ) VALUES (?, ?, ?, ?, ?, ?)
                ");
                $refundStmt->execute([
                    $sale_id,
                    $drug_id,
                    $drug['drug_name'],
                    $refund_quantity,
                    $username,
                    $refund_date
                ]);

                // Log to drug history only for refunded items
                $historyStmt = $pdo->prepare("
                    INSERT INTO drug_history (
                        drug_id, action, quantity, details, 
                        user, action_date
                    ) VALUES (?, ?, ?, ?, ?, ?)
                ");
                $historyStmt->execute([
                    $drug_id,
                    'Refund',
                    $refund_quantity,
                    "Refunded quantity of $refund_quantity units of {$drug['drug_name']}",
                    $username,
                    $refund_date
                ]);
            }
        }

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

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