<?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';
$currentSaleId = isset($_POST['currentSaleId']) ? intval($_POST['currentSaleId']) : 0;

try {
    if ($direction === 'next') {
        if ($currentSaleId > 0) {
            $query = "SELECT ID FROM tblsales WHERE ID > $currentSaleId ORDER BY ID ASC LIMIT 1";
        } else {
            $query = "SELECT ID FROM tblsales ORDER BY ID DESC LIMIT 1";
        }
    } else { // previous
        if ($currentSaleId > 0) {
            $query = "SELECT ID FROM tblsales WHERE ID < $currentSaleId ORDER BY ID DESC LIMIT 1";
        } else {
            $query = "SELECT ID FROM tblsales 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);
        $saleId = $row['ID'];
        
        // Get sale details
        $saleQuery = "SELECT s.*, c.CustomerCode, c.CustomerName, c.Mobile, c.CurrentBalance 
                      FROM tblsales s 
                      LEFT JOIN tblcustomers c ON s.CustomerID = c.ID 
                      WHERE s.ID = $saleId";
        $saleResult = mysqli_query($con, $saleQuery);
        
        if (!$saleResult) {
            throw new Exception('Failed to fetch sale: ' . mysqli_error($con));
        }
        
        $sale = mysqli_fetch_assoc($saleResult);
        
        if (!$sale) {
            throw new Exception('Sale not found');
        }
        
        // Get sale items
    $itemsQuery = "SELECT sd.*, 
                   COALESCE(i.ItemName, sd.ProductName) AS ProductName,
                   gst.HSNCode AS GST_HSNCode,
                   gst.TaxableAmount AS GST_TaxableAmount,
                   gst.TaxPercentage AS GST_TaxPercentage,
                   gst.TaxType AS GST_TaxType,
                   gst.CGSTPercent AS GST_CGSTPercent,
                   gst.CGSTAmount AS GST_CGSTAmount,
                   gst.SGSTPercent AS GST_SGSTPercent,
                   gst.SGSTAmount AS GST_SGSTAmount,
                   gst.IGSTPercent AS GST_IGSTPercent,
                   gst.IGSTAmount AS GST_IGSTAmount,
                   gst.TotalTaxAmount AS GST_TotalTaxAmount,
                   gst.FinalAmount AS GST_FinalAmount
               FROM tblsales_details sd 
               LEFT JOIN tblitems i ON sd.ProductCode = i.ItemCode 
               LEFT JOIN tblsales_gst_details gst ON gst.SaleID = sd.SaleID 
                             AND gst.ProductID = sd.ProductID 
                             AND gst.ProductCode = sd.ProductCode
               WHERE sd.SaleID = $saleId 
               ORDER BY sd.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)) {
            $taxPercentage = isset($item['GST_TaxPercentage']) ? floatval($item['GST_TaxPercentage']) : 0;
            $gstDetails = null;

            if ($taxPercentage > 0 || isset($item['GST_TaxType'])) {
                $gstDetails = [
                    'hsnCode' => isset($item['GST_HSNCode']) ? $item['GST_HSNCode'] : '',
                    'taxableAmount' => isset($item['GST_TaxableAmount']) ? floatval($item['GST_TaxableAmount']) : 0,
                    'taxPercentage' => $taxPercentage,
                    'taxType' => isset($item['GST_TaxType']) ? $item['GST_TaxType'] : 'INTRA',
                    'cgstPercent' => isset($item['GST_CGSTPercent']) ? floatval($item['GST_CGSTPercent']) : 0,
                    'cgstAmount' => isset($item['GST_CGSTAmount']) ? floatval($item['GST_CGSTAmount']) : 0,
                    'sgstPercent' => isset($item['GST_SGSTPercent']) ? floatval($item['GST_SGSTPercent']) : 0,
                    'sgstAmount' => isset($item['GST_SGSTAmount']) ? floatval($item['GST_SGSTAmount']) : 0,
                    'igstPercent' => isset($item['GST_IGSTPercent']) ? floatval($item['GST_IGSTPercent']) : 0,
                    'igstAmount' => isset($item['GST_IGSTAmount']) ? floatval($item['GST_IGSTAmount']) : 0,
                    'totalTaxAmount' => isset($item['GST_TotalTaxAmount']) ? floatval($item['GST_TotalTaxAmount']) : 0,
                    'finalAmount' => isset($item['GST_FinalAmount']) ? floatval($item['GST_FinalAmount']) : 0
                ];
            }

            $items[] = [
                'productId' => intval($item['ProductID']),
                'productCode' => $item['ProductCode'],
                'productName' => $item['ProductName'],
                'rate' => floatval($item['Rate']),
                'purchaseRate' => isset($item['PurchaseRate']) ? floatval($item['PurchaseRate']) : 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']) : 0,
                'finalTotal' => isset($item['FinalTotal']) ? floatval($item['FinalTotal']) : 0,
                'hsnCode' => isset($item['GST_HSNCode']) ? $item['GST_HSNCode'] : '',
                'taxRate' => $taxPercentage,
                'taxPercent' => $taxPercentage,
                'taxPercentage' => $taxPercentage,
                'taxType' => isset($item['GST_TaxType']) ? $item['GST_TaxType'] : null,
                'taxableAmount' => isset($item['GST_TaxableAmount']) ? floatval($item['GST_TaxableAmount']) : 0,
                'taxAmount' => isset($item['GST_TotalTaxAmount']) ? floatval($item['GST_TotalTaxAmount']) : 0,
                'gstDetails' => $gstDetails
            ];
        }
        
        // Calculate adjusted old balance
        // Current balance includes this bill (பற்று) minus payment (வரவு)
        // To get the balance BEFORE this bill, we need to subtract the bill amount and add back the payment
        $currentBalance = floatval($sale['CurrentBalance']);
        $billAmount = floatval($sale['TotalAmount']);
        $paymentAmount = isset($sale['PaymentAmount']) ? floatval($sale['PaymentAmount']) : 0;
        
        // Adjusted old balance = Current balance - Bill amount + Payment amount
        // Because: Current balance = Old balance + Bill - Payment
        // So: Old balance = Current balance - Bill + Payment
        $adjustedOldBalance = $currentBalance - $billAmount + $paymentAmount;
        
        echo json_encode([
            'success' => true,
            'sale' => [
                'id' => $sale['ID'],
                'invoiceNumber' => $sale['InvoiceNumber'],
                'customerId' => $sale['CustomerID'],
                'customerCode' => $sale['CustomerCode'],
                'customerName' => $sale['CustomerName'],
                'customerPhone' => $sale['Mobile'],
                'customerBalance' => floatval($sale['CurrentBalance']),
                'adjustedOldBalance' => $adjustedOldBalance, // Balance before this bill
                'subTotal' => floatval($sale['SubTotal']),
                'cooli' => floatval($sale['CooliAmount']),
                'transportName' => isset($sale['TransportName']) ? $sale['TransportName'] : '',
                'vehicleNumber' => isset($sale['VehicleNumber']) ? $sale['VehicleNumber'] : '',
                'transportGSTPercent' => isset($sale['TransportGSTPercent']) ? floatval($sale['TransportGSTPercent']) : 0,
                'transportGSTType' => isset($sale['TransportGSTType']) ? $sale['TransportGSTType'] : 'inclusive',
                'transportGSTAmount' => isset($sale['TransportGSTAmount']) ? floatval($sale['TransportGSTAmount']) : 0,
                'grandTotal' => floatval($sale['TotalAmount']),
                'paymentMethod' => $sale['PaymentMode'],
                'paymentAmount' => isset($sale['PaymentAmount']) ? floatval($sale['PaymentAmount']) : 0,
                'cashAmount' => isset($sale['CashAmount']) ? floatval($sale['CashAmount']) : 0,
                'upiAmount' => isset($sale['UpiAmount']) ? floatval($sale['UpiAmount']) : 0,
                'creditAmount' => isset($sale['CreditAmount']) ? floatval($sale['CreditAmount']) : 0,
                'paymentStatus' => isset($sale['PaymentStatus']) ? $sale['PaymentStatus'] : 'Paid',
                'notes' => $sale['Notes'],
                'saleDate' => $sale['SaleDate']
            ],
            '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()
    ]);
}
?>
