<?php
/**
 * ============================================================
 *  বধুবরণ জুয়েলার্স ERP — Sales Module
 *  File: api/sales/get_sale_details.php
 *  Date: 2026-05-16 (v2 — output buffer fix)
 * ============================================================
 */

// === Strict output control ===
ob_start();
@ini_set('display_errors', '0');
error_reporting(E_ERROR | E_PARSE);

require_once __DIR__ . '/../_core.php';

ob_get_clean();

header('Content-Type: application/json; charset=utf-8');

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'লগইন করুন']);
    exit;
}

$id         = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$invoice_no = trim($_GET['invoice_no'] ?? '');

if ($id <= 0 && $invoice_no === '') {
    echo json_encode(['ok' => false, 'error' => 'id বা invoice_no দিন']);
    exit;
}

try {
    if ($id > 0) {
        $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
        $stmt->execute([$id]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM sales WHERE invoice_no = ?");
        $stmt->execute([$invoice_no]);
    }
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sale) {
        echo json_encode(['ok' => false, 'error' => 'Sale পাওয়া যায়নি']);
        exit;
    }
    $sale_id = (int)$sale['id'];

    // Items
    $stmt = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id = ? ORDER BY id ASC");
    $stmt->execute([$sale_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Payments
    $stmt = $pdo->prepare("
        SELECT sp.*, ca.account_name AS cash_account_name
          FROM sale_payments sp
          LEFT JOIN cash_accounts ca ON ca.id = sp.cash_account_id
         WHERE sp.sale_id = ?
         ORDER BY sp.id ASC
    ");
    $stmt->execute([$sale_id]);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Exchanges
    $stmt = $pdo->prepare("SELECT * FROM sale_exchanges WHERE sale_id = ? ORDER BY id ASC");
    $stmt->execute([$sale_id]);
    $exchanges = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Customer (if linked)
    $customer = null;
    if (!empty($sale['customer_id'])) {
        try {
            $stmt = $pdo->prepare("SELECT * FROM parties WHERE id = ?");
            $stmt->execute([(int)$sale['customer_id']]);
            $customer = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } catch (Exception $e) {
            // ignore parties schema mismatch
        }
    }

    echo json_encode([
        'ok'        => true,
        'sale'      => $sale,
        'items'     => $items,
        'payments'  => $payments,
        'exchanges' => $exchanges,
        'customer'  => $customer
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}