<?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_weight       = $data['pure_weight'] ?? null;
$rate              = $data['rate'] ?? null;
$making_charge     = $data['making_charge'] ?? 0;
$discount          = $data['discount'] ?? 0;
$exchange_weight   = $data['exchange_weight'] ?? 0;
$exchange_amount   = $data['exchange_amount'] ?? 0;
$paid_amount       = $data['paid_amount'] ?? 0;
$payment_method_id = $data['payment_method_id'] ?? null;
$note              = $data['note'] ?? '';
$sale_date         = $data['sale_date'] ?? date('Y-m-d');
$created_by        = $_SESSION['user_id'];

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

// হিসাব
$total_amount = round(
    ($gross_weight * $rate) + $making_charge - $discount - $exchange_amount, 
    2
);
$due_amount = round($total_amount - $paid_amount, 2);

try {
    $pdo->beginTransaction();

    // ১. sales টেবিলে রেকর্ড
    $stmt = $pdo->prepare(
        "INSERT INTO sales 
            (sale_date, party_id, location_id, karat,
             gross_weight, pure_weight, rate, making_charge,
             discount, exchange_weight, exchange_amount,
             total_amount, paid_amount, due_amount,
             payment_method_id, note, created_by)
         VALUES 
            (:sale_date, :party_id, :location_id, :karat,
             :gross_weight, :pure_weight, :rate, :making_charge,
             :discount, :exchange_weight, :exchange_amount,
             :total_amount, :paid_amount, :due_amount,
             :payment_method_id, :note, :created_by)"
    );
    $stmt->execute([
        ':sale_date'         => $sale_date,
        ':party_id'          => $party_id,
        ':location_id'       => $location_id,
        ':karat'             => $karat,
        ':gross_weight'      => $gross_weight,
        ':pure_weight'       => $pure_weight,
        ':rate'              => $rate,
        ':making_charge'     => $making_charge,
        ':discount'          => $discount,
        ':exchange_weight'   => $exchange_weight,
        ':exchange_amount'   => $exchange_amount,
        ':total_amount'      => $total_amount,
        ':paid_amount'       => $paid_amount,
        ':due_amount'        => $due_amount,
        ':payment_method_id' => $payment_method_id,
        ':note'              => $note,
        ':created_by'        => $created_by
    ]);
    $sale_id = $pdo->lastInsertId();

    // ২. gold_stock থেকে কমাবে
    $stmt = $pdo->prepare(
        "UPDATE gold_stock 
         SET weight_gram = weight_gram - :weight_gram,
             pure_weight = pure_weight - :pure_weight
         WHERE location_id = :location_id 
         AND karat = :karat"
    );
    $stmt->execute([
        ':weight_gram' => $gross_weight,
        ':pure_weight' => $pure_weight,
        ':location_id' => $location_id,
        ':karat'       => $karat
    ]);

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

    $pdo->commit();

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

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