<?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);

// ইনপুট ভ্যালিডেশন
$party_id          = $data['party_id'] ?? null;
$location_id       = $data['location_id'] ?? null;
$karat             = $data['karat'] ?? null;
$gross_weight      = $data['gross_weight'] ?? null;
$pure_ratio        = $data['pure_ratio'] ?? null;
$rate_24k          = $data['rate_24k'] ?? null;
$payment_method_id = $data['payment_method_id'] ?? null;
$note              = $data['note'] ?? '';
$purchase_date     = $data['purchase_date'] ?? date('Y-m-d');
$created_by        = $_SESSION['user_id'];

if (!$location_id || !$karat || !$gross_weight || 
    !$pure_ratio || !$rate_24k) {
    send_response(400, false, 'সব তথ্য দিন');
}

// pure weight ও total amount হিসাব
$pure_weight  = round($gross_weight * $pure_ratio, 3);
$total_amount = round($pure_weight * $rate_24k, 2);

try {
    $pdo->beginTransaction();

    // ১. purchases টেবিলে রেকর্ড যোগ
    $stmt = $pdo->prepare(
        "INSERT INTO purchases 
            (purchase_date, party_id, location_id, karat,
             gross_weight, pure_ratio, pure_weight,
             rate_24k, total_amount, payment_method_id,
             note, created_by)
         VALUES 
            (:purchase_date, :party_id, :location_id, :karat,
             :gross_weight, :pure_ratio, :pure_weight,
             :rate_24k, :total_amount, :payment_method_id,
             :note, :created_by)"
    );
    $stmt->execute([
        ':purchase_date'     => $purchase_date,
        ':party_id'          => $party_id,
        ':location_id'       => $location_id,
        ':karat'             => $karat,
        ':gross_weight'      => $gross_weight,
        ':pure_ratio'        => $pure_ratio,
        ':pure_weight'       => $pure_weight,
        ':rate_24k'          => $rate_24k,
        ':total_amount'      => $total_amount,
        ':payment_method_id' => $payment_method_id,
        ':note'              => $note,
        ':created_by'        => $created_by
    ]);
    $purchase_id = $pdo->lastInsertId();

    // ২. gold_stock আপডেট
    $stmt = $pdo->prepare(
        "INSERT INTO gold_stock 
            (location_id, karat, weight_gram, pure_weight)
         VALUES 
            (:location_id, :karat, :weight_gram, :pure_weight)
         ON DUPLICATE KEY UPDATE
            weight_gram  = weight_gram + :weight_gram,
            pure_weight  = pure_weight + :pure_weight"
    );
    $stmt->execute([
        ':location_id' => $location_id,
        ':karat'       => $karat,
        ':weight_gram' => $gross_weight,
        ':pure_weight' => $pure_weight
    ]);

    // ৩. gold_ledger এ এন্ট্রি
    $stmt = $pdo->prepare(
        "INSERT INTO gold_ledger 
            (entry_date, party_id, location_id, entry_type,
             reference_id, gold_in, amount_out, karat,
             note, created_by)
         VALUES 
            (:entry_date, :party_id, :location_id, 'PURCHASE',
             :reference_id, :gold_in, :amount_out, :karat,
             :note, :created_by)"
    );
    $stmt->execute([
        ':entry_date'   => $purchase_date,
        ':party_id'     => $party_id,
        ':location_id'  => $location_id,
        ':reference_id' => $purchase_id,
        ':gold_in'      => $pure_weight,
        ':amount_out'   => $total_amount,
        ':karat'        => $karat,
        ':note'         => $note,
        ':created_by'   => $created_by
    ]);

    $pdo->commit();

    send_response(200, true, 'সোনা কেনার রেকর্ড সফলভাবে সেভ হয়েছে', [
        'purchase_id'  => $purchase_id,
        'pure_weight'  => $pure_weight,
        'total_amount' => $total_amount
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage());
}
?>