<?php
// /public_html/erp.jewellersbd.com/api/barcode/create_barcode_item.php

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/response.php';

if (!is_logged_in()) {
    send_response(401, false, 'লগইন প্রয়োজন', null);
}

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

$data = json_decode(file_get_contents('php://input'), true);

$newStockId         = (int)($data['new_stock_id'] ?? 0);
$piecesToCreate     = (int)($data['pieces_to_create'] ?? 0);
$weightPerPieceGram = (float)($data['weight_per_piece_gram'] ?? 0);

if ($newStockId <= 0) {
    send_response(400, false, 'New stock ID দিন', null);
}

if ($piecesToCreate <= 0) {
    send_response(400, false, 'কত পিস barcode হবে তা দিন', null);
}

if ($weightPerPieceGram <= 0) {
    send_response(400, false, 'প্রতি পিস ওজন দিন', null);
}

try {
    $pdo->beginTransaction();

    $stockStmt = $pdo->prepare("
        SELECT
            id,
            stock_date,
            supplier_id,
            invoice_no,
            category,
            product_name,
            karat,
            total_pcs,
            total_weight_gram,
            available_pcs,
            available_weight_gram,
            location_id,
            note,
            deleted_at
        FROM new_stock
        WHERE id = ?
        LIMIT 1
        FOR UPDATE
    ");
    $stockStmt->execute([$newStockId]);
    $stock = $stockStmt->fetch(PDO::FETCH_ASSOC);

    if (!$stock) {
        $pdo->rollBack();
        send_response(404, false, 'New stock পাওয়া যায়নি', null);
    }

    if (!empty($stock['deleted_at'])) {
        $pdo->rollBack();
        send_response(400, false, 'এই stock delete করা হয়েছে', null);
    }

    $availablePcs = (int)($stock['available_pcs'] ?? 0);
    $availableWeightGram = (float)($stock['available_weight_gram'] ?? 0);

    if ($piecesToCreate > $availablePcs) {
        $pdo->rollBack();
        send_response(400, false, 'Available pcs এর বেশি barcode করা যাবে না', null);
    }

    $totalNeedGram = $piecesToCreate * $weightPerPieceGram;

    if ($totalNeedGram > $availableWeightGram) {
        $pdo->rollBack();
        send_response(400, false, 'Available weight এর বেশি barcode করা যাবে না', [
            'available_weight_gram' => round($availableWeightGram, 3),
            'required_weight_gram' => round($totalNeedGram, 3)
        ]);
    }

    $createdCodes = [];

    $itemName = trim(($stock['product_name'] ?? '') !== '' ? $stock['product_name'] : ($stock['category'] ?? 'Barcode Item'));
    $karat = strtoupper(trim($stock['karat'] ?? '22K'));

    if (!in_array($karat, ['24K', '22K', '21K', '18K'], true)) {
        $karat = 'other';
    }

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

    for ($i = 1; $i <= $piecesToCreate; $i++) {
        $barcode = 'BC' . date('ymdHis') . str_pad((string)random_int(1, 9999), 4, '0', STR_PAD_LEFT);

        $insertStmt->execute([
            $newStockId,
            $barcode,
            $itemName,
            $karat,
            round($weightPerPieceGram, 3),
            (int)$stock['location_id'],
            0.00,
            0.00,
            'in_stock',
            'Generated from new_stock ID ' . $newStockId
        ]);

        $createdCodes[] = $barcode;
    }

    $newAvailablePcs = $availablePcs - $piecesToCreate;
    $newAvailableWeight = $availableWeightGram - $totalNeedGram;

    if ($newAvailableWeight < 0) {
        $newAvailableWeight = 0;
    }

    $updateStmt = $pdo->prepare("
        UPDATE new_stock
        SET
            available_pcs = ?,
            available_weight_gram = ?
        WHERE id = ?
        LIMIT 1
    ");
    $updateStmt->execute([
        $newAvailablePcs,
        round($newAvailableWeight, 3),
        $newStockId
    ]);

    $pdo->commit();

    send_response(200, true, 'Barcode item সফলভাবে তৈরি হয়েছে', [
        'new_stock_id' => $newStockId,
        'created_pieces' => $piecesToCreate,
        'weight_per_piece_gram' => round($weightPerPieceGram, 3),
        'total_used_weight_gram' => round($totalNeedGram, 3),
        'remaining_pcs' => $newAvailablePcs,
        'remaining_weight_gram' => round($newAvailableWeight, 3),
        'barcodes' => $createdCodes
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage(), [
        'error' => $e->getMessage()
    ]);
}