<?php
session_start();
include_once('../../includes/config.php');

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

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$direction = isset($_POST['direction']) ? $_POST['direction'] : 'next';
$currentPurchaseId = isset($_POST['currentSaleId']) ? intval($_POST['currentSaleId']) : 0;

try {
    if ($direction === 'next') {
        if ($currentPurchaseId > 0) {
            $query = "SELECT ID FROM tblpurchases WHERE ID > $currentPurchaseId ORDER BY ID ASC LIMIT 1";
        } else {
            $query = "SELECT ID FROM tblpurchases ORDER BY ID DESC LIMIT 1";
        }
    } else { // previous
        if ($currentPurchaseId > 0) {
            $query = "SELECT ID FROM tblpurchases WHERE ID < $currentPurchaseId ORDER BY ID DESC LIMIT 1";
        } else {
            $query = "SELECT ID FROM tblpurchases ORDER BY ID DESC LIMIT 1";
        }
    }
    
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        throw new Exception('Query failed: ' . mysqli_error($con));
    }
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $purchaseId = $row['ID'];
        
        // Get purchase details with supplier balance
        $purchaseQuery = "SELECT p.*, s.SupplierCode, s.SupplierName, s.PhoneNumber, 
                         COALESCE(s.OutstandingBalance, 0) as SupplierBalance
                         FROM tblpurchases p 
                         LEFT JOIN tblsuppliers s ON p.SupplierID = s.ID 
                         WHERE p.ID = $purchaseId";
        $purchaseResult = mysqli_query($con, $purchaseQuery);
        
        if (!$purchaseResult) {
            throw new Exception('Failed to fetch purchase: ' . mysqli_error($con));
        }
        
        $purchase = mysqli_fetch_assoc($purchaseResult);
        
        if (!$purchase) {
            throw new Exception('Purchase not found');
        }
        
        // Get purchase items with HSN and Tax info
        $itemsQuery = "SELECT pd.*, i.ItemName as ProductName, i.HSN as HSNCode, t.TaxRate 
                       FROM tblpurchases_details pd 
                       LEFT JOIN tblitems i ON pd.ProductCode = i.ItemCode 
                       LEFT JOIN tbltaxtypes t ON i.TaxID = t.ID
                       WHERE pd.PurchaseID = $purchaseId 
                       ORDER BY pd.ID";
        $itemsResult = mysqli_query($con, $itemsQuery);
        
        if (!$itemsResult) {
            throw new Exception('Failed to fetch items: ' . mysqli_error($con));
        }
        
        $items = [];
        while ($item = mysqli_fetch_assoc($itemsResult)) {
            $items[] = [
                'productId' => intval($item['ProductID']),
                'productCode' => $item['ProductCode'],
                'productName' => $item['ProductName'],
                'rate' => floatval($item['Rate']),
                'purchaseRate' => floatval($item['Rate']), // Purchase rate is same as rate
                'mrp' => isset($item['MRP']) ? floatval($item['MRP']) : 0,
                'quantity' => floatval($item['Quantity']),
                'amount' => floatval($item['Amount']),
                'discount' => isset($item['Discount']) ? floatval($item['Discount']) : 0,
                'discountType' => isset($item['DiscountType']) ? $item['DiscountType'] : 'PERCENTAGE',
                'discountAmount' => isset($item['DiscountAmount']) ? floatval($item['DiscountAmount']) : 0,
                'finalRate' => isset($item['FinalRate']) ? floatval($item['FinalRate']) : floatval($item['Rate']),
                'finalTotal' => isset($item['FinalTotal']) ? floatval($item['FinalTotal']) : floatval($item['Amount']),
                'hsnCode' => isset($item['HSNCode']) ? $item['HSNCode'] : '-',
                'taxRate' => isset($item['TaxRate']) ? floatval($item['TaxRate']) : 0
            ];
        }
        
        echo json_encode([
            'success' => true,
            'sale' => [
                'id' => $purchase['ID'],
                'invoiceNumber' => $purchase['InvoiceNumber'],
                'supplierId' => $purchase['SupplierID'],
                'supplierCode' => $purchase['SupplierCode'],
                'supplierName' => $purchase['SupplierName'],
                'supplierPhone' => $purchase['PhoneNumber'],
                'supplierBalance' => isset($purchase['SupplierBalance']) ? floatval($purchase['SupplierBalance']) : 0,
                'purchaseType' => isset($purchase['PurchaseType']) ? $purchase['PurchaseType'] : 'GST',
                'purchaseInvoiceNumber' => isset($purchase['PurchaseInvoiceNumber']) ? $purchase['PurchaseInvoiceNumber'] : '',
                'purchaseInvoiceDate' => isset($purchase['PurchaseInvoiceDate']) ? $purchase['PurchaseInvoiceDate'] : '',
                'subTotal' => floatval($purchase['SubTotal']),
                'freightAmount' => isset($purchase['FreightAmount']) ? floatval($purchase['FreightAmount']) : 0,
                'transportName' => isset($purchase['TransportName']) ? $purchase['TransportName'] : '',
                'vehicleNumber' => isset($purchase['VehicleNumber']) ? $purchase['VehicleNumber'] : '',
                'transportGSTPercent' => isset($purchase['TransportGSTPercent']) ? floatval($purchase['TransportGSTPercent']) : 0,
                'transportGSTType' => isset($purchase['TransportGSTType']) ? $purchase['TransportGSTType'] : 'inclusive',
                'transportGSTAmount' => isset($purchase['TransportGSTAmount']) ? floatval($purchase['TransportGSTAmount']) : 0,
                'billDiscount' => isset($purchase['BillDiscount']) ? floatval($purchase['BillDiscount']) : 0,
                'billDiscountType' => isset($purchase['BillDiscountType']) ? $purchase['BillDiscountType'] : 'PERCENTAGE',
                'discountAmount' => isset($purchase['DiscountAmount']) ? floatval($purchase['DiscountAmount']) : 0,
                'roundOffAmount' => isset($purchase['RoundOffAmount']) ? floatval($purchase['RoundOffAmount']) : 0,
                'totalAmount' => floatval($purchase['TotalAmount']),
                'finalAmount' => isset($purchase['FinalAmount']) ? floatval($purchase['FinalAmount']) : floatval($purchase['TotalAmount']),
                'grandTotal' => isset($purchase['FinalAmount']) ? floatval($purchase['FinalAmount']) : floatval($purchase['TotalAmount']),
                'paymentMethod' => $purchase['PaymentMode'],
                'paymentAmount' => isset($purchase['PaymentAmount']) ? floatval($purchase['PaymentAmount']) : 0,
                'cashAmount' => isset($purchase['CashAmount']) ? floatval($purchase['CashAmount']) : 0,
                'upiAmount' => isset($purchase['UpiAmount']) ? floatval($purchase['UpiAmount']) : 0,
                'creditAmount' => isset($purchase['CreditAmount']) ? floatval($purchase['CreditAmount']) : 0,
                'paymentStatus' => isset($purchase['PaymentStatus']) ? $purchase['PaymentStatus'] : 'Paid',
                'referenceNumber' => isset($purchase['ReferenceNumber']) ? $purchase['ReferenceNumber'] : '',
                'supplierInvoiceNumber' => isset($purchase['SupplierInvoiceNumber']) ? $purchase['SupplierInvoiceNumber'] : '',
                'supplierInvoiceDate' => isset($purchase['SupplierInvoiceDate']) ? $purchase['SupplierInvoiceDate'] : '',
                'notes' => isset($purchase['Notes']) ? $purchase['Notes'] : '',
                'purchaseDate' => $purchase['PurchaseDate']
            ],
            'items' => $items
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No ' . ($direction === 'next' ? 'next' : 'previous') . ' bill found'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
