<?php
/**
 * barcode_sell.php
 * Single barcode item বিক্রয় (customer support সহ)
 *
 * v2 FIX (2026-06-01):
 *   - gs_find_cash_transaction_type_id() বাদ (ফাংশন নেই → fatal error ছিল)
 *   - gs_insert_cash_transaction()-এ category_id যোগ (SALE_RECEIPT, IN)
 *   - party_id → customer cash লেনদেনে লিংক হবে
 */
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/response.php';
require_once __DIR__ . '/../_finance.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);
$barcodeId     = (int)($data['barcode_id']     ?? 0);
$salePrice     = round((float)($data['sale_price']     ?? 0), 2);
$cashAccountId = (int)($data['cash_account_id'] ?? 0);
$customerId    = (int)($data['customer_id']    ?? 0);
$note          = trim((string)($data['note']   ?? ''));

if ($barcodeId     <= 0) send_response(400, false, 'Barcode ID দিন', null);
if ($salePrice     <= 0) send_response(400, false, 'Sale price দিন', null);
if ($cashAccountId <= 0) send_response(400, false, 'Cash account select করুন', null);

try {
    $pdo->beginTransaction();

    $itemStmt = $pdo->prepare(
        'SELECT id, barcode, item_name, karat, weight, customer_id, customer_name, status, deleted_at
         FROM barcode_stock WHERE id = ? LIMIT 1 FOR UPDATE'
    );
    $itemStmt->execute([$barcodeId]);
    $item = $itemStmt->fetch(PDO::FETCH_ASSOC);

    if (!$item)                       send_response(404, false, 'Barcode item পাওয়া যায়নি', null);
    if (!empty($item['deleted_at']))  send_response(400, false, 'এই barcode item delete করা হয়েছে', null);
    if (strtolower((string)($item['status'] ?? '')) !== 'in_stock')
        send_response(400, false, 'এই barcode item আর stock-এ নেই', ['current_status' => $item['status'] ?? '']);

    $accStmt = $pdo->prepare('SELECT id, account_name FROM cash_accounts WHERE id = ? LIMIT 1 FOR UPDATE');
    $accStmt->execute([$cashAccountId]);
    $account = $accStmt->fetch(PDO::FETCH_ASSOC);
    if (!$account) send_response(400, false, 'Cash account পাওয়া যায়নি', null);

    $customer = null;
    if ($customerId > 0) {
        $custStmt = $pdo->prepare(
            'SELECT id, name, phone FROM parties WHERE id = ? AND deleted_at IS NULL LIMIT 1 FOR UPDATE'
        );
        $custStmt->execute([$customerId]);
        $customer = $custStmt->fetch(PDO::FETCH_ASSOC);
        if (!$customer) send_response(400, false, 'Customer পাওয়া যায়নি', null);
    }

    $customerName = $customer ? trim((string)$customer['name']) : 'Cash Customer';
    $itemName     = trim((string)($item['item_name'] ?? 'Item'));
    $parts        = ['Barcode Sale', $itemName];
    if ($customerName !== '') $parts[] = $customerName;
    if ($note !== '')         $parts[] = $note;
    $saleNote = implode(' - ', $parts);

    $updStmt = $pdo->prepare(
        "UPDATE barcode_stock
         SET customer_id = ?, customer_name = ?, sale_price = ?,
             status = 'sold', sold_at = NOW(), note = ?
         WHERE id = ? LIMIT 1"
    );
    $updStmt->execute([
        $customerId > 0 ? $customerId : null,
        $customerName,
        $salePrice,
        $saleNote,
        $barcodeId
    ]);

    // ── ক্যাশ IN — central helper দিয়ে (v2 FIX) ──
    // SALE_RECEIPT category id সরাসরি বের করি (proven pattern)
    $catStmt = $pdo->prepare(
        "SELECT id FROM cash_categories WHERE category_code = 'SALE_RECEIPT' LIMIT 1"
    );
    $catStmt->execute();
    $saleCatId = (int)$catStmt->fetchColumn();

    if ($saleCatId <= 0) {
        $dbName = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
        throw new RuntimeException("SALE_RECEIPT category পাওয়া যায়নি (connected DB: {$dbName})");
    }

    if (function_exists('gs_insert_cash_transaction')) {
        gs_insert_cash_transaction($pdo, [
            'category_id'      => $saleCatId,                         // IN — বিক্রির টাকা
            'cash_account_id'  => $cashAccountId,
            'amount'           => $salePrice,
            'transaction_date' => date('Y-m-d'),
            'note'             => $saleNote,
            'reference_type'   => 'BARCODE_SALE',
            'reference_id'     => $barcodeId,
            'party_id'         => $customerId > 0 ? $customerId : null, // কাস্টমার লিংক
            'created_by'       => $_SESSION['user_id'] ?? null
        ]);
    }

    if (function_exists('gs_recalc_cash_account')) {
        gs_recalc_cash_account($pdo, $cashAccountId);
    }

    $balStmt = $pdo->prepare('SELECT current_balance FROM cash_accounts WHERE id = ? LIMIT 1');
    $balStmt->execute([$cashAccountId]);
    $updatedBalance = (float)$balStmt->fetchColumn();

    $pdo->commit();

    send_response(200, true, 'Barcode item সফলভাবে বিক্রি হয়েছে', [
        'barcode_id'        => (int)$item['id'],
        'barcode'           => $item['barcode']   ?? '',
        'item_name'         => $itemName,
        'karat'             => $item['karat']     ?? '',
        'weight'            => round((float)($item['weight'] ?? 0), 3),
        'sale_price'        => $salePrice,
        'cash_account_id'   => $cashAccountId,
        'cash_account_name' => $account['account_name'] ?? '',
        'customer_id'       => $customerId > 0 ? $customerId : null,
        'customer_name'     => $customerName,
        'updated_balance'   => round($updatedBalance, 2),
        'status'            => 'sold',
        'note'              => $saleNote
    ]);

} catch (Throwable $e) {
    if ($pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage(), ['error' => $e->getMessage()]);
}
