<?php
session_start();
header('Content-Type: application/json');
include('../../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

$from_store = isset($_POST['from_store']) ? (int)$_POST['from_store'] : 0;
$to_store = isset($_POST['to_store']) ? (int)$_POST['to_store'] : 0;
$product = isset($_POST['product']) ? (int)$_POST['product'] : 0;
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
$remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';

if ($from_store <= 0 || $to_store <= 0 || $product <= 0 || $quantity <= 0) {
    echo json_encode(['success' => false, 'message' => 'Missing or invalid data']);
    exit;
}

if ($from_store === $to_store) {
    echo json_encode(['success' => false, 'message' => 'From Store and To Store cannot be the same']);
    exit;
}

// Check available quantity in from_store
$stmt = $conn->prepare("SELECT quantity FROM inventory WHERE store_id = ? AND product_id = ?");
$stmt->bind_param("ii", $from_store, $product);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$stmt->close();

$available_qty = $result ? (int)$result['quantity'] : 0;

if ($available_qty < $quantity) {
    echo json_encode(['success' => false, 'message' => 'Insufficient stock in source store']);
    exit;
}

$conn->begin_transaction();

try {
    // Deduct from source store
    $stmt = $conn->prepare("UPDATE inventory SET quantity = quantity - ? WHERE store_id = ? AND product_id = ?");
    $stmt->bind_param("iii", $quantity, $from_store, $product);
    $stmt->execute();
    $stmt->close();

    // Add to destination store
    $stmt = $conn->prepare("SELECT quantity FROM inventory WHERE store_id = ? AND product_id = ?");
    $stmt->bind_param("ii", $to_store, $product);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($res) {
        $stmt = $conn->prepare("UPDATE inventory SET quantity = quantity + ? WHERE store_id = ? AND product_id = ?");
        $stmt->bind_param("iii", $quantity, $to_store, $product);
        $stmt->execute();
        $stmt->close();
    } else {
        $stmt = $conn->prepare("
            INSERT INTO inventory (store_id, product_id, quantity, restock_threshold, cost_price, selling_price, vat_rate) 
            SELECT ?, id, ?, 0, 0, 0, 0 FROM products WHERE id = ?
        ");
        $stmt->bind_param("iii", $to_store, $quantity, $product);
        $stmt->execute();
        $stmt->close();
    }

    // ✅ Log in stock_transfer_log
    $stmt = $conn->prepare("
        INSERT INTO stock_transfer_log (product_id, from_store_id, to_store_id, quantity, transferred_by, remarks, transfer_date)
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->bind_param("iiiiss", $product, $from_store, $to_store, $quantity, $user_id, $remarks);
    $stmt->execute();
    $stmt->close();

    // ✅ Audit Logging
    $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $module = 'Stock Transfer';
    $action = 'transfer_stock';
    $now = date("Y-m-d H:i:s");

    // Fetch product name
    $product_name = '';
    $stmt = $conn->prepare("SELECT product_name FROM products WHERE id = ?");
    $stmt->bind_param("i", $product);
    $stmt->execute();
    $stmt->bind_result($product_name);
    $stmt->fetch();
    $stmt->close();

    $details = json_encode([
        'product_id' => $product,
        'product_name' => $product_name,
        'quantity' => $quantity,
        'from_store_id' => $from_store,
        'to_store_id' => $to_store,
        'remarks' => $remarks,
        'timestamp' => $now
    ]);

    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info)
                            VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issssis", $user_id, $action, $details, $now, $module, $role_id, $device_info);
    $stmt->execute();
    $stmt->close();

    $conn->commit();
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Transaction failed: ' . $e->getMessage()]);
}
?>
