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

// Include database configuration
require_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    // Get parameters
    $startDate = isset($_GET['startDate']) ? trim($_GET['startDate']) : '';
    $endDate = isset($_GET['endDate']) ? trim($_GET['endDate']) : '';
    $customerId = isset($_GET['customerId']) ? trim($_GET['customerId']) : '';
    
    // Validate required parameters
    if (empty($startDate) || empty($endDate)) {
        echo json_encode(['success' => false, 'message' => 'Start date and end date are required']);
        exit();
    }
    
    // Initialize response data
    $response = [
        'success' => true,
        'startDate' => $startDate,
        'endDate' => $endDate,
        'customerInfo' => null,
        'summary' => [
            'openingBalance' => 0,
            'totalSales' => 0,
            'totalPayments' => 0,
            'closingBalance' => 0
        ],
        'transactions' => []
    ];
    
    // Get customer info if specific customer is selected
    if (!empty($customerId)) {
        $customerQuery = "SELECT c.ID, c.CustomerID, c.CustomerName, c.ContactPerson, c.Mobile, c.City, c.CurrentBalance 
                         FROM tblcustomers c 
                         WHERE c.ID = ?";
        $stmt = mysqli_prepare($con, $customerQuery);
        mysqli_stmt_bind_param($stmt, 'i', $customerId);
        mysqli_stmt_execute($stmt);
        $customerResult = mysqli_stmt_get_result($stmt);
        
        if ($customerRow = mysqli_fetch_assoc($customerResult)) {
            $response['customerInfo'] = $customerRow;
        }
        mysqli_stmt_close($stmt);
    }
    
    // Calculate opening balance (balance before start date)
    $openingBalanceQuery = "SELECT 
                               SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END) as TotalDebit,
                               SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END) as TotalCredit
                           FROM tblcustomer_accounts 
                           WHERE TransactionDate < ?";
    
    if (!empty($customerId)) {
        $openingBalanceQuery .= " AND CustomerID = ?";
    }
    
    $stmt = mysqli_prepare($con, $openingBalanceQuery);
    if (!empty($customerId)) {
        mysqli_stmt_bind_param($stmt, 'si', $startDate, $customerId);
    } else {
        mysqli_stmt_bind_param($stmt, 's', $startDate);
    }
    
    mysqli_stmt_execute($stmt);
    $obResult = mysqli_stmt_get_result($stmt);
    $obRow = mysqli_fetch_assoc($obResult);
    
    $openingDebit = floatval($obRow['TotalDebit'] ?? 0);
    $openingCredit = floatval($obRow['TotalCredit'] ?? 0);
    $openingBalance = $openingDebit - $openingCredit; // Positive = Customer owes us
    
    $response['summary']['openingBalance'] = $openingBalance;
    mysqli_stmt_close($stmt);
    
    // Get transactions for the period
    $transactionQuery = "SELECT 
                            ca.ID,
                            ca.CustomerID,
                            c.CustomerName,
                            c.Mobile,
                            c.City,
                            ca.TransactionDate,
                            ca.TransactionType,
                            ca.Amount,
                            ca.InvoiceNumber,
                            ca.Description,
                            ca.PaymentMode,
                            ca.ReferenceNumber,
                            CASE 
                                WHEN ca.TransactionType = 'Debit' THEN ca.Amount 
                                ELSE 0 
                            END as DebitAmount,
                            CASE 
                                WHEN ca.TransactionType = 'Credit' THEN ca.Amount 
                                ELSE 0 
                            END as CreditAmount
                        FROM tblcustomer_accounts ca
                        LEFT JOIN tblcustomers c ON ca.CustomerID = c.ID
                        WHERE ca.TransactionDate BETWEEN ? AND ?";
    
    if (!empty($customerId)) {
        $transactionQuery .= " AND ca.CustomerID = ?";
    }
    
    $transactionQuery .= " ORDER BY ca.TransactionDate ASC, ca.ID ASC";
    
    $stmt = mysqli_prepare($con, $transactionQuery);
    if (!empty($customerId)) {
        mysqli_stmt_bind_param($stmt, 'ssi', $startDate, $endDate, $customerId);
    } else {
        mysqli_stmt_bind_param($stmt, 'ss', $startDate, $endDate);
    }
    
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    $totalDebit = 0;
    $totalCredit = 0;
    
    while ($row = mysqli_fetch_assoc($result)) {
        $response['transactions'][] = [
            'ID' => $row['ID'],
            'TransactionDate' => $row['TransactionDate'],
            'CustomerName' => $row['CustomerName'] ?? 'Unknown',
            'Mobile' => $row['Mobile'] ?? '',
            'City' => $row['City'] ?? '',
            'TransactionType' => $row['TransactionType'],
            'InvoiceNumber' => $row['InvoiceNumber'] ?? '',
            'ReferenceNumber' => $row['ReferenceNumber'] ?? '',
            'Description' => $row['Description'] ?? '',
            'PaymentMode' => $row['PaymentMode'] ?? '',
            'DebitAmount' => floatval($row['DebitAmount']),
            'CreditAmount' => floatval($row['CreditAmount']),
            'Amount' => floatval($row['Amount'])
        ];
        
        $totalDebit += floatval($row['DebitAmount']);
        $totalCredit += floatval($row['CreditAmount']);
    }
    
    mysqli_stmt_close($stmt);
    
    // Calculate summary
    $response['summary']['totalSales'] = $totalDebit;
    $response['summary']['totalPayments'] = $totalCredit;
    $response['summary']['closingBalance'] = $openingBalance + $totalDebit - $totalCredit;
    
    echo json_encode($response);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
