<?php
/**
 * API to add stock by bag count
 * This will add bags and update both StockInBags and CurrentStock accordingly
 */

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

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

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

try {
    // Get input data
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $productId = (int)$input['product_id'];
    $bagsToAdd = (int)$input['bags_to_add'];
    $reason = isset($input['reason']) ? $input['reason'] : 'Stock Addition';
    $userId = $_SESSION['uid'];
    
    if ($productId <= 0 || $bagsToAdd <= 0) {
        throw new Exception('Invalid product ID or bag quantity');
    }
    
    // Get current product details
    $productQuery = "SELECT * FROM tblricebags WHERE ID = ? AND IsActive = 1";
    $stmt = mysqli_prepare($con, $productQuery);
    mysqli_stmt_bind_param($stmt, "i", $productId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $product = mysqli_fetch_assoc($result);
    
    if (!$product) {
        throw new Exception('Product not found or inactive');
    }
    
    // Calculate new stock values
    $kgToAdd = $bagsToAdd * $product['BagKg'];
    $newStockInBags = $product['StockInBags'] + $bagsToAdd;
    $newCurrentStock = $product['CurrentStock'] + $kgToAdd;
    
    // Start transaction
    mysqli_begin_transaction($con);
    
    try {
        // Update product stock
        $updateQuery = "UPDATE tblricebags SET CurrentStock = ?, StockInBags = ?, UpdatedBy = ?, UpdatedDate = NOW() WHERE ID = ?";
        $stmt = mysqli_prepare($con, $updateQuery);
        mysqli_stmt_bind_param($stmt, "ddii", $newCurrentStock, $newStockInBags, $userId, $productId);
        $updateResult = mysqli_stmt_execute($stmt);
        
        if (!$updateResult) {
            throw new Exception('Failed to update product stock');
        }
        
        // Create stock adjustment record
        $adjustmentQuery = "
            INSERT INTO tblstockadjustments 
            (RiceBagID, AdjustmentType, Quantity, PreviousStock, NewStock, Reason, 
             ReferenceNumber, AdjustmentDate, Status, CreatedBy, CreatedDate) 
            VALUES 
            (?, 'Add', ?, ?, ?, ?, ?, CURDATE(), 'Approved', ?, NOW())
        ";
        
        $refNumber = 'STOCK-ADD-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
        $stmt = mysqli_prepare($con, $adjustmentQuery);
        mysqli_stmt_bind_param($stmt, "idddssi", 
            $productId, $bagsToAdd, $product['StockInBags'], $newStockInBags, 
            $reason, $refNumber, $userId
        );
        $adjustmentResult = mysqli_stmt_execute($stmt);
        
        if (!$adjustmentResult) {
            throw new Exception('Failed to create stock adjustment record');
        }
        
        // Commit transaction
        mysqli_commit($con);
        
        echo json_encode([
            'success' => true,
            'message' => 'Stock added successfully',
            'data' => [
                'product_name' => $product['RiceBagName'],
                'bags_added' => $bagsToAdd,
                'kg_added' => $kgToAdd,
                'previous_stock_bags' => $product['StockInBags'],
                'new_stock_bags' => $newStockInBags,
                'previous_stock_kg' => $product['CurrentStock'],
                'new_stock_kg' => $newCurrentStock,
                'reference_number' => $refNumber
            ]
        ]);
        
    } catch (Exception $e) {
        mysqli_rollback($con);
        throw $e;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
