<?php
// admin/accounts/get-po.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    exit;
}

$id = intval($_GET['id'] ?? 0);
if ($id > 0) {
    try {
        $stmt = $pdo->prepare("SELECT po.*, v.name as vendor_name,
                               (SELECT COALESCE(SUM(amount), 0) FROM po_payments WHERE po_id = po.id) as total_paid
                               FROM purchase_orders po 
                               LEFT JOIN vendors v ON po.vendor_id = v.id 
                               WHERE po.id = ?");
        $stmt->execute([$id]);
        $po = $stmt->fetch();
        
        if ($po) {
            $po['paid_amount'] = $po['total_paid'] ?? 0;
            $po['due_amount'] = $po['total'] - $po['paid_amount'];
            
            $stmt = $pdo->prepare("SELECT * FROM po_items WHERE po_id = ?");
            $stmt->execute([$id]);
            $items = $stmt->fetchAll();
            
            echo json_encode([
                'po' => $po,
                'items' => $items
            ]);
        } else {
            echo json_encode(['error' => 'PO not found']);
        }
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'Invalid ID']);
}
?>