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

header('Content-Type: application/json');

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

// Check if POST data exists
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'Invalid JSON data']);
    exit();
}

// Validate required fields
if (!isset($data['itemId']) || !isset($data['field']) || !isset($data['value'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

$itemId = (int)$data['itemId'];
$field = $data['field'];
$value = $data['value'];

// Validate field name to prevent SQL injection
$allowedFields = [
    'ItemName',
    'SKU',
    'Barcode',
    'HSN',
    'CurrentStock',
    'AlertQuantity',
    'PurchasePrice',
    'SalesPrice',
    'ShopRate',
    'WholesaleRate',
    'MRP'
];

if (!in_array($field, $allowedFields)) {
    echo json_encode(['success' => false, 'message' => 'Invalid field name']);
    exit();
}

// Determine if field is text or numeric
$textFields = ['ItemName', 'SKU', 'Barcode', 'HSN'];
$isTextField = in_array($field, $textFields);

// Validate value
if ($isTextField) {
    // Text field validation
    if (trim($value) === '') {
        echo json_encode(['success' => false, 'message' => 'Value cannot be empty']);
        exit();
    }
    $value = mysqli_real_escape_string($con, trim($value));
} else {
    // Numeric field validation
    if (!is_numeric($value)) {
        echo json_encode(['success' => false, 'message' => 'Value must be numeric']);
        exit();
    }
    
    $value = (float)$value;
    
    // Check if value is negative
    if ($value < 0) {
        echo json_encode(['success' => false, 'message' => 'Value cannot be negative']);
        exit();
    }
}

// Update the item
if ($isTextField) {
    $updateQuery = "UPDATE tblitems SET $field = ?, LastUpdated = NOW() WHERE ID = ?";
    $stmt = mysqli_prepare($con, $updateQuery);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($con)]);
        exit();
    }
    mysqli_stmt_bind_param($stmt, 'si', $value, $itemId);
} else {
    $updateQuery = "UPDATE tblitems SET $field = ?, LastUpdated = NOW() WHERE ID = ?";
    $stmt = mysqli_prepare($con, $updateQuery);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($con)]);
        exit();
    }
    mysqli_stmt_bind_param($stmt, 'di', $value, $itemId);
}
$result = mysqli_stmt_execute($stmt);

if ($result) {
    // Get updated item details
    $selectQuery = "SELECT 
                    i.ID,
                    i.ItemCode,
                    i.ItemName,
                    i.CurrentStock,
                    i.PurchasePrice,
                    i.SalesPrice,
                    i.MRP,
                    (i.CurrentStock * i.PurchasePrice) as StockValue,
                    CASE 
                        WHEN i.CurrentStock = 0 THEN 'Out of Stock'
                        WHEN i.CurrentStock <= i.AlertQuantity THEN 'Low Stock'
                        ELSE 'In Stock'
                    END as StockStatus
                    FROM tblitems i
                    WHERE i.ID = ?";
    
    $selectStmt = mysqli_prepare($con, $selectQuery);
    mysqli_stmt_bind_param($selectStmt, 'i', $itemId);
    mysqli_stmt_execute($selectStmt);
    $selectResult = mysqli_stmt_get_result($selectStmt);
    
    if ($row = mysqli_fetch_assoc($selectResult)) {
        // Log the change (optional - you can create an audit log table)
        $userId = $_SESSION['uid'];
        $logQuery = "INSERT INTO tblstockaudit (ItemID, UserID, Field, OldValue, NewValue, UpdatedAt) 
                     SELECT ?, ?, ?, 
                     (SELECT $field FROM tblitems WHERE ID = ? LIMIT 1), 
                     ?, NOW()
                     FROM DUAL
                     WHERE EXISTS (SELECT 1 FROM tblitems WHERE ID = ?)";
        
        // Only log if audit table exists
        $tableExists = mysqli_query($con, "SHOW TABLES LIKE 'tblstockaudit'");
        if (mysqli_num_rows($tableExists) > 0) {
            $logStmt = mysqli_prepare($con, $logQuery);
            if ($logStmt) {
                mysqli_stmt_bind_param($logStmt, 'issidi', $itemId, $userId, $field, $itemId, $value, $itemId);
                mysqli_stmt_execute($logStmt);
                mysqli_stmt_close($logStmt);
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Stock updated successfully',
            'data' => [
                'itemId' => $row['ID'],
                'itemCode' => $row['ItemCode'],
                'itemName' => $row['ItemName'],
                'currentStock' => number_format($row['CurrentStock'], 2, '.', ''),
                'purchasePrice' => number_format($row['PurchasePrice'], 2, '.', ''),
                'salesPrice' => number_format($row['SalesPrice'], 2, '.', ''),
                'mrp' => number_format($row['MRP'], 2, '.', ''),
                'stockValue' => number_format($row['StockValue'], 2, '.', ''),
                'stockStatus' => $row['StockStatus']
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Item not found after update']);
    }
    
    mysqli_stmt_close($selectStmt);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update: ' . mysqli_error($con)]);
}

mysqli_stmt_close($stmt);
mysqli_close($con);
?>
