<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
header('Content-Type: application/json');

// Commission rate used at sale time (keep in sync with process_sale.php)
$commission_rate = 0.01;

$input = json_decode(file_get_contents('php://input'), true);
$item_id = isset($input['item_id']) ? intval($input['item_id']) : 0;
$sale_id = isset($input['sale_id']) ? intval($input['sale_id']) : 0;

if (!$item_id || !$sale_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid item or sale ID']);
    exit;
}

// Ensure refunded column exists once (safe for MySQL 5.7+)
$colCheck = $conn->query("SHOW COLUMNS FROM sale_items LIKE 'refunded'");
if ($colCheck && $colCheck->num_rows === 0) {
    $conn->query("ALTER TABLE sale_items ADD COLUMN refunded TINYINT(1) NOT NULL DEFAULT 0");
}

// Ensure refunds audit table exists
$conn->query("CREATE TABLE IF NOT EXISTS refunds (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sale_id INT NOT NULL,
    sale_item_id INT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    quantity INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (sale_id) REFERENCES sales(id) ON DELETE CASCADE,
    FOREIGN KEY (sale_item_id) REFERENCES sale_items(id) ON DELETE CASCADE
)");

try {
    $conn->begin_transaction();

    // Fetch item with validation
    $stmt = $conn->prepare("SELECT id, sale_id, product_id, quantity, total_price, refunded FROM sale_items WHERE id = ? AND sale_id = ? LIMIT 1");
    $stmt->bind_param('ii', $item_id, $sale_id);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();

    if (!$item) {
        throw new Exception('Sale item not found');
    }

    if (!empty($item['refunded'])) {
        throw new Exception('Item already refunded');
    }

    // Mark as refunded
    $stmt = $conn->prepare("UPDATE sale_items SET refunded = 1 WHERE id = ?");
    $stmt->bind_param('i', $item_id);
    if (!$stmt->execute()) {
        throw new Exception('Failed to mark item refunded');
    }

    // Restock the product by original quantity
    $stmt = $conn->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
    $stmt->bind_param('ii', $item['quantity'], $item['product_id']);
    if (!$stmt->execute()) {
        throw new Exception('Failed to restock product');
    }

    // Log refund event for audit
    $stmt = $conn->prepare("INSERT INTO refunds (sale_id, sale_item_id, amount, quantity) VALUES (?, ?, ?, ?)");
    $amount = $item['total_price'];
    $stmt->bind_param('iidi', $sale_id, $item_id, $amount, $item['quantity']);
    if (!$stmt->execute()) {
        throw new Exception('Failed to record refund');
    }

    // Reduce commission for the sale if one exists
    $commissionStmt = $conn->prepare("SELECT id, commission_amount FROM sales_commissions WHERE sale_id = ? ORDER BY id DESC LIMIT 1");
    if ($commissionStmt) {
        $commissionStmt->bind_param('i', $sale_id);
        $commissionStmt->execute();
        $commissionRow = $commissionStmt->get_result()->fetch_assoc();
        if ($commissionRow) {
            $current_commission = (float)$commissionRow['commission_amount'];
            $deduct = round($amount * $commission_rate, 2);
            $new_commission = max(0, $current_commission - $deduct);

            $updateStmt = $conn->prepare("UPDATE sales_commissions SET commission_amount = ? WHERE id = ?");
            if ($updateStmt) {
                $updateStmt->bind_param('di', $new_commission, $commissionRow['id']);
                if (!$updateStmt->execute()) {
                    throw new Exception('Failed to update commission');
                }
            }

            // Log commission adjustment for traceability
            @file_put_contents(__DIR__ . '/commission_log.txt', date('Y-m-d H:i:s') . " - Refund commission adjust: sale {$sale_id}, item {$item_id}, old {$current_commission}, deduct {$deduct}, new {$new_commission}\n", FILE_APPEND);
        }
    }

    $conn->commit();
    echo json_encode(['success' => true, 'refunded_amount' => $amount]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
