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

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

$startDate = isset($_GET['startDate']) ? mysqli_real_escape_string($con, $_GET['startDate']) : '';
$endDate = isset($_GET['endDate']) ? mysqli_real_escape_string($con, $_GET['endDate']) : '';
$supplierId = isset($_GET['supplierId']) ? intval($_GET['supplierId']) : 0;

if (empty($startDate) || empty($endDate)) {
    echo json_encode(['success' => false, 'message' => 'Start date and end date are required']);
    exit();
}

// Get supplier info if specific supplier is selected
$supplierInfo = null;
if ($supplierId > 0) {
    $supplierQuery = "SELECT ID, SupplierCode, SupplierName, PhoneNumber, Email, Address, GSTNumber, CurrentBalance 
                      FROM tblsuppliers WHERE ID = $supplierId";
    $supplierResult = mysqli_query($con, $supplierQuery);
    if ($supplierResult && mysqli_num_rows($supplierResult) > 0) {
        $supplierInfo = mysqli_fetch_assoc($supplierResult);
    }
}

// Calculate opening balance (balance before the start date)
$openingBalance = 0;

if ($supplierId > 0) {
    // Opening balance for specific supplier from account transactions before start date
    $openingQuery = "
        SELECT 
            COALESCE(SUM(DebitAmount), 0) as TotalDebit,
            COALESCE(SUM(CreditAmount), 0) as TotalCredit
        FROM tblsupplier_accounts
        WHERE SupplierID = $supplierId
        AND TransactionDate < '$startDate'
    ";
    
    $openingResult = mysqli_query($con, $openingQuery);
    if ($openingResult) {
        $openingData = mysqli_fetch_assoc($openingResult);
        // For suppliers: Debit (we owe them) - Credit (we paid them)
        $openingBalance = $openingData['TotalDebit'] - $openingData['TotalCredit'];
    }
} else {
    // Opening balance for all suppliers
    $openingQuery = "
        SELECT 
            COALESCE(SUM(DebitAmount), 0) as TotalDebit,
            COALESCE(SUM(CreditAmount), 0) as TotalCredit
        FROM tblsupplier_accounts
        WHERE TransactionDate < '$startDate'
    ";
    
    $openingResult = mysqli_query($con, $openingQuery);
    if ($openingResult) {
        $openingData = mysqli_fetch_assoc($openingResult);
        $openingBalance = $openingData['TotalDebit'] - $openingData['TotalCredit'];
    }
}

// Get transactions within the date range
$transactionsQuery = "
    SELECT 
        sa.ID,
        sa.TransactionDate,
        sa.TransactionType,
        sa.ReferenceType,
        sa.ReferenceNumber,
        sa.DebitAmount,
        sa.CreditAmount,
        sa.Balance,
        sa.Notes,
        s.SupplierName,
        s.SupplierCode
    FROM tblsupplier_accounts sa
    LEFT JOIN tblsuppliers s ON sa.SupplierID = s.ID
    WHERE sa.TransactionDate >= '$startDate' 
    AND sa.TransactionDate <= '$endDate'
";

if ($supplierId > 0) {
    $transactionsQuery .= " AND sa.SupplierID = $supplierId";
}

$transactionsQuery .= " ORDER BY sa.TransactionDate ASC, sa.ID ASC";

$transactions = [];
$totalPurchases = 0;
$totalPayments = 0;

$transactionsResult = mysqli_query($con, $transactionsQuery);
if ($transactionsResult) {
    while ($row = mysqli_fetch_assoc($transactionsResult)) {
        $transactions[] = $row;
        $totalPurchases += floatval($row['DebitAmount']);
        $totalPayments += floatval($row['CreditAmount']);
    }
}

// Calculate closing balance
$closingBalance = $openingBalance + $totalPurchases - $totalPayments;

// Prepare summary
$summary = [
    'openingBalance' => round($openingBalance, 2),
    'totalPurchases' => round($totalPurchases, 2),
    'totalPayments' => round($totalPayments, 2),
    'closingBalance' => round($closingBalance, 2)
];

// Return response
echo json_encode([
    'success' => true,
    'summary' => $summary,
    'transactions' => $transactions,
    'startDate' => $startDate,
    'endDate' => $endDate,
    'supplierInfo' => $supplierInfo
]);
?>
