<?php
/**
 * API: Get Products Tax Information
 * Returns HSN and tax rate for given product IDs
 */

session_start();
header('Content-Type: application/json');

// Include database connection
include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get POST data
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['productIds']) || !is_array($input['productIds']) || empty($input['productIds'])) {
    echo json_encode(['success' => false, 'message' => 'Product IDs are required']);
    exit();
}

$productIds = array_map('intval', $input['productIds']);
$productIdsStr = implode(',', $productIds);

try {
    // Fetch product details with tax information
    $query = "
        SELECT 
            p.ID,
            p.ProductCode,
            p.ProductName,
            p.HSN,
            p.TaxID,
            COALESCE(t.TaxRate, 0) as TaxRate,
            t.TaxName
        FROM tblitems p
        LEFT JOIN tbltaxtypes t ON p.TaxID = t.ID
        WHERE p.ID IN ($productIdsStr)
    ";
    
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        echo json_encode(['success' => false, 'message' => 'Database query failed']);
        exit();
    }
    
    $products = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $products[] = [
            'ID' => $row['ID'],
            'ProductCode' => $row['ProductCode'],
            'ProductName' => $row['ProductName'],
            'HSN' => $row['HSN'] ?? '-',
            'TaxID' => $row['TaxID'],
            'TaxRate' => floatval($row['TaxRate']),
            'TaxName' => $row['TaxName'] ?? 'No Tax'
        ];
    }
    
    echo json_encode([
        'success' => true,
        'products' => $products
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

mysqli_close($con);
?>
