<?php
// update_stock.php
include 'includes/config.php';

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

try {
    if (isset($_POST['product_id']) && isset($_POST['current_stock'])) {
        $productId = intval($_POST['product_id']);
        $currentStock = intval($_POST['current_stock']);

        // Check if the product_id exists in the stock_setting table
        $stmt = $conn->prepare("SELECT quantity FROM stock_setting WHERE product_id = :productId");
        $stmt->execute(['productId' => $productId]);
        $existingStock = $stmt->fetchColumn();

        if ($existingStock !== false) {
            // Update existing record by adding the current stock
            // $newQuantity = $existingStock + $currentStock;
            $newQuantity = $currentStock;
            $stmt = $conn->prepare("UPDATE stock_setting SET quantity = :newQuantity WHERE product_id = :productId");
            $stmt->execute(['newQuantity' => $newQuantity, 'productId' => $productId]);
            $success = $stmt->rowCount() > 0;
        } else {
            // Insert new record with the current stock
            $stmt = $conn->prepare("INSERT INTO stock_setting (product_id, quantity) VALUES (:productId, :currentStock)");
            $stmt->execute(['productId' => $productId, 'currentStock' => $currentStock]);
            $success = $stmt->rowCount() > 0;
        }

        if ($success) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['error' => 'Failed to update or insert stock']);
        }
    } else {
        echo json_encode(['error' => 'Invalid input']);
    }
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
