<?php
// =====================================================
// File: /api/sales/get_barcode_for_sale.php
// Purpose: Barcode Sale item fetch - SAFE final version
// Rule: only status=in_stock, is_deleted=0, transfer_status=none
// Rule: weight always calculated from gross_weight_gram
// =====================================================

ob_start();
ini_set('display_errors', 0);
ini_set('serialize_precision', -1);
ini_set('precision', 14);
error_reporting(E_ALL);

function json_out($data, $code = 200) {
    while (ob_get_level() > 0) ob_end_clean();
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

try {
    $root = dirname(__DIR__, 2);

    require_once $root . '/config/db.php';

    if (file_exists($root . '/config/session.php')) {
        require_once $root . '/config/session.php';
    }

    if (function_exists('is_logged_in') && !is_logged_in()) {
        json_out(['success' => false, 'message' => 'লগইন প্রয়োজন'], 401);
    }

    if (!isset($pdo) || !($pdo instanceof PDO)) {
        json_out(['success' => false, 'message' => 'Database connection পাওয়া যায়নি'], 500);
    }

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    function nval($value, $default = 0.0) {
        if ($value === null || $value === '') return $default;
        $value = str_replace([',', '৳', ' '], '', (string)$value);
        return is_numeric($value) ? (float)$value : $default;
    }

    function sval($value, $default = '') {
        return $value === null ? $default : trim((string)$value);
    }

    function row_get($row, $keys, $default = null) {
        foreach ($keys as $key) {
            foreach ($row as $rk => $rv) {
                if (strtolower((string)$rk) === strtolower((string)$key)) {
                    if ($rv !== null && $rv !== '') return $rv;
                }
            }
        }
        return $default;
    }

    function table_cols($pdo, $table) {
        $stmt = $pdo->query("SHOW COLUMNS FROM `$table`");
        $cols = [];
        foreach ($stmt->fetchAll() as $r) {
            $cols[strtolower($r['Field'])] = $r['Field'];
        }
        return $cols;
    }

    function has_col($cols, $name) {
        return isset($cols[strtolower($name)]);
    }

    function latest_rate_per_gram($pdo, $karat) {
        $stmt = $pdo->query("SELECT * FROM gold_rates ORDER BY rate_date DESC, id DESC LIMIT 1");
        $rate = $stmt->fetch();

        if (!$rate) return 0.0;

        $k = preg_replace('/[^0-9]/', '', (string)$karat);

        if ($k === '24' && isset($rate['rate_24k'])) return nval($rate['rate_24k']);
        if ($k === '22' && isset($rate['rate_22k'])) return nval($rate['rate_22k']);
        if ($k === '21' && isset($rate['rate_21k'])) return nval($rate['rate_21k']);
        if ($k === '18' && isset($rate['rate_18k'])) return nval($rate['rate_18k']);

        return nval($rate['rate_22k'] ?? 0);
    }

    function weight_parts_from_gram($weightGram) {
        $weightGram = nval($weightGram, 0);
        $weightVori = $weightGram > 0 ? ($weightGram / 11.664) : 0;

        $totalPoint = (int)round($weightVori * 960);

        $vori = intdiv($totalPoint, 960);
        $remain = $totalPoint % 960;

        $ana = intdiv($remain, 60);
        $remain %= 60;

        $roti = intdiv($remain, 10);
        $point = $remain % 10;

        return [
            'vori' => $vori,
            'ana' => $ana,
            'roti' => $roti,
            'point' => $point,
            'weight_vori' => round($weightVori, 5),
            'weight_text' => $vori . ' ভরি ' . $ana . ' আনা ' . $roti . ' রতি ' . $point . ' পয়েন্ট'
        ];
    }

    $search = trim((string)(
        $_GET['barcode'] ??
        $_GET['q'] ??
        $_GET['search'] ??
        $_POST['barcode'] ??
        $_POST['q'] ??
        ''
    ));

    if ($search === '') {
        json_out(['success' => false, 'message' => 'বারকোড দিন'], 400);
    }

    $cols = table_cols($pdo, 'barcode_stock');

    $where = [];
    $params = [];

    if (has_col($cols, 'barcode')) {
        $where[] = "`barcode` = :barcode";
        $params[':barcode'] = $search;
    }

    if (has_col($cols, 'barcode_no')) {
        $where[] = "`barcode_no` = :barcode_no";
        $params[':barcode_no'] = $search;
    }

    if (has_col($cols, 'barcode_code')) {
        $where[] = "`barcode_code` = :barcode_code";
        $params[':barcode_code'] = $search;
    }

    if (!$where) {
        json_out(['success' => false, 'message' => 'barcode column পাওয়া যায়নি'], 500);
    }

    $sql = "SELECT * FROM barcode_stock WHERE (" . implode(' OR ', $where) . ") ORDER BY id DESC LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $row = $stmt->fetch();

    if (!$row) {
        json_out(['success' => false, 'message' => 'এই বারকোডের stock পাওয়া যায়নি']);
    }

    $status = strtolower(sval(row_get($row, ['status'], '')));
    $isDeleted = (int)nval(row_get($row, ['is_deleted'], 0));
    $transferStatus = strtolower(sval(row_get($row, ['transfer_status'], 'none')));

    if ($isDeleted !== 0) {
        json_out(['success' => false, 'message' => 'এই বারকোডটি deleted stock']);
    }

    if ($status !== 'in_stock') {
        json_out(['success' => false, 'message' => 'এই বারকোডটি stock-এ available নেই']);
    }

    if ($transferStatus !== 'none') {
        json_out(['success' => false, 'message' => 'এই বারকোডটি transfer pending/in transit আছে']);
    }

    $saleId = (int)nval(row_get($row, ['sale_id', 'barcode_sale_id', 'sold_sale_id'], 0));

    if ($saleId > 0) {
        json_out(['success' => false, 'message' => 'এই বারকোডটি আগে বিক্রি হয়েছে']);
    }

    $barcode  = sval(row_get($row, ['barcode', 'barcode_no', 'barcode_code'], ''));
    $itemName = sval(row_get($row, ['item_name', 'product_name', 'name'], 'Barcode Item'));
    $karat    = sval(row_get($row, ['karat', 'purity', 'carat'], '22K'));

    $weightGram = nval(row_get($row, [
        'gross_weight_gram',
        'weight_gram',
        'weight_g',
        'gross_weight',
        'net_weight_gram',
        'net_weight',
        'total_weight_gram',
        'weight'
    ], 0));

    $parts = weight_parts_from_gram($weightGram);

    $ratePerGram = latest_rate_per_gram($pdo, $karat);
    $ratePerVori = $ratePerGram * 11.664;

    $makingCharge = nval(row_get($row, ['making_charge', 'making', 'labour_charge'], 0));
    $itemPrice = ($weightGram * $ratePerGram) + $makingCharge;

    json_out([
        'success' => true,
        'message' => 'বারকোড পাওয়া গেছে',
        'item' => [
            'barcode_stock_id'   => (int)row_get($row, ['id'], 0),
            'barcode'            => $barcode,
            'item_name'          => $itemName,
            'category'           => sval(row_get($row, ['category', 'category_name'], '')),
            'karat'              => $karat,

            'weight_g'           => round($weightGram, 3),
            'weight_vori'        => $parts['weight_vori'],
            'vori'               => $parts['vori'],
            'ana'                => $parts['ana'],
            'roti'               => $parts['roti'],
            'point'              => $parts['point'],
            'weight_text'        => $parts['weight_text'],

            'rate_per_gram'      => round($ratePerGram, 2),
            'sale_rate_per_vori' => round($ratePerVori, 2),
            'making_charge'      => round($makingCharge, 2),
            'item_price'         => round($itemPrice, 2),

            'status'             => $status,
            'source'             => 'barcode_stock',
            'source_json'        => $row
        ]
    ]);

} catch (Throwable $e) {
    json_out(['success' => false, 'message' => 'Server error: ' . $e->getMessage()], 500);
}