<?php
include("../db/cn.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


if (!isset($_GET['order_id']) || empty($_GET['order_id'])) {
    echo "<script>alert('Order ID missing.'); window.history.back();</script>";
    exit;
}

$order_id = mysqli_real_escape_string($connection, trim($_GET['order_id']));

function qrun($conn, $sql) {
    $res = mysqli_query($conn, $sql);
    if ($res === false) {
        throw new Exception("MySQL error: " . mysqli_error($conn) . " — Query: " . $sql);
    }
    return $res;
}

mysqli_begin_transaction($connection);

try {
    // 1) Detect items table (order_id, product_id, quantity)
    $itemsTable = null;
    $sqlDetectItems = "
        SELECT TABLE_NAME, GROUP_CONCAT(COLUMN_NAME) AS cols
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND COLUMN_NAME IN ('order_id','product_id','quantity')
        GROUP BY TABLE_NAME
        HAVING COUNT(DISTINCT COLUMN_NAME) = 3
        LIMIT 1
    ";
    $res = mysqli_query($connection, $sqlDetectItems);
    if ($res && mysqli_num_rows($res) > 0) {
        $r = mysqli_fetch_assoc($res);
        $itemsTable = $r['TABLE_NAME'];
    }

    // 2) Restore stock if items table found
    if ($itemsTable) {
        $sqlItems = "SELECT product_id, quantity FROM `{$itemsTable}` WHERE order_id = '{$order_id}'";
        $resItems = mysqli_query($connection, $sqlItems);
        if ($resItems === false) throw new Exception("Error fetching order items: " . mysqli_error($connection));

        while ($item = mysqli_fetch_assoc($resItems)) {
            $pid = mysqli_real_escape_string($connection, $item['product_id']);
            $qty = (float)$item['quantity'];
            if ($qty > 0) {
                $sqlUpdateProd = "UPDATE products SET quantity = quantity + {$qty} WHERE product_id = '{$pid}'";
                qrun($connection, $sqlUpdateProd);
            }
        }
    }

    // 3) Detect status table (order_id, status)
    $statusTable = null;
    $sqlDetectStatus = "
        SELECT TABLE_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND COLUMN_NAME IN ('order_id','status')
        GROUP BY TABLE_NAME
        HAVING COUNT(DISTINCT COLUMN_NAME) = 2
        LIMIT 1
    ";
    $resS = mysqli_query($connection, $sqlDetectStatus);
    if ($resS && mysqli_num_rows($resS) > 0) {
        $r = mysqli_fetch_assoc($resS);
        $statusTable = $r['TABLE_NAME'];
    }

    // 4) Update status if found
    if ($statusTable) {
        $sqlUpdateStatus = "UPDATE `{$statusTable}` SET status = 'refund' WHERE order_id = '{$order_id}'";
        qrun($connection, $sqlUpdateStatus);
    }

    mysqli_commit($connection);
    echo "<script>alert('Order refunded successfully.'); window.location.href = document.referrer ? document.referrer : 'index.php';</script>";
    exit;
} catch (Exception $ex) {
    mysqli_rollback($connection);
    $err = addslashes($ex->getMessage());
    echo "<script>alert('Refund failed: {$err}'); window.history.back();</script>";
    exit;
}
