<?php
include 'includes/auth.php';
include 'db.php';

if(isset($_POST['transfer'])){
    $product_id = intval($_POST['product_id']);
    $from_store = intval($_POST['from_store_id']);
    $to_store = intval($_POST['to_store_id']);
    $qty = intval($_POST['quantity']);

    if(!$to_store || $qty <=0){
        echo "<script>alert('Select store and enter quantity');window.history.back();</script>";
        exit;
    }

    // Deduct from from_store
    $conn->query("UPDATE store_stock SET quantity = quantity - $qty WHERE product_id=$product_id AND store_id=$from_store");

    // Add to to_store
    $existing = $conn->query("SELECT * FROM store_stock WHERE product_id=$product_id AND store_id=$to_store")->fetch_assoc();
    if($existing){
        $conn->query("UPDATE store_stock SET quantity = quantity + $qty WHERE product_id=$product_id AND store_id=$to_store");
    } else {
        $conn->query("INSERT INTO store_stock (product_id, store_id, quantity) VALUES ($product_id, $to_store, $qty)");
    }

    // Log movement
    $conn->query("INSERT INTO stock_movements (product_id, from_store_id, to_store_id, quantity, movement_type, notes) 
                  VALUES ($product_id, $from_store, $to_store, $qty, 'Transfer', 'Transferred $qty units')");

    echo "<script>alert('Stock transferred successfully');window.location='store_inventory.php?store_id=$from_store';</script>";
}
?>
