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

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

// Get customer info if specific customer is selected
$customerInfo = null;
if ($customerId > 0) {
    $customerQuery = "SELECT ID, CustomerID, CustomerCode, CustomerName, Mobile, City, CurrentBalance 
                      FROM tblcustomers WHERE ID = $customerId";
    $customerResult = mysqli_query($con, $customerQuery);
    if ($customerResult && mysqli_num_rows($customerResult) > 0) {
        $customerInfo = mysqli_fetch_assoc($customerResult);
    }
}

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

if ($customerId > 0) {
    // Opening balance for specific customer
    $openingQuery = "
        SELECT 
            COALESCE(SUM(s.TotalAmount), 0) as TotalSales,
            COALESCE(SUM(s.PaymentAmount), 0) as TotalPayments
        FROM tblsales s
        WHERE s.CustomerID = $customerId
        AND s.SaleDate < '$startDate'
    ";
} else {
    // Opening balance for all customers
    $openingQuery = "
        SELECT 
            COALESCE(SUM(s.TotalAmount), 0) as TotalSales,
            COALESCE(SUM(s.PaymentAmount), 0) as TotalPayments
        FROM tblsales s
        WHERE s.SaleDate < '$startDate'
    ";
}

$openingResult = mysqli_query($con, $openingQuery);
if ($openingResult) {
    $openingData = mysqli_fetch_assoc($openingResult);
    $openingBalance = $openingData['TotalSales'] - $openingData['TotalPayments'];
}

// Get transactions within the date range
$transactionsQuery = "
    SELECT 
        s.ID,
        s.InvoiceNumber,
        s.SaleDate as TransactionDate,
        s.TotalAmount,
        s.PaymentAmount,
        s.PaymentMode,
        s.Notes,
        c.CustomerName,
        c.CustomerCode,
        'Sale' as TransactionType,
        s.TotalAmount as DebitAmount,
        s.PaymentAmount as CreditAmount
    FROM tblsales s
    LEFT JOIN tblcustomers c ON s.CustomerID = c.ID
    WHERE s.SaleDate >= '$startDate' 
    AND s.SaleDate <= '$endDate'
";

if ($customerId > 0) {
    $transactionsQuery .= " AND s.CustomerID = $customerId";
}

$transactionsQuery .= " ORDER BY s.SaleDate ASC, s.ID ASC";

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

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

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

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

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