<?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, 'অনুমতি নেই');
}

$id = (int)($_GET['id'] ?? 0);

if (!$id) {
    send_response(400, false, 'Purchase ID দিন');
}

try {
    $stmt = $pdo->prepare(
        "SELECT
            p.id,
            p.purchase_date,
            p.karat,
            p.gross_weight,
            p.pure_weight,
            p.pure_ratio,
            p.rate_24k,
            p.total_amount,
            p.note,
            p.created_at,
            pt.id          AS party_id,
            pt.name        AS party_name,
            pt.phone       AS party_phone,
            sl.id          AS location_id,
            sl.name        AS location_name,
            sl.name_bn     AS location_name_bn,
            pm.id          AS payment_method_id,
            pm.method_name AS payment_method
         FROM purchases p
         LEFT JOIN parties pt
            ON p.party_id = pt.id
         LEFT JOIN stock_locations sl
            ON p.location_id = sl.id
         LEFT JOIN payment_methods pm
            ON p.payment_method_id = pm.id
         WHERE p.id = ?"
    );
    $stmt->execute([$id]);
    $purchase = $stmt->fetch();

    if (!$purchase) {
        send_response(404, false,
            'Purchase পাওয়া যায়নি');
    }

    send_response(200, true, 'সফল', [
        'purchase' => $purchase
    ]);

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