<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

session_start_if_not_started();

if (!is_logged_in()) {
    send_response(401, false, 'অনুমতি নেই');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_response(405, false, 'শুধু POST অনুরোধ গ্রহণযোগ্য');
}

$data              = json_decode(file_get_contents('php://input'), true);
$purchase_stock_id = intval($data['purchase_stock_id'] ?? 0);
$sale_price_vori   = floatval($data['sale_price_vori'] ?? 0);
$pieces            = intval($data['pieces']            ?? 0);
$weight_per_piece  = floatval($data['weight_per_piece']?? 0);

if (!$purchase_stock_id) {
    send_response(400, false, 'Purchase Stock ID দিন');
}
if ($sale_price_vori <= 0) {
    send_response(400, false, 'Sale Price দিন');
}
if ($pieces <= 0) {
    send_response(400, false, 'Piece সংখ্যা দিন');
}
if ($weight_per_piece <= 0) {
    send_response(400, false, 'প্রতি পিসের ওজন দিন');
}

$VORI = 11.664;

try {
    $stmt = $pdo->prepare(
        "SELECT * FROM purchase_stock WHERE id = ?"
    );
    $stmt->execute([$purchase_stock_id]);
    $stock = $stmt->fetch();

    if (!$stock) {
        send_response(404, false, 'Stock পাওয়া যায়নি');
    }

    $existStmt = $pdo->prepare(
        "SELECT COUNT(*) as cnt
         FROM barcode_stock
         WHERE purchase_stock_id = ?"
    );
    $existStmt->execute([$purchase_stock_id]);
    $existing = $existStmt->fetch()['cnt'];

    if (($existing + $pieces) > $stock['total_pieces']) {
        send_response(400, false,
            'মোট পিস '.$stock['total_pieces'].
            ' — আগে '.$existing.
            ' টা বারকোড হয়েছে। আর '.
            ($stock['total_pieces'] - $existing).
            ' টা করা যাবে।'
        );
    }

    $cost_gram      = $stock['rate_per_vori'] / $VORI;
    $pure_ratio     = floatval($stock['gross_weight']) > 0
        ? floatval($stock['pure_weight']) /
          floatval($stock['gross_weight'])
        : 0.9167;
    $cost_per_piece = round(
        $weight_per_piece * $pure_ratio * $cost_gram, 2);
    $sale_per_piece = round(
        ($weight_per_piece / $VORI) * $sale_price_vori, 2);

    $pdo->beginTransaction();

    $barcodes   = [];
    $insertStmt = $pdo->prepare(
        "INSERT INTO barcode_stock
            (purchase_stock_id, barcode, item_name,
             karat, weight, location_id,
             cost_price, sale_price, status)
         VALUES (?,?,?,?,?,?,?,?,'in_stock')"
    );

    for ($i = 0; $i < $pieces; $i++) {
        $barcode = strtoupper(
            substr($stock['karat'], 0, 2).
            date('ymd').
            str_pad($purchase_stock_id, 4, '0', STR_PAD_LEFT).
            str_pad(($existing + $i + 1), 3, '0', STR_PAD_LEFT)
        );

        $insertStmt->execute([
            $purchase_stock_id,
            $barcode,
            $stock['item_name'],
            $stock['karat'],
            $weight_per_piece,
            $stock['location_id'],
            $cost_per_piece,
            $sale_per_piece
        ]);

        $barcodes[] = [
            'id'         => $pdo->lastInsertId(),
            'barcode'    => $barcode,
            'item_name'  => $stock['item_name'],
            'karat'      => $stock['karat'],
            'weight'     => $weight_per_piece,
            'cost_price' => $cost_per_piece,
            'sale_price' => $sale_per_piece
        ];
    }

    $pdo->commit();

    send_response(200, true,
        $pieces.' টা বারকোড তৈরি হয়েছে', [
        'barcodes'       => $barcodes,
        'total_barcodes' => $existing + $pieces,
        'remaining'      => $stock['total_pieces'] -
                            $existing - $pieces
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    send_response(500, false, 'Error: '.$e->getMessage());
}
?>