<?php
/**
 * api/sales/print_sale.php
 * GET ?id=10 — sale details JSON (AJAX / JS use)
 */
require_once __DIR__ . '/../../config/db.php';
header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) session_start();
if (empty($_SESSION['user_id'])) { echo json_encode(['success'=>false,'message'=>'Login করুন।']); exit; }

$sale_id = (int)($_GET['id'] ?? 0);
$inv_no  = trim($_GET['invoice'] ?? '');

if ($sale_id > 0) {
    $s = $pdo->prepare("SELECT * FROM sales WHERE id=? LIMIT 1");
    $s->execute([$sale_id]);
} elseif ($inv_no) {
    $s = $pdo->prepare("SELECT * FROM sales WHERE invoice_no=? LIMIT 1");
    $s->execute([$inv_no]);
} else {
    echo json_encode(['success'=>false,'message'=>'id বা invoice দিন।']); exit;
}
$sale = $s->fetch(PDO::FETCH_ASSOC);
if (!$sale) { echo json_encode(['success'=>false,'message'=>'বিক্রয় পাওয়া যায়নি।']); exit; }

$items = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id=? ORDER BY id");
$items->execute([$sale['id']]);

$pays = $pdo->prepare("SELECT sp.*,ca.account_name FROM sale_payments sp LEFT JOIN cash_accounts ca ON ca.id=sp.cash_account_id WHERE sp.sale_id=?");
$pays->execute([$sale['id']]);

$exch = $pdo->prepare("SELECT * FROM sale_exchanges WHERE sale_id=?");
$exch->execute([$sale['id']]);

echo json_encode([
    'success'   => true,
    'sale'      => $sale,
    'items'     => $items->fetchAll(PDO::FETCH_ASSOC),
    'payments'  => $pays->fetchAll(PDO::FETCH_ASSOC),
    'exchanges' => $exch->fetchAll(PDO::FETCH_ASSOC),
    'print_url' => '/sale_print.php?id=' . $sale['id'],
]);