<?php
header('Content-Type: application/json');
session_start();
include_once('../../includes/config.php');

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

$startDate = isset($_GET['startDate']) ? $_GET['startDate'] : date('Y-m-01');
$endDate = isset($_GET['endDate']) ? $_GET['endDate'] : date('Y-m-t');
$supplierId = isset($_GET['supplierId']) ? $_GET['supplierId'] : '';
$purchaseType = isset($_GET['purchaseType']) ? $_GET['purchaseType'] : '';

try {
    // Build the main query
    $query = "
        SELECT 
            p.ID,
            p.InvoiceNumber,
            p.PurchaseInvoiceNumber,
            p.PurchaseInvoiceDate,
            p.PurchaseDate,
            p.PurchaseType,
            p.FinalAmount,
            s.SupplierName,
            s.SupplierID AS SupplierCode,
            s.GSTNumber,
            s.City,
            s.State,
            -- Calculate aggregated GST details from tblpurchases_gst_details
            SUM(pgd.TaxableAmount) as TaxableAmount,
            SUM(pgd.CGSTAmount) as CGSTAmount,
            SUM(pgd.SGSTAmount) as SGSTAmount,
            SUM(pgd.IGSTAmount) as IGSTAmount,
            SUM(pgd.TotalTaxAmount) as TotalTax,
            MAX(pgd.TaxType) as TaxType,
            MAX(pgd.CGSTPercent) as CGSTPercent,
            MAX(pgd.SGSTPercent) as SGSTPercent,
            MAX(pgSTPercent) as IGSTPercent,
            ptc.Description as PurchaseTypeDescription
        FROM tblpurchases p
        LEFT JOIN tblsuppliers s ON p.SupplierID = s.ID
        LEFT JOIN tblpurchases_gst_details pgd ON p.ID = pgd.PurchaseID
        LEFT JOIN tblpurchase_type_config ptc ON p.PurchaseType = ptc.PurchaseType
        WHERE p.PurchaseDate BETWEEN ? AND ?
    ";
    
    $params = [$startDate, $endDate];
    $types = 'ss';
    
    // Add supplier filter
    if ($supplierId) {
        $query .= " AND s.SupplierID = ?";
        $params[] = $supplierId;
        $types .= 's';
    }
    
    // Add purchase type filter
    if ($purchaseType) {
        $query .= " AND p.PurchaseType = ?";
        $params[] = $purchaseType;
        $types .= 's';
    }
    
    $query .= " GROUP BY p.ID ORDER BY p.PurchaseDate DESC, p.ID DESC";
    
    $stmt = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $purchases = [];
    $summary = [
        'totalPurchases' => 0,
        'taxableAmount' => 0,
        'cgstAmount' => 0,
        'sgstAmount' => 0,
        'igstAmount' => 0,
        'totalTax' => 0,
        'transactionCount' => 0
    ];
    
    while ($row = mysqli_fetch_assoc($result)) {
        $purchases[] = $row;
        
        $summary['totalPurchases'] += floatval($row['FinalAmount']);
        $summary['taxableAmount'] += floatval($row['TaxableAmount']);
        $summary['cgstAmount'] += floatval($row['CGSTAmount']);
        $summary['sgstAmount'] += floatval($row['SGSTAmount']);
        $summary['igstAmount'] += floatval($row['IGSTAmount']);
        $summary['totalTax'] += floatval($row['TotalTax']);
        $summary['transactionCount']++;
    }
    
    // Get supplier info if filtered
    $supplierInfo = null;
    if ($supplierId) {
        $supplierQuery = "SELECT SupplierName, City FROM tblsuppliers WHERE SupplierID = ? LIMIT 1";
        $supplierStmt = mysqli_prepare($con, $supplierQuery);
        mysqli_stmt_bind_param($supplierStmt, 's', $supplierId);
        mysqli_stmt_execute($supplierStmt);
        $supplierResult = mysqli_stmt_get_result($supplierStmt);
        $supplierInfo = mysqli_fetch_assoc($supplierResult);
    }
    
    // Get purchase type info if filtered
    $purchaseTypeInfo = null;
    if ($purchaseType) {
        $typeQuery = "SELECT PurchaseType FROM tblpurchase_type_config WHERE PurchaseType = ? LIMIT 1";
        $typeStmt = mysqli_prepare($con, $typeQuery);
        mysqli_stmt_bind_param($typeStmt, 's', $purchaseType);
        mysqli_stmt_execute($typeStmt);
        $typeResult = mysqli_stmt_get_result($typeStmt);
        $typeRow = mysqli_fetch_assoc($typeResult);
        $purchaseTypeInfo = $typeRow ? $typeRow['PurchaseType'] : null;
    }
    
    echo json_encode([
        'success' => true,
        'purchases' => $purchases,
        'summary' => $summary,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'supplierInfo' => $supplierInfo,
        'purchaseTypeInfo' => $purchaseTypeInfo
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
