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

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

// Set content type to JSON
header('Content-Type: application/json');

try {
    // Get parameters
    $searchTerm = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';
    $filterType = isset($_GET['type']) ? mysqli_real_escape_string($con, $_GET['type']) : '';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $isSuggestions = isset($_GET['suggestions']) && $_GET['suggestions'] === '1';
    
    // Build WHERE clause
    $whereConditions = ['c.IsActive = 1'];
    
    // Add search conditions
    if (!empty($searchTerm)) {
        $whereConditions[] = "(
            c.CustomerName LIKE '%$searchTerm%' 
            OR c.Mobile LIKE '%$searchTerm%'
            OR c.AlternativePhone LIKE '%$searchTerm%'
            OR c.Area LIKE '%$searchTerm%'
            OR c.Address LIKE '%$searchTerm%'
        )";
    }
    
    // Add type filter
    if (!empty($filterType)) {
        $whereConditions[] = "c.CustomerType = '$filterType'";
    }
    
    $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
    
    // Count total matching records for suggestions
    $countQuery = "SELECT COUNT(*) as total FROM tblcustomers c $whereClause";
    $countResult = mysqli_query($con, $countQuery);
    $totalRecords = mysqli_fetch_assoc($countResult)['total'];
    
    // Build main query
    $query = "
        SELECT 
            c.ID,
            c.CustomerName,
            c.Mobile,
            c.AlternativePhone,
            c.Area,
            c.CustomerType,
            c.Address,
            c.GmapLocation,
            c.CreatedDate,
            COALESCE(
                (SELECT SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE -Amount END) 
                 FROM tblcustomerpayments cp 
                 WHERE cp.CustomerID = c.ID AND cp.Status = 'Completed' AND cp.IsActive = 1), 0
            ) as Outstanding
        FROM tblcustomers c
        $whereClause
        ORDER BY 
            CASE 
                WHEN c.CustomerName LIKE '$searchTerm%' THEN 1
                WHEN c.Mobile LIKE '$searchTerm%' THEN 2
                ELSE 3
            END,
            c.CustomerName ASC
        LIMIT $limit
    ";
    
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        throw new Exception('Database query failed: ' . mysqli_error($con));
    }
    
    $customers = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $customer = [
            'ID' => (int)$row['ID'],
            'CustomerName' => $row['CustomerName'],
            'Mobile' => $row['Mobile'],
            'AlternativePhone' => $row['AlternativePhone'],
            'Area' => $row['Area'],
            'CustomerType' => $row['CustomerType'],
            'Address' => $row['Address'],
            'GmapLocation' => $row['GmapLocation'],
            'Outstanding' => (float)$row['Outstanding'],
            'CreatedDate' => $row['CreatedDate']
        ];
        
        // Add display format for dropdowns
        if (!$isSuggestions) {
            $customer['display'] = $row['CustomerName'] . ' (' . $row['Mobile'] . ') - ' . $row['Area'];
        }
        
        $customers[] = $customer;
    }
    
    // Response format
    $response = [
        'success' => true,
        'data' => $customers,
        'count' => count($customers),
        'total' => (int)$totalRecords
    ];
    
    // Add search metadata for suggestions
    if ($isSuggestions && !empty($searchTerm)) {
        $response['searchTerm'] = $searchTerm;
        $response['hasMore'] = $totalRecords > $limit;
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log('Customer search error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
