<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)($_POST['product_id'] ?? 0);
    $store_id = (int)($_POST['store_id'] ?? 0);
    $adjustment_qty = (int)($_POST['adjustment_qty'] ?? 0);
    $reason = trim($_POST['reason'] ?? '');
    $user_id = $_SESSION['user_id'];

    // Basic validation
    if ($product_id <= 0 || $store_id <= 0 || $adjustment_qty == 0 || $reason === '') {
        $_SESSION['error'] = 'All fields are required and quantity cannot be zero.';
        header('Location: adjust_stock.php');
        exit();
    }

    // Begin transaction
    $conn->begin_transaction();

    try {
        // Lock inventory record for update
        $stmt = $conn->prepare("SELECT quantity FROM inventory WHERE product_id = ? AND store_id = ? FOR UPDATE");
        $stmt->bind_param("ii", $product_id, $store_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows) {
            $current_qty = $result->fetch_assoc()['quantity'];
            $new_qty = $current_qty + $adjustment_qty;

            if ($new_qty < 0) {
                throw new Exception("Adjustment would result in negative stock. Operation aborted.");
            }

            // Update inventory quantity
            $update_stmt = $conn->prepare("UPDATE inventory SET quantity = ?, modified_at = NOW() WHERE product_id = ? AND store_id = ?");
            $update_stmt->bind_param("iii", $new_qty, $product_id, $store_id);
            $update_stmt->execute();
        } else {
            // No inventory record: only allow positive addition
            if ($adjustment_qty < 0) {
                throw new Exception("Cannot reduce stock; no existing inventory record.");
            }
            $new_qty = $adjustment_qty;
            $insert_stmt = $conn->prepare("INSERT INTO inventory (product_id, store_id, quantity, created_at, modified_at) VALUES (?, ?, ?, NOW(), NOW())");
            $insert_stmt->bind_param("iii", $product_id, $store_id, $new_qty);
            $insert_stmt->execute();
        }

        // Insert stock adjustment record
        $insert_adj = $conn->prepare("INSERT INTO stock_adjustments (product_id, store_id, adjustment_qty, reason, adjusted_by, adjustment_date) VALUES (?, ?, ?, ?, ?, NOW())");
        $insert_adj->bind_param("iiisi", $product_id, $store_id, $adjustment_qty, $reason, $user_id);
        $insert_adj->execute();
// Audit Logging Section
include('../../includes/config.php'); // if not already included

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$module = 'Stock Adjustment';
$action = 'adjust_stock';
$device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
$now = date("Y-m-d H:i:s");

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

$details = json_encode([
    'product_id'    => $product_id,
    'product_name'  => $product_name,
    'store_id'      => $store_id,
    'adjustment_qty'=> $adjustment_qty,
    'reason'        => $reason,
    'timestamp'     => $now
]);

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

        // Insert audit log entry
        $action = "Stock adjustment";
        $details = json_encode([
            'product_id' => $product_id,
            'store_id' => $store_id,
            'adjustment_qty' => $adjustment_qty,
            'reason' => $reason,
            'new_quantity' => $new_qty
        ]);
        $insert_audit = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at) VALUES (?, ?, ?, NOW())");
        $insert_audit->bind_param("iss", $user_id, $action, $details);
        $insert_audit->execute();

        $conn->commit();

        $_SESSION['success'] = "Stock adjusted successfully. New quantity: $new_qty";
        header("Location: adjust_stock.php");
        exit();

    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = "Error: " . $e->getMessage();
        header("Location: adjust_stock.php");
        exit();
    }
} else {
    header("Location: adjust_stock.php");
    exit();
}
