<?php
session_start();

require(realpath(__DIR__ . '/../../../services/Model.php'));
$obj = new Model();

$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : NULL;

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $batch_id = $_GET['batch'] ?? 0;
    $stock = $obj->rawSqlSingle("SELECT * FROM `stock` WHERE `stock_id` = '$id' AND `deleted_at` IS NULL");

    // Check if stock was found and return JSON response
    if ($stock) {
        $batch_id = $stock['batch_id'];
        $product_id = $stock['product_id'];
        $modelIds = $obj->rawSql("
            SELECT *
            FROM product_model
            WHERE batch_id = '$batch_id'
              AND product_id = '$product_id'
              AND sold = 0
              AND returned = 0
              AND deleted_at IS NULL
        ");
        $quantity = min((int)$stock['current_stock'], count($modelIds));

        if ($quantity <= 0) {
            echo json_encode(['success' => false, 'status' => 'No sellable models available for this batch']);
            exit;
        }

        echo json_encode(['success' => true, 'batch_id' => $batch_id, 'quantity' => $quantity, 'modelIds' => $modelIds]);
        exit;
    } else {
        echo json_encode(['success' => false, 'status' => 'Failed to add stock']);
        exit;
    }
}
