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

header('Content-Type: application/json');

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

    if (!isset($dbh) || !$dbh) {
        throw new Exception('Database connection not available');
    }

    $saleNumber = isset($_GET['sale_number']) ? trim($_GET['sale_number']) : '';
    $includeItems = isset($_GET['include_items']) && $_GET['include_items'] === 'true';

    if ($saleNumber === '') {
        throw new Exception('sale_number is required');
    }

    // Detect available customer columns (Mobile / MobileNumber, Area)
    $columns = [];
    try {
        $colStmt = $dbh->query("SHOW COLUMNS FROM tblcustomers");
        $columns = $colStmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e) {
        $columns = [];
    }
    $mobileSelect = "'' AS Mobile,";
    if (in_array('Mobile', $columns)) {
        $mobileSelect = 'c.Mobile AS Mobile,';
    } elseif (in_array('MobileNumber', $columns)) {
        $mobileSelect = 'c.MobileNumber AS Mobile,';
    }
    $areaSelect = "'' AS Area,";
    if (in_array('Area', $columns)) {
        $areaSelect = 'c.Area AS Area,';
    }

    // Get sale details
    $query = "
        SELECT 
            ps.ID,
            ps.SaleNumber,
            ps.SaleDate,
            ps.SaleTime,
            ps.CustomerID,
            c.CustomerName,
            $areaSelect
            $mobileSelect
            ps.SubTotal,
            ps.DiscountAmount,
            ps.TotalAmount,
            ps.PaidAmount,
            ps.BalanceAmount,
            ps.ChangeAmount,
            ps.PaymentMethod,
            ps.ReferenceNumber,
            ps.Notes,
            ps.PaymentStatus,
            ps.SaleStatus,
            ps.CashierName,
            ps.CreatedAt,
            ps.UpdatedAt
        FROM tblpossales ps
        LEFT JOIN tblcustomers c ON ps.CustomerID = c.ID
        WHERE ps.SaleNumber = ?
        LIMIT 1
    ";

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

    if (!$sale) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Sale not found']);
        exit();
    }

    // Include items if requested
    if ($includeItems) {
        $itemsQuery = "
            SELECT 
                psi.ID,
                psi.ProductID,
                psi.ProductName,
                psi.ProductCode,
                psi.Quantity,
                psi.UnitPrice,
                psi.LineTotal
            FROM tblpossaleitems psi
            WHERE psi.SaleID = ?
            ORDER BY psi.ID
        ";
        $stmt = $dbh->prepare($itemsQuery);
        $stmt->execute([$sale['ID']]);
        $sale['items'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    echo json_encode(['success' => true, 'data' => $sale]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
