<?php
/**
 * API: Get GST Details for a Sale
 * Returns detailed GST breakdown for all products in a sale
 */

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 sale ID or invoice number
$saleId = isset($_GET['sale_id']) ? intval($_GET['sale_id']) : 0;
$invoiceNumber = isset($_GET['invoice_number']) ? mysqli_real_escape_string($con, $_GET['invoice_number']) : '';

if ($saleId <= 0 && empty($invoiceNumber)) {
    echo json_encode(['success' => false, 'message' => 'Sale ID or Invoice Number is required']);
    exit();
}

try {
    // Build query condition
    $whereClause = $saleId > 0 ? "s.ID = $saleId" : "s.InvoiceNumber = '$invoiceNumber'";
    
    // Get sale information
    $saleQuery = "
        SELECT 
            s.ID as SaleID,
            s.InvoiceNumber,
            s.SaleDate,
            s.CustomerID,
            c.CustomerName,
            c.CustomerCode,
            c.GSTNumber,
            c.State,
            s.SubTotal,
            s.TotalAmount,
            s.FinalAmount
        FROM tblsales s
        LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
        WHERE $whereClause
    ";
    
    $saleResult = mysqli_query($con, $saleQuery);
    
    if (!$saleResult || mysqli_num_rows($saleResult) == 0) {
        echo json_encode(['success' => false, 'message' => 'Sale not found']);
        exit();
    }
    
    $saleInfo = mysqli_fetch_assoc($saleResult);
    
    // Determine tax type based on customer GST number
    $taxType = 'INTRA'; // Default to CGST+SGST (Tamil Nadu)
    $gstNumber = $saleInfo['GSTNumber'];
    
    if (!empty($gstNumber)) {
        $stateCode = substr($gstNumber, 0, 2);
        if ($stateCode !== '33') {
            $taxType = 'INTER'; // IGST for other states
        }
    }
    
    // Get sale details (products)
    $detailsQuery = "
        SELECT 
            sd.ID,
            sd.ProductID,
            sd.ProductCode,
            sd.ProductName,
            sd.Rate,
            sd.Quantity,
            sd.Discount,
            sd.DiscountType,
            sd.DiscountAmount,
            sd.FinalRate,
            sd.Amount,
            sd.FinalTotal,
            p.HSN as HSNCode,
            p.TaxID,
            COALESCE(t.TaxRate, 0) as TaxPercentage
        FROM tblsales_details sd
        LEFT JOIN tblitems p ON sd.ProductID = p.ID
        LEFT JOIN tbltaxtypes t ON p.TaxID = t.ID
        WHERE sd.SaleID = {$saleInfo['SaleID']}
        ORDER BY sd.ID
    ";
    
    $detailsResult = mysqli_query($con, $detailsQuery);
    
    if (!$detailsResult) {
        echo json_encode(['success' => false, 'message' => 'Error fetching sale details']);
        exit();
    }
    
    $gstDetails = [];
    $totalCGST = 0;
    $totalSGST = 0;
    $totalIGST = 0;
    $totalTaxableAmount = 0;
    $totalTaxAmount = 0;
    $totalFinalAmount = 0;
    
    while ($row = mysqli_fetch_assoc($detailsResult)) {
        // Calculate taxable amount (after discount)
        $taxableAmount = $row['FinalTotal'] ?? ($row['Amount'] - $row['DiscountAmount']);
        
        // Get tax percentage (default 0 if not set)
        $taxPercentage = floatval($row['TaxPercentage'] ?? 0);
        
        // Calculate tax amounts
        if ($taxType === 'INTRA') {
            // Split equally between CGST and SGST
            $cgstPercent = $taxPercentage / 2;
            $sgstPercent = $taxPercentage / 2;
            $cgstAmount = ($taxableAmount * $cgstPercent) / 100;
            $sgstAmount = ($taxableAmount * $sgstPercent) / 100;
            $igstPercent = 0;
            $igstAmount = 0;
            $totalTax = $cgstAmount + $sgstAmount;
        } else {
            // IGST only
            $cgstPercent = 0;
            $sgstPercent = 0;
            $cgstAmount = 0;
            $sgstAmount = 0;
            $igstPercent = $taxPercentage;
            $igstAmount = ($taxableAmount * $igstPercent) / 100;
            $totalTax = $igstAmount;
        }
        
        $finalAmount = $taxableAmount + $totalTax;
        
        // Add to totals
        $totalCGST += $cgstAmount;
        $totalSGST += $sgstAmount;
        $totalIGST += $igstAmount;
        $totalTaxableAmount += $taxableAmount;
        $totalTaxAmount += $totalTax;
        $totalFinalAmount += $finalAmount;
        
        $gstDetails[] = [
            'ProductID' => $row['ProductID'],
            'ProductCode' => $row['ProductCode'],
            'ProductName' => $row['ProductName'],
            'HSNCode' => $row['HSNCode'] ?? '-',
            'Rate' => number_format($row['Rate'], 2),
            'Quantity' => number_format($row['Quantity'], 2),
            'DiscountAmount' => number_format($row['DiscountAmount'], 2),
            'TaxableAmount' => number_format($taxableAmount, 2),
            'TaxPercentage' => number_format($taxPercentage, 2),
            'TaxType' => $taxType,
            'CGSTPercent' => number_format($cgstPercent, 2),
            'CGSTAmount' => number_format($cgstAmount, 2),
            'SGSTPercent' => number_format($sgstPercent, 2),
            'SGSTAmount' => number_format($sgstAmount, 2),
            'IGSTPercent' => number_format($igstPercent, 2),
            'IGSTAmount' => number_format($igstAmount, 2),
            'TotalTaxAmount' => number_format($totalTax, 2),
            'FinalAmount' => number_format($finalAmount, 2)
        ];
    }
    
    // Prepare response
    $response = [
        'success' => true,
        'saleInfo' => [
            'SaleID' => $saleInfo['SaleID'],
            'InvoiceNumber' => $saleInfo['InvoiceNumber'],
            'SaleDate' => date('d-M-Y', strtotime($saleInfo['SaleDate'])),
            'CustomerName' => $saleInfo['CustomerName'],
            'CustomerCode' => $saleInfo['CustomerCode'],
            'GSTNumber' => $saleInfo['GSTNumber'] ?? 'Not Provided',
            'State' => $saleInfo['State'] ?? 'Tamil Nadu',
            'TaxType' => $taxType,
            'TaxTypeLabel' => $taxType === 'INTRA' ? 'Intra-State (CGST + SGST)' : 'Inter-State (IGST)'
        ],
        'gstDetails' => $gstDetails,
        'totals' => [
            'TotalTaxableAmount' => number_format($totalTaxableAmount, 2),
            'TotalCGST' => number_format($totalCGST, 2),
            'TotalSGST' => number_format($totalSGST, 2),
            'TotalIGST' => number_format($totalIGST, 2),
            'TotalTaxAmount' => number_format($totalTaxAmount, 2),
            'TotalFinalAmount' => number_format($totalFinalAmount, 2)
        ]
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

mysqli_close($con);
?>
