<?php
require('config.php');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

$response = [];

if (isset($_POST['stockEdit'])) {
    $stockEdit = json_decode($_POST['stockEdit'], true);

    // Validate JSON decoding
    if (json_last_error() !== JSON_ERROR_NONE) {
        $response['error'] = true;
        $response['message'] = "Invalid JSON format: " . json_last_error_msg();
        echo json_encode($response);
        exit;
    }

    if (isset($stockEdit['flag'])) {
        $flag = $stockEdit['flag'];

        if ($flag === "update" && isset($stockEdit['id'])) {
            $id = (int)$stockEdit['id'];
            if (isset($stockEdit['quantity']) && isset($stockEdit['batchNo']) && isset($stockEdit['addedBy']) && isset($stockEdit['dateAdded'])) {
                // Assign values to variables
                $quantity = (int)$stockEdit['quantity'];
                $batchNo = $stockEdit['batchNo'];
                $addedBy = (int)$stockEdit['addedBy'];
                $dateAdded = $stockEdit['dateAdded'];

                // Start transaction
                $connect->begin_transaction();

                // Get the initial quantity
                $stmt = $connect->prepare("SELECT quantity FROM store_stock WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $stmt->bind_result($initialQTY);
                $stmt->fetch();
                $stmt->close();

                // Update the quantity in store_stock table
                $stmt = $connect->prepare("UPDATE store_stock SET quantity = quantity + ? WHERE id = ?");
                $stmt->bind_param("ii", $quantity, $id);
                
                if ($stmt->execute()) {
                    $stmt->close();

                    // Create batch_entries table if not exists
                    $createTableQuery = "CREATE TABLE IF NOT EXISTS batch_entries (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        stockID INT NOT NULL,
                        initialQTY INT NOT NULL,
                        quantity INT NOT NULL,
                        batchNo VARCHAR(255) NOT NULL,
                        addedBy INT NOT NULL,
                        dateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    )";
                    $connect->query($createTableQuery);

                    // Insert the batch entry
                    $stmt = $connect->prepare("INSERT INTO batch_entries (stockID, initialQTY, quantity, batchNo, addedBy, dateAdded) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("iiisis", $id, $initialQTY, $quantity, $batchNo, $addedBy, $dateAdded);
                    
                    if ($stmt->execute()) {
                        $connect->commit();
                        $response['error'] = false;
                        $response['message'] = "Stock updated and batch entry recorded successfully.";
                    } else {
                        $connect->rollback();
                        $response['error'] = true;
                        $response['message'] = "Failed to record batch entry: " . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $connect->rollback();
                    $response['error'] = true;
                    $response['message'] = "Failed to update stock: " . $stmt->error;
                }
            } else {
                $response['error'] = true;
                $response['message'] = "Missing parameters for update.";
            }
        } elseif ($flag === "newEntry") {
            if (isset($stockEdit['quantity']) && isset($stockEdit['batchNo']) && isset($stockEdit['addedBy']) && isset($stockEdit['dateAdded'])) {
                // Assign values to variables
                $quantity = (int)$stockEdit['quantity'];
                $batchNo = $stockEdit['batchNo'];
                $addedBy = (int)$stockEdit['addedBy'];
                $dateAdded = $stockEdit['dateAdded'];

                // Get the last inserted stock ID
                $result = $connect->query("SELECT id FROM store_stock ORDER BY id DESC LIMIT 1");
                $row = $result->fetch_assoc();
                $stockID = $row ? (int)$row['id'] : 0;

                // Create batch_entries table if not exists
                $createTableQuery = "CREATE TABLE IF NOT EXISTS batch_entries (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    stockID INT NOT NULL,
                    initialQTY INT NOT NULL,
                    quantity INT NOT NULL,
                    batchNo VARCHAR(255) NOT NULL,
                    addedBy INT NOT NULL,
                    dateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )";
                $connect->query($createTableQuery);

                // Insert the batch entry
                $stmt = $connect->prepare("INSERT INTO batch_entries (stockID, initialQTY, quantity, batchNo, addedBy, dateAdded) VALUES (?, 0, ?, ?, ?, ?)");
                $stmt->bind_param("iisis", $stockID, $quantity, $batchNo, $addedBy, $dateAdded);
                
                if ($stmt->execute()) {
                    $response['error'] = false;
                    $response['message'] = "New batch entry recorded successfully.";
                } else {
                    $response['error'] = true;
                    $response['message'] = "Failed to record batch entry: " . $stmt->error;
                }
                $stmt->close();
            } else {
                $response['error'] = true;
                $response['message'] = "Missing parameters for new entry.";
            }
        } else {
            $response['error'] = true;
            $response['message'] = "Invalid flag value. Allowed values are 'update' or 'newEntry'.";
        }
    } else {
        $response['error'] = true;
        $response['message'] = "Missing required parameter 'flag'.";
    }
} else {
    $response['error'] = true;
    $response['message'] = "No data received in 'stockEdit'.";
}

echo json_encode($response);
?>
