<?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_date     = $data['purchase_date']            ?? date('Y-m-d');
$party_id          = $data['party_id']                 ?? null;
$location_id       = $data['location_id']              ?? 1;
$item_name         = trim($data['item_name']           ?? '');
$karat             = $data['karat']                    ?? '22K';
$gross_weight      = floatval($data['gross_weight']    ?? 0);
$total_pieces      = intval($data['total_pieces']      ?? 1);
$rate_per_vori     = floatval($data['rate_per_vori']   ?? 0);
$payment_method_id = intval($data['payment_method_id'] ?? 1);
$cash_account_id   = intval($data['cash_account_id']   ?? 0);
$note              = trim($data['note']                ?? '');

if (empty($item_name)) {
    send_response(400, false, 'Item Name দিন');
}
if ($gross_weight <= 0) {
    send_response(400, false, 'Weight দিন');
}
if ($rate_per_vori <= 0) {
    send_response(400, false, 'Rate দিন');
}
if ($total_pieces <= 0) {
    send_response(400, false, 'Piece দিন');
}

$ratios = [
    '24K'   => 1.0000,
    '22K'   => 0.9167,
    '21K'   => 0.8750,
    '18K'   => 0.7500,
    'other' => 0.5833
];
$pure_ratio   = $ratios[$karat] ?? 0.9167;
$pure_weight  = round($gross_weight * $pure_ratio, 3);
$VORI         = 11.664;
$rate_gram    = $rate_per_vori / $VORI;
$total_amount = round($pure_weight * $rate_gram, 2);

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare(
        "INSERT INTO purchase_stock
            (purchase_date, party_id, location_id,
             item_name, karat, gross_weight, pure_weight,
             total_pieces, rate_per_vori, total_amount,
             payment_method_id, cash_account_id,
             note, created_by)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
    );
    $stmt->execute([
        $purchase_date,
        $party_id ?: null,
        $location_id,
        $item_name,
        $karat,
        $gross_weight,
        $pure_weight,
        $total_pieces,
        $rate_per_vori,
        $total_amount,
        $payment_method_id,
        $cash_account_id ?: null,
        $note,
        $_SESSION['user_id'] ?? null
    ]);
    $purchase_stock_id = $pdo->lastInsertId();

    // ─── ক্যাশ এন্ট্রি — central helper দিয়ে (v2 FIX, 2026-06-01) ───
    //   পুরোনো raw INSERT বাদ (মৃত কলাম transaction_type_id/type/is_reversal)।
    //   শর্ত বদল: payment_method==1 নয় — যেকোনো অ্যাকাউন্ট (নগদ/ব্যাংক)
    //   সিলেক্ট করলেই cash OUT বসবে।
    if ($cash_account_id && $total_amount > 0) {

        // PURCHASE_PAYMENT category id সরাসরি বের করি (helper-এর gs_find এড়িয়ে)
        $catStmt = $pdo->prepare(
            "SELECT id FROM cash_categories WHERE category_code = 'PURCHASE_PAYMENT' LIMIT 1"
        );
        $catStmt->execute();
        $purchaseCatId = (int)$catStmt->fetchColumn();

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

        if (function_exists('gs_insert_cash_transaction')) {
            gs_insert_cash_transaction($pdo, [
                'category_id'      => $purchaseCatId,   // OUT — ক্রয়ে টাকা পরিশোধ
                'cash_account_id'  => $cash_account_id,
                'amount'           => $total_amount,
                'transaction_date' => $purchase_date,
                'note'             => 'নতুন ক্রয়: ' . $item_name,
                'reference_type'   => 'new_purchase',
                'reference_id'     => $purchase_stock_id,
                'created_by'       => $_SESSION['user_id'] ?? null
            ]);

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

    if ($party_id) {
        $pdo->prepare(
            "UPDATE parties SET balance=balance-? WHERE id=?"
        )->execute([$total_amount, $party_id]);
    }

    $pdo->commit();

    send_response(200, true, 'সফলভাবে সেভ হয়েছে', [
        'purchase_stock_id' => $purchase_stock_id,
        'item_name'         => $item_name,
        'gross_weight'      => $gross_weight,
        'pure_weight'       => $pure_weight,
        'total_pieces'      => $total_pieces,
        'total_amount'      => $total_amount
    ]);

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