<?php
session_start();
include('../../includes/config.php');

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)$_POST['product_id'];
    $store_id = (int)$_POST['store_id'];
    $quantity = (int)$_POST['quantity'];
    $cost_price = (float)$_POST['cost_price'];
    $purchase_date = $_POST['purchase_date'];
    $remarks = trim($_POST['remarks'] ?? '');
    $supplier_id = isset($_POST['supplier_id']) && $_POST['supplier_id'] !== '' ? (int)$_POST['supplier_id'] : null;

    // ✅ Fetch barcode from products
    $barcode = '';
    $barcode_stmt = $conn->prepare("SELECT barcode, product_name FROM products WHERE id = ?");
    $barcode_stmt->bind_param("i", $product_id);
    $barcode_stmt->execute();
    $barcode_stmt->bind_result($barcode, $product_name);
    $barcode_stmt->fetch();
    $barcode_stmt->close();

    $now = date("Y-m-d H:i:s");

    // ✅ Insert into stock_entries
    $stock_stmt = $conn->prepare("
        INSERT INTO stock_entries (product_id, store_id, quantity, cost_price, purchase_date, remarks, added_by, supplier_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stock_stmt->bind_param("iiidssii", $product_id, $store_id, $quantity, $cost_price, $purchase_date, $remarks, $user_id, $supplier_id);
    
    if ($stock_stmt->execute()) {
        $stock_stmt->close();

        // ✅ Check inventory
        $check = $conn->prepare("SELECT id, quantity, cost_price FROM inventory WHERE product_id = ? AND store_id = ?");
        $check->bind_param("ii", $product_id, $store_id);
        $check->execute();
        $result = $check->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $existing_qty = (int)$row['quantity'];
            $existing_cost = (float)$row['cost_price'];
            $new_qty = $existing_qty + $quantity;

            $total_existing = $existing_qty * $existing_cost;
            $total_new = $quantity * $cost_price;
            $avg_cost = ($total_existing + $total_new) / $new_qty;

            $update = $conn->prepare("
                UPDATE inventory 
                SET quantity = ?, cost_price = ?, modified_by = ?, modified_at = ? 
                WHERE id = ?
            ");
            $update->bind_param("idisi", $new_qty, $avg_cost, $user_id, $now, $row['id']);
            $update->execute();
            $update->close();
        } else {
            $insert = $conn->prepare("
                INSERT INTO inventory (store_id, product_id, barcode, quantity, cost_price, created_at, updated_at, modified_by, modified_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $insert->bind_param("iisidssss", $store_id, $product_id, $barcode, $quantity, $cost_price, $now, $now, $user_id, $now);
            $insert->execute();
            $insert->close();
        }

        $check->close();

        // ✅ Audit logging
        $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
        $module = 'Stock Entry';
        $action = 'add_stock_entry';
        $details = json_encode([
            'product_id'   => $product_id,
            'product_name' => $product_name,
            'store_id'     => $store_id,
            'quantity'     => $quantity,
            'cost_price'   => $cost_price,
            'purchase_date'=> $purchase_date,
            'remarks'      => $remarks,
            'supplier_id'  => $supplier_id,
        ]);

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

        $conn->close();
        header("Location: stock_entries.php?msg=Stock+added+successfully");
        exit();
    } else {
        echo "❌ Failed to insert stock entry: " . $stock_stmt->error;
    }
}
?>
