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

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

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

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

    // Determine store_id based on role
    if ($role_id == 1) {
        // Admin can post any store
        $store_id = isset($_POST['store_id']) ? (int)$_POST['store_id'] : 0;
    } elseif ($role_id == 2) {
        // Manager restricted to their own store
        $store_id = $_SESSION['store_id'] ?? 0;
    } else {
        // Should never get here due to session check above
        header("Location: ../../index.php");
        exit();
    }

    // Basic validation
    if ($product_id <= 0 || $store_id <= 0 || $quantity <= 0 || $cost_price <= 0 || !$purchase_date) {
        header("Location: add_stock.php?error=Missing+or+invalid+fields");
        exit();
    }

    // If manager, enforce store restriction
    if ($role_id == 2 && (!isset($_SESSION['store_id']) || $store_id !== $_SESSION['store_id'])) {
        header("Location: add_stock.php?error=Unauthorized+store+access");
        exit();
    }

    // Fetch barcode and product_name
    $barcode = '';
    $product_name = '';
    $barcode_stmt = $conn->prepare("SELECT barcode, product_name FROM products WHERE id = ?");
    if (!$barcode_stmt) {
        die("Prepare failed: " . $conn->error);
    }
    $barcode_stmt->bind_param("i", $product_id);
    $barcode_stmt->execute();
    $barcode_stmt->bind_result($barcode, $product_name);
    if (!$barcode_stmt->fetch()) {
        $barcode_stmt->close();
        header("Location: add_stock.php?error=Product+not+found");
        exit();
    }
    $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 (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    if (!$stock_stmt) {
        die("Prepare failed: " . $conn->error);
    }
    // supplier_id can be null, so bind accordingly
    if ($supplier_id === null) {
        $stock_stmt->bind_param("iiidssii", $product_id, $store_id, $quantity, $cost_price, $purchase_date, $remarks, $user_id, $supplier_id);
        // This won't work since supplier_id null is int but null is not int; so bind param with "i" but value null? 
        // So we must bind supplier_id as nullable. To handle nullable int in mysqli, pass NULL as null in bind_param is impossible.
        // Instead, use a workaround with prepared statements and separate query, or insert NULL explicitly via query.
        // Best is to change supplier_id param type to "i" and pass NULL as integer 0 and treat 0 as NULL in DB, or use NULL explicitly in query.
        // So let's rewrite insert to use NULL explicitly if supplier_id is null.

        $stock_stmt->close();
        // Re-prepare with conditional insert for supplier_id
        if ($supplier_id === null) {
            $stock_stmt = $conn->prepare("
                INSERT INTO stock_entries (product_id, store_id, quantity, cost_price, purchase_date, remarks, added_by, supplier_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
            ");
            $stock_stmt->bind_param("iiidsss", $product_id, $store_id, $quantity, $cost_price, $purchase_date, $remarks, $user_id);
        } else {
            $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);
        }
    } else {
        $stock_stmt->bind_param("iiidssii", $product_id, $store_id, $quantity, $cost_price, $purchase_date, $remarks, $user_id, $supplier_id);
    }

    if (!$stock_stmt->execute()) {
        $err = $stock_stmt->error;
        $stock_stmt->close();
        header("Location: add_stock.php?error=" . urlencode("Failed to add stock entry: $err"));
        exit();
    }
    $stock_stmt->close();

    // Check inventory record for this product & store
    $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) {
        // Update existing inventory
        $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 new inventory record
        $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=" . urlencode("Stock added successfully"));
    exit();
} else {
    header("Location: add_stock.php");
    exit();
}
