<?php
/**
 * Search Sales AJAX Endpoint
 * LandSales Pro - Search sales with autocomplete
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

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

initSecureSession();

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
$search = trim($_GET['q'] ?? '');
$limit = min(intval($_GET['limit'] ?? 20), 50);
$onlyWithBalance = isset($_GET['with_balance']) && $_GET['with_balance'] === '1';

// Build search query
$whereClause = "WHERE s.user_id = ? AND s.status = 'active'";
$params = [$userId];
$types = 'i';

if ($onlyWithBalance) {
    $whereClause .= " HAVING balance > 0";
}

if (strlen($search) >= 1) {
    $searchTerm = "%{$search}%";
    $whereClause .= " AND (
        s.sale_number LIKE ? OR
        b.full_name LIKE ? OR
        b.phone LIKE ? OR
        p.plot_number LIKE ? OR
        pr.name LIKE ?
    )";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'sssss';
}

$sql = "SELECT s.id, s.sale_number, s.total_price, s.sale_date,
        b.full_name as buyer_name, b.phone as buyer_phone,
        p.plot_number, pr.name as project_name,
        (s.total_price - COALESCE((SELECT SUM(amount) FROM payments WHERE sale_id = s.id AND status = 'confirmed'), 0)) as balance
        FROM sales s
        JOIN buyers b ON s.buyer_id = b.id
        JOIN plots p ON s.plot_id = p.id
        JOIN projects pr ON p.project_id = pr.id
        {$whereClause}
        ORDER BY s.sale_date DESC
        LIMIT {$limit}";

$results = db_fetch_all($sql, $types, $params);

$formatted = [];
foreach ($results as $sale) {
    // Skip sales with no balance if filter is active
    if ($onlyWithBalance && $sale['balance'] <= 0) {
        continue;
    }

    $formatted[] = [
        'id' => $sale['id'],
        'text' => $sale['sale_number'] . ' - ' . $sale['buyer_name'] . ' - Plot ' . $sale['plot_number'],
        'sale_number' => $sale['sale_number'],
        'buyer_name' => $sale['buyer_name'],
        'buyer_phone' => $sale['buyer_phone'],
        'plot_number' => $sale['plot_number'],
        'project_name' => $sale['project_name'],
        'total_price' => $sale['total_price'],
        'balance' => $sale['balance'],
        'balance_formatted' => number_format($sale['balance']),
        'total_formatted' => number_format($sale['total_price'])
    ];
}

echo json_encode([
    'success' => true,
    'results' => $formatted
]);
