<?php
include_once('../includes/config.php');

try {
    $paymentId = $_GET['id'] ?? '';
    $includeItems = isset($_GET['include_items']) && $_GET['include_items'] === 'true';

    if (empty($paymentId)) {
        throw new Exception('Payment ID is required');
    }

    // Get POS sale details with customer information
    // Detect available columns in tblcustomers
    $mobileExists = false;
    $emailExists = false;
    try {
        $colCheck = $dbh->query("SHOW COLUMNS FROM tblcustomers");
        $columns = $colCheck->fetchAll(PDO::FETCH_COLUMN);
        $mobileExists = in_array('Mobile', $columns) || in_array('MobileNumber', $columns);
        $emailExists = in_array('Email', $columns);
    } catch (Exception $e) { /* ignore */ }
    
    $mobileSelect = '';
    if (in_array('Mobile', $columns ?? [])) {
        $mobileSelect = 'c.Mobile AS MobileNumber,';
    } elseif (in_array('MobileNumber', $columns ?? [])) {
        $mobileSelect = 'c.MobileNumber,';
    } else {
        $mobileSelect = "'' AS MobileNumber,";
    }
    
    $emailSelect = $emailExists ? 'c.Email,' : "'' AS Email,";

    $query = "
        SELECT 
            ps.ID,
            ps.SaleNumber,
            ps.SaleDate as TransactionDate,
            ps.SaleTime,
            ps.CustomerID,
            c.CustomerName,
            $mobileSelect
            $emailSelect
            ps.SubTotal,
            ps.DiscountAmount,
            ps.TotalAmount as Amount,
            ps.PaidAmount,
            ps.BalanceAmount,
            ps.ChangeAmount,
            ps.PaymentMethod,
            ps.ReferenceNumber,
            ps.Notes as Description,
            ps.PaymentStatus as Status,
            ps.SaleStatus,
            ps.CashierName,
            ps.CreatedAt,
            ps.UpdatedAt
        FROM tblpossales ps
        LEFT JOIN tblcustomers c ON ps.CustomerID = c.ID
        WHERE ps.ID = ?
    ";

    $stmt = $dbh->prepare($query);
    $stmt->execute([$paymentId]);
    $payment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$payment) {
        throw new Exception('Sale record not found');
    }

    // Get items if requested
    if ($includeItems) {
        $itemsQuery = "
            SELECT 
                psi.ID,
                psi.ProductID as RiceBagID,
                psi.ProductName,
                psi.ProductCode,
                psi.Quantity,
                psi.UnitPrice as Rate,
                psi.LineTotal as TotalAmount,
                psi.DiscountAmount,
                psi.TaxAmount
            FROM tblpossaleitems psi
            WHERE psi.SaleID = ?
            ORDER BY psi.ID
        ";

        $stmt = $dbh->prepare($itemsQuery);
        $stmt->execute([$paymentId]);
        $payment['items'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'data' => $payment
    ]);

} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
